Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix: clear conversation notifications on manual entry (#851)
Genercedd67986dc5
diff --git a/scripts/ci/mobile-system-notification.test.ts b/scripts/ci/mobile-system-notification.test.tsindex e1795d3bd..f60258f26 100644--- a/scripts/ci/mobile-system-notification.test.ts+++ b/scripts/ci/mobile-system-notification.test.ts@@ -26,6 +26,7 @@ const commands = ["mobile_system_notification_acknowledge_registration","mobile_system_notification_take_activation","mobile_system_notification_dismiss",+ "mobile_system_notification_dismiss_conversation","mobile_system_notification_listen","mobile_system_notification_unlisten",]@@ -67,7 +68,7 @@ const iosEntitlements = readTauri(const mobileRelease = readRoot(".github/workflows/mobile-release.yml")describe("mobile system notification contract", () => {- it("grants only the guarded eight-command API to trusted mobile WebViews", () => {+ it("grants only the guarded nine-command API to trusted mobile WebViews", () => {const expected = {windows: ["main"],platforms: ["android", "iOS"],@@ -113,6 +114,7 @@ describe("mobile system notification contract", () => {expect(readPlugin("build.rs")).toContain('"acknowledgeRegistration"')expect(readPlugin("build.rs")).toContain('"takeActivation"')expect(readPlugin("build.rs")).toContain('"dismissNotification"')+ expect(readPlugin("build.rs")).toContain('"dismissConversation"')const webAdapter = readRoot("src/web/src/lib/community/mobile-system-notification.ts",)@@ -120,6 +122,7 @@ describe("mobile system notification contract", () => {expect(webAdapter).toContain('credentials: "same-origin"')expect(webAdapter).toContain('"mobile_system_notification_acknowledge_registration"')expect(webAdapter).toContain('"mobile_system_notification_dismiss"')+ expect(webAdapter).toContain('"mobile_system_notification_dismiss_conversation"')})it("locks Android FCM delivery, durable state, and credential-free builds", () => {@@ -152,8 +155,16 @@ describe("mobile system notification contract", () => {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)")+ expect(androidRoute).toContain('"alook:v2:$viewerUserId:$targetId:$notificationId"')+ expect(androidRoute).toContain("mobilePushNotificationTagMatchesNotification")+ expect(androidRoute).toContain("mobilePushNotificationTagMatchesConversation")+ expect(androidPlugin).toContain("manager.activeNotifications")+ expect(androidPlugin).toContain(+ "mobilePushNotificationTagMatchesNotification(notification.tag, args.notificationId)",+ )+ expect(androidPlugin).toContain("fun dismissConversation")+ expect(androidPlugin).toContain("mobilePushNotificationTagMatchesConversation(")+ expect(androidPlugin).toContain("manager.cancel(it.tag, it.id)")})it("locks iOS APNs callbacks, foreground/tap handling, and production entitlement", () => {@@ -166,7 +177,11 @@ describe("mobile system notification contract", () => {expect(iosPlugin).toContain("MobilePushStore")expect(iosPlugin).toContain("removeDeliveredNotifications")expect(iosPlugin).toContain("response.notification.request.identifier")- expect(iosPlugin).toContain("takeDeliveredNotificationIdentifier")+ expect(iosPlugin).toContain("deliveredNotificationIdentifier(")+ expect(iosPlugin).toContain("@objc public func dismissConversation")+ expect(iosPlugin).toContain("mobilePushDeliveredNotificationIdentifiers(")+ expect(iosPlugin).toContain("center.removeDeliveredNotifications(withIdentifiers: identifiers)")+ expect(iosPlugin).toContain("stillDelivered.isEmpty")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.tsindex b66e5a4f3..6e68bc067 100644--- a/scripts/ci/system-notifications-desktop.test.ts+++ b/scripts/ci/system-notifications-desktop.test.ts@@ -16,6 +16,7 @@ const desktopCommands = ["desktop_system_notification_take_activation","desktop_system_notification_retry_activation","desktop_system_notification_dismiss",+ "desktop_system_notification_dismiss_conversation","desktop_system_notification_unlisten",]diff --git a/src/desktop/src-tauri/build.rs b/src/desktop/src-tauri/build.rsindex 84e2e69cc..619fb2350 100644--- a/src/desktop/src-tauri/build.rs+++ b/src/desktop/src-tauri/build.rs@@ -15,6 +15,7 @@ fn main() {"desktop_system_notification_take_activation","desktop_system_notification_retry_activation","desktop_system_notification_dismiss",+ "desktop_system_notification_dismiss_conversation","desktop_system_notification_unlisten","mobile_share_image_copy","mobile_share_image_save",@@ -24,6 +25,7 @@ fn main() {"mobile_system_notification_acknowledge_registration","mobile_system_notification_take_activation","mobile_system_notification_dismiss",+ "mobile_system_notification_dismiss_conversation","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.tomlindex a1d609ad3..885ad1efb 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_retry_activation", "desktop_system_notification_dismiss", "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_dismiss_conversation", "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.tomlindex a07d4c559..877315259 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_dismiss", "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_dismiss_conversation", "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.ktindex 2736554a7..0984ef397 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@@ -28,6 +28,7 @@ class AlookFirebaseMessagingService : FirebaseMessagingService() {launchIntent.putExtra("notificationId", route.notificationId)launchIntent.putExtra("messageId", route.messageId)launchIntent.putExtra("targetId", route.targetId)+ route.viewerUserId?.let { launchIntent.putExtra("viewerUserId", it) }val requestCode = mobilePushNotificationRequestCode(route.notificationId)val pendingIntent = PendingIntent.getActivity(this,@@ -44,7 +45,9 @@ class AlookFirebaseMessagingService : FirebaseMessagingService() {.setGroup(route.targetId).build()NotificationManagerCompat.from(this).notify(- route.notificationId,+ route.viewerUserId?.let {+ mobilePushNotificationTag(it, route.targetId, route.notificationId)+ } ?: route.notificationId,requestCode,notification,)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.ktindex 94eb0bfee..1abc903da 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@@ -31,6 +31,12 @@ class DismissNotificationArgs {lateinit var notificationId: String}+@InvokeArg+class DismissConversationArgs {+ lateinit var viewerUserId: String+ lateinit var targetId: String+}+@InvokeArgclass MobilePushListenArgs {lateinit var channel: Channel@@ -164,9 +170,68 @@ class MobilePushPlugin(private val activity: Activity) : Plugin(activity) {invoke.reject("Notification dismissal is invalid", "invalid_request")return}- val requestCode = mobilePushNotificationRequestCode(args.notificationId)- NotificationManagerCompat.from(activity).cancel(args.notificationId, requestCode)- invoke.resolve()+ if (MobilePushRoute.create(args.notificationId, "message", "target") == null) {+ invoke.reject("Notification dismissal is invalid", "invalid_request")+ return+ }+ val manager = activity.getSystemService(NotificationManager::class.java)+ if (manager == null) {+ invoke.reject("Notification manager is unavailable", "notification_unavailable")+ return+ }+ val matches = manager.activeNotifications.filter { notification ->+ mobilePushNotificationTagMatchesNotification(notification.tag, args.notificationId)+ }+ matches.forEach { manager.cancel(it.tag, it.id) }+ val remains = manager.activeNotifications.any { notification ->+ mobilePushNotificationTagMatchesNotification(notification.tag, args.notificationId)+ }+ if (remains) {+ invoke.reject("Notification remains delivered", "notification_unavailable")+ } else {+ invoke.resolve()+ }+ }++ @Command+ fun dismissConversation(invoke: Invoke) {+ val args = try {+ invoke.parseArgs(DismissConversationArgs::class.java)+ } catch (_: Exception) {+ invoke.reject("Conversation dismissal is invalid", "invalid_request")+ return+ }+ if (!validMobilePushTargetId(args.viewerUserId)+ || !validMobilePushTargetId(args.targetId)+ ) {+ invoke.reject("Conversation dismissal is invalid", "invalid_request")+ return+ }+ val manager = activity.getSystemService(NotificationManager::class.java)+ if (manager == null) {+ invoke.reject("Notification manager is unavailable", "notification_unavailable")+ return+ }+ manager.activeNotifications+ .filter {+ mobilePushNotificationTagMatchesConversation(+ it.tag,+ args.viewerUserId,+ args.targetId,+ )+ }+ .forEach { manager.cancel(it.tag, it.id) }+ if (manager.activeNotifications.any {+ mobilePushNotificationTagMatchesConversation(+ it.tag,+ args.viewerUserId,+ args.targetId,+ )+ }) {+ invoke.reject("Conversation notifications remain delivered", "notification_unavailable")+ } else {+ invoke.resolve()+ }}@Command@@ -224,6 +289,7 @@ class MobilePushPlugin(private val activity: Activity) : Plugin(activity) {it.getStringExtra("notificationId"),it.getStringExtra("messageId"),it.getStringExtra("targetId"),+ it.getStringExtra("viewerUserId"),)} ?: returntry {@@ -231,6 +297,7 @@ class MobilePushPlugin(private val activity: Activity) : Plugin(activity) {intent.removeExtra("notificationId")intent.removeExtra("messageId")intent.removeExtra("targetId")+ intent.removeExtra("viewerUserId")signal()} catch (_: Exception) {returndiff --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.ktindex f16577994..14504aac1 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@@ -10,15 +10,74 @@ internal fun mobilePushNotificationRequestCode(notificationId: String): Int =internal fun mobilePushNotificationAction(packageName: String, notificationId: String): String ="$packageName.mobilepush.notification.$notificationId"+data class MobilePushNotificationTag(+ val viewerUserId: String,+ val targetId: String,+ val notificationId: String,+)++internal fun mobilePushNotificationTag(+ viewerUserId: String,+ targetId: String,+ notificationId: String,+): String = "alook:v2:$viewerUserId:$targetId:$notificationId"++internal fun validMobilePushTargetId(value: String): Boolean =+ Regex("^[A-Za-z0-9_-]{1,128}$").matches(value)++internal fun parseMobilePushNotificationTag(value: String?): MobilePushNotificationTag? {+ if (value == null) return null+ val parts = value.split(':')+ if (parts.size != 5 || parts[0] != "alook" || parts[1] != "v2") return null+ val route = MobilePushRoute.create(parts[4], "message", parts[3], parts[2]) ?: return null+ return MobilePushNotificationTag(+ route.viewerUserId ?: return null,+ route.targetId,+ route.notificationId,+ )+}++internal fun mobilePushNotificationTagMatchesConversation(+ value: String?,+ viewerUserId: String,+ targetId: String,+): Boolean {+ if (!validMobilePushTargetId(viewerUserId) || !validMobilePushTargetId(targetId)) return false+ val parsed = parseMobilePushNotificationTag(value) ?: return false+ return parsed.viewerUserId == viewerUserId && parsed.targetId == targetId+}++private fun legacyMobilePushNotificationId(value: String?): String? {+ if (value == null) return null+ val parts = value.split(':')+ if (parts.size != 3 || parts[0] != "alook" || !validMobilePushTargetId(parts[1])) return null+ return MobilePushRoute.create(parts[2], "message", parts[1])?.notificationId+}++internal fun mobilePushNotificationTagMatchesNotification(+ value: String?,+ notificationId: String,+): Boolean {+ val expected = MobilePushRoute.create(notificationId, "message", "target")?.notificationId+ ?: return false+ if (value == expected) return true+ return parseMobilePushNotificationTag(value)?.notificationId == expected+ || legacyMobilePushNotificationId(value) == expected+}+data class MobilePushRoute(val notificationId: String,val messageId: String,val targetId: String,+ val viewerUserId: String? = null,) {companion object {- private val safeId = Regex("^[A-Za-z0-9_-]{1,128}$")-- fun create(notificationId: String?, messageId: String?, targetId: String?): MobilePushRoute? {+ fun create(+ notificationId: String?,+ messageId: String?,+ targetId: String?,+ viewerUserId: String? = null,+ ): MobilePushRoute? {if (notificationId == null || messageId == null || targetId == null) return nullval canonicalNotificationId = try {UUID.fromString(notificationId).toString()@@ -26,14 +85,16 @@ data class MobilePushRoute(return null}if (canonicalNotificationId != notificationId.lowercase()) return null- if (!safeId.matches(messageId) || !safeId.matches(targetId)) return null- return MobilePushRoute(canonicalNotificationId, messageId, targetId)+ if (!validMobilePushTargetId(messageId) || !validMobilePushTargetId(targetId)) return null+ if (viewerUserId != null && !validMobilePushTargetId(viewerUserId)) return null+ return MobilePushRoute(canonicalNotificationId, messageId, targetId, viewerUserId)}fun fromMap(values: Map<String, String>): MobilePushRoute? = create(values["notificationId"],values["messageId"],values["targetId"],+ values["viewerUserId"],)}}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.ktindex 96cb07d21..6a16acec6 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@@ -22,6 +22,96 @@ class MobilePushRouteTest {assertTrue(mobilePushNotificationRequestCode(notificationId) >= 0)}+ @Test+ fun roundTripsOneUniqueConversationTagWithoutCollapsingSiblingNotifications() {+ val first = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"+ val second = "5f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"+ val firstTag = mobilePushNotificationTag("viewer_1", "channel_1", first)+ val secondTag = mobilePushNotificationTag("viewer_1", "channel_1", second)++ assertEquals("alook:v2:viewer_1:channel_1:$first", firstTag)+ assertTrue(firstTag != secondTag)+ assertEquals(+ MobilePushNotificationTag("viewer_1", "channel_1", first),+ parseMobilePushNotificationTag(firstTag),+ )+ }++ @Test+ fun rejectsMalformedV2TagsWithoutGuessingLegacyValues() {+ val notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"+ listOf(+ notificationId,+ "alook:channel_1:$notificationId",+ "alook:v2:viewer_1:channel_1",+ "alook:v2::channel_1:$notificationId",+ "alook:v2:viewer_1::${notificationId}",+ "alook:v2:viewer_1:channel_1:",+ "alook:v2:../viewer:channel_1:$notificationId",+ "alook:v2:viewer_1:../channel:$notificationId",+ "alook:v2:viewer_1:channel_1:bad",+ "alook:v2:viewer_1:channel_1:$notificationId:extra",+ ).forEach { assertNull(parseMobilePushNotificationTag(it)) }+ }++ @Test+ fun bulkSelectionMatchesOnlyTheExactViewerAndConversation() {+ val b1 = mobilePushNotificationTag(+ "viewer_b",+ "channel_1",+ "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ )+ val b2 = mobilePushNotificationTag(+ "viewer_b",+ "channel_1",+ "5f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ )+ val a1 = mobilePushNotificationTag(+ "viewer_a",+ "channel_1",+ "6f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ )+ val a2 = mobilePushNotificationTag(+ "viewer_a",+ "channel_1",+ "7f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ )+ val other = mobilePushNotificationTag(+ "viewer_b",+ "channel_2",+ "8f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ )++ assertTrue(mobilePushNotificationTagMatchesConversation(b1, "viewer_b", "channel_1"))+ assertTrue(mobilePushNotificationTagMatchesConversation(b2, "viewer_b", "channel_1"))+ assertFalse(mobilePushNotificationTagMatchesConversation(a1, "viewer_b", "channel_1"))+ assertFalse(mobilePushNotificationTagMatchesConversation(a2, "viewer_b", "channel_1"))+ assertFalse(mobilePushNotificationTagMatchesConversation(other, "viewer_b", "channel_1"))+ assertFalse(mobilePushNotificationTagMatchesConversation(+ "alook:channel_1:4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "viewer_b",+ "channel_1",+ ))+ }++ @Test+ fun singleIdSelectionRecognizesV2AndLegacyTagsOnlyByExactId() {+ val notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"+ assertTrue(mobilePushNotificationTagMatchesNotification(+ mobilePushNotificationTag("viewer_1", "channel_1", notificationId),+ notificationId,+ ))+ assertTrue(mobilePushNotificationTagMatchesNotification(+ "alook:channel_1:$notificationId",+ notificationId,+ ))+ assertTrue(mobilePushNotificationTagMatchesNotification(notificationId, notificationId))+ assertFalse(mobilePushNotificationTagMatchesNotification(+ "alook:channel_1:5f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ notificationId,+ ))+ }+@Testfun keepsPendingIntentIdentityExactAcrossRequestCodeCollisions() {val first = "4f5dff4f-8ecf-4e12-8df0-09deeca44cad"@@ -42,13 +132,22 @@ class MobilePushRouteTest {"4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e","message_1","channel-2",+ "viewer_1",)assertEquals("message_1", route?.messageId)- assertNull(MobilePushRoute.create("bad", "message_1", "channel-2"))+ assertEquals("viewer_1", route?.viewerUserId)+ assertNull(MobilePushRoute.create("bad", "message_1", "channel-2", "viewer_1"))assertNull(MobilePushRoute.create("4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e","../message","channel-2",+ "viewer_1",+ ))+ assertNull(MobilePushRoute.create(+ "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "message_1",+ "channel-2",+ "../viewer",))}@@ -58,6 +157,7 @@ class MobilePushRouteTest {"notificationId" to "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e","messageId" to "message_1","targetId" to "channel_2",+ "viewerUserId" to "viewer_1","from" to "transport",))assertEquals(@@ -65,8 +165,14 @@ class MobilePushRouteTest {"4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e","message_1","channel_2",+ "viewer_1",),route,)+ assertEquals(null, MobilePushRoute.fromMap(mapOf(+ "notificationId" to "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId" to "message_1",+ "targetId" to "channel_2",+ ))?.viewerUserId)}}diff --git a/src/desktop/src-tauri/plugins/mobile-push/build.rs b/src/desktop/src-tauri/plugins/mobile-push/build.rsindex 3689a46ec..013b9540c 100644--- a/src/desktop/src-tauri/plugins/mobile-push/build.rs+++ b/src/desktop/src-tauri/plugins/mobile-push/build.rs@@ -4,6 +4,7 @@ fn main() {"acknowledgeRegistration","takeActivation","dismissNotification",+ "dismissConversation","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.swiftindex d054d0013..dfe20b46a 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@@ -5,19 +5,38 @@ import UIKitimport UserNotificationsimport WebKit+private let mobilePushSafeId = try! NSRegularExpression(+ pattern: "^[A-Za-z0-9_-]{1,128}$"+)++func mobilePushValidTargetId(_ value: String) -> Bool {+ let range = NSRange(value.startIndex..<value.endIndex, in: value)+ return mobilePushSafeId.firstMatch(in: value, range: range)?.range == range+}+struct MobilePushRoute: Codable, Equatable {let notificationId: Stringlet messageId: Stringlet targetId: String+ let viewerUserId: String?- private static let safeId = try! NSRegularExpression(- pattern: "^[A-Za-z0-9_-]{1,128}$"- )+ init(+ notificationId: String,+ messageId: String,+ targetId: String,+ viewerUserId: String? = nil+ ) {+ self.notificationId = notificationId+ self.messageId = messageId+ self.targetId = targetId+ self.viewerUserId = viewerUserId+ }static func create(notificationId: String?,messageId: String?,- targetId: String?+ targetId: String?,+ viewerUserId: String? = nil) -> MobilePushRoute? {guard let notificationId = notificationId,let messageId = messageId,@@ -25,26 +44,47 @@ struct MobilePushRoute: Codable, Equatable {let uuid = UUID(uuidString: notificationId),uuid.uuidString.lowercased() == notificationId.lowercased(),matchesSafeId(messageId),- matchesSafeId(targetId)+ matchesSafeId(targetId),+ viewerUserId == nil || matchesSafeId(viewerUserId!)else { return nil }return MobilePushRoute(notificationId: uuid.uuidString.lowercased(),messageId: messageId,- targetId: targetId+ targetId: targetId,+ viewerUserId: viewerUserId)}static func from(_ values: [AnyHashable: Any]) -> MobilePushRoute? {- create(+ let viewerUserId = values["viewerUserId"]+ guard viewerUserId == nil || viewerUserId is String else { return nil }+ return create(notificationId: values["notificationId"] as? String,messageId: values["messageId"] as? String,- targetId: values["targetId"] as? String+ targetId: values["targetId"] as? String,+ viewerUserId: viewerUserId as? String)}private static func matchesSafeId(_ value: String) -> Bool {- let range = NSRange(value.startIndex..<value.endIndex, in: value)- return safeId.firstMatch(in: value, range: range)?.range == range+ mobilePushValidTargetId(value)+ }+}++func mobilePushDeliveredNotificationIdentifiers(+ viewerUserId: String,+ targetId: String,+ delivered: [(String, [AnyHashable: Any])]+) -> [String] {+ guard mobilePushValidTargetId(viewerUserId),+ mobilePushValidTargetId(targetId)+ else { return [] }+ return delivered.compactMap { identifier, userInfo in+ guard let route = MobilePushRoute.from(userInfo),+ route.viewerUserId == viewerUserId,+ route.targetId == targetId+ else { return nil }+ return identifier}}@@ -130,6 +170,7 @@ final class MobilePushStore {defaults.set(route.notificationId, forKey: Keys.pendingNotificationId)defaults.set(route.messageId, forKey: Keys.pendingMessageId)defaults.set(route.targetId, forKey: Keys.pendingTargetId)+ defaults.set(route.viewerUserId, forKey: Keys.pendingViewerUserId)defaults.set(route.notificationId, forKey: Keys.dismissNotificationId)defaults.set(deliveredNotificationIdentifier, forKey: Keys.deliveredNotificationIdentifier)}@@ -140,24 +181,33 @@ final class MobilePushStore {let route = MobilePushRoute.create(notificationId: defaults.string(forKey: Keys.pendingNotificationId),messageId: defaults.string(forKey: Keys.pendingMessageId),- targetId: defaults.string(forKey: Keys.pendingTargetId)+ targetId: defaults.string(forKey: Keys.pendingTargetId),+ viewerUserId: defaults.string(forKey: Keys.pendingViewerUserId))defaults.removeObject(forKey: Keys.pendingNotificationId)defaults.removeObject(forKey: Keys.pendingMessageId)defaults.removeObject(forKey: Keys.pendingTargetId)+ defaults.removeObject(forKey: Keys.pendingViewerUserId)return route}- func takeDeliveredNotificationIdentifier(for notificationId: String) -> String? {+ func deliveredNotificationIdentifier(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)+ return defaults.string(forKey: Keys.deliveredNotificationIdentifier)+ }++ func completeDeliveredNotificationIdentifier(for notificationId: String) {+ lock.lock()+ defer { lock.unlock() }+ guard defaults.string(forKey: Keys.dismissNotificationId) == notificationId else {+ return+ }defaults.removeObject(forKey: Keys.dismissNotificationId)defaults.removeObject(forKey: Keys.deliveredNotificationIdentifier)- return deliveredIdentifier}private func unlockedRegistration() -> MobilePushRegistrationState {@@ -174,6 +224,7 @@ final class MobilePushStore {static let pendingNotificationId = "alook.mobilePush.pendingNotificationId"static let pendingMessageId = "alook.mobilePush.pendingMessageId"static let pendingTargetId = "alook.mobilePush.pendingTargetId"+ static let pendingViewerUserId = "alook.mobilePush.pendingViewerUserId"static let dismissNotificationId = "alook.mobilePush.dismissNotificationId"static let deliveredNotificationIdentifier = "alook.mobilePush.deliveredNotificationIdentifier"}@@ -336,6 +387,11 @@ private struct DismissNotificationArgs: Decodable {let notificationId: String}+private struct DismissConversationArgs: Decodable {+ let viewerUserId: String+ let targetId: String+}+private struct ListenArgs: Decodable {let channel: Channel}@@ -428,18 +484,69 @@ final class MobilePushPlugin: Plugin {@objc public func dismissNotification(_ invoke: Invoke) {do {let args = try invoke.parseArgs(DismissNotificationArgs.self)- let identifier = bridge.store.takeDeliveredNotificationIdentifier(+ let identifier = bridge.store.deliveredNotificationIdentifier(for: args.notificationId) ?? args.notificationIdUNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [identifier])- invoke.resolve()+ UNUserNotificationCenter.current().getDeliveredNotifications { delivered in+ if delivered.contains(where: { $0.request.identifier == identifier }) {+ invoke.reject("Notification remains delivered", code: "notification_unavailable")+ } else {+ self.bridge.store.completeDeliveredNotificationIdentifier(+ for: args.notificationId+ )+ invoke.resolve()+ }+ }} catch {invoke.reject("Notification dismissal is invalid", code: "invalid_request")}}+ @objc public func dismissConversation(_ invoke: Invoke) {+ do {+ let args = try invoke.parseArgs(DismissConversationArgs.self)+ guard mobilePushValidTargetId(args.viewerUserId),+ mobilePushValidTargetId(args.targetId)+ else {+ invoke.reject("Conversation dismissal is invalid", code: "invalid_request")+ return+ }+ let center = UNUserNotificationCenter.current()+ center.getDeliveredNotifications { delivered in+ let identifiers = mobilePushDeliveredNotificationIdentifiers(+ viewerUserId: args.viewerUserId,+ targetId: args.targetId,+ delivered: delivered.map {+ ($0.request.identifier, $0.request.content.userInfo)+ }+ )+ center.removeDeliveredNotifications(withIdentifiers: identifiers)+ center.getDeliveredNotifications { remaining in+ let stillDelivered = mobilePushDeliveredNotificationIdentifiers(+ viewerUserId: args.viewerUserId,+ targetId: args.targetId,+ delivered: remaining.map {+ ($0.request.identifier, $0.request.content.userInfo)+ }+ )+ if stillDelivered.isEmpty {+ invoke.resolve()+ } else {+ invoke.reject(+ "Conversation notifications remain delivered",+ code: "notification_unavailable"+ )+ }+ }+ }+ } catch {+ invoke.reject("Conversation 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.swiftindex b11016d53..8784227fd 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@@ -7,23 +7,33 @@ final class MobilePushPluginTests: XCTestCase {MobilePushRoute.create(notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",messageId: "message_1",- targetId: "channel-2"+ targetId: "channel-2",+ viewerUserId: "viewer_1"),MobilePushRoute(notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",messageId: "message_1",- targetId: "channel-2"+ targetId: "channel-2",+ viewerUserId: "viewer_1"))XCTAssertNil(MobilePushRoute.create(notificationId: "bad",messageId: "message_1",- targetId: "channel-2"+ targetId: "channel-2",+ viewerUserId: "viewer_1"))XCTAssertNil(MobilePushRoute.create(notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",messageId: "../message",- targetId: "channel-2"+ targetId: "channel-2",+ viewerUserId: "viewer_1"+ ))+ XCTAssertNil(MobilePushRoute.create(+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ messageId: "message_1",+ targetId: "channel-2",+ viewerUserId: "../viewer"))}@@ -32,10 +42,77 @@ final class MobilePushPluginTests: XCTestCase {"notificationId": "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e","messageId": "message_1","targetId": "channel_2",+ "viewerUserId": "viewer_1","aps": ["transport": true],])XCTAssertEqual(route?.messageId, "message_1")XCTAssertEqual(route?.targetId, "channel_2")+ XCTAssertEqual(route?.viewerUserId, "viewer_1")+ XCTAssertNil(MobilePushRoute.from([+ "notificationId": "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId": "message_1",+ "targetId": "channel_2",+ "viewerUserId": 7,+ ]))+ XCTAssertNil(MobilePushRoute.from([+ "notificationId": "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId": "message_1",+ "targetId": "channel_2",+ ])?.viewerUserId)+ }++ func testDeliveredRouteSelectionMatchesOnlyExactViewerAndConversation() {+ let b1: [AnyHashable: Any] = [+ "notificationId": "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId": "message_1",+ "targetId": "channel_1",+ "viewerUserId": "viewer_b",+ ]+ let b2: [AnyHashable: Any] = [+ "notificationId": "5f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId": "message_2",+ "targetId": "channel_1",+ "viewerUserId": "viewer_b",+ ]+ let a1: [AnyHashable: Any] = [+ "notificationId": "6f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId": "message_3",+ "targetId": "channel_1",+ "viewerUserId": "viewer_a",+ ]+ let a2: [AnyHashable: Any] = [+ "notificationId": "7f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId": "message_4",+ "targetId": "channel_1",+ "viewerUserId": "viewer_a",+ ]+ let other: [AnyHashable: Any] = [+ "notificationId": "8f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId": "message_5",+ "targetId": "channel_2",+ "viewerUserId": "viewer_b",+ ]+ let legacy: [AnyHashable: Any] = [+ "notificationId": "9f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId": "message_6",+ "targetId": "channel_1",+ ]++ XCTAssertEqual(+ mobilePushDeliveredNotificationIdentifiers(+ viewerUserId: "viewer_b",+ targetId: "channel_1",+ delivered: [+ ("ios-b1", b1),+ ("ios-b2", b2),+ ("ios-a1", a1),+ ("ios-a2", a2),+ ("ios-other", other),+ ("ios-legacy", legacy),+ ]+ ),+ ["ios-b1", "ios-b2"]+ )}func testSuccessfulPostedTokenBecomesProofAcrossAConcurrentRotation() {@@ -73,11 +150,16 @@ final class MobilePushPluginTests: XCTestCase {store.saveActivation(route, deliveredNotificationIdentifier: "apns-delivered-1")XCTAssertEqual(store.takeActivation(), route)XCTAssertNil(store.takeActivation())- XCTAssertNil(store.takeDeliveredNotificationIdentifier(for: "another-notification"))+ XCTAssertNil(store.deliveredNotificationIdentifier(for: "another-notification"))+ XCTAssertEqual(+ store.deliveredNotificationIdentifier(for: route.notificationId),+ "apns-delivered-1"+ )XCTAssertEqual(- store.takeDeliveredNotificationIdentifier(for: route.notificationId),+ store.deliveredNotificationIdentifier(for: route.notificationId),"apns-delivered-1")- XCTAssertNil(store.takeDeliveredNotificationIdentifier(for: route.notificationId))+ store.completeDeliveredNotificationIdentifier(for: route.notificationId)+ XCTAssertNil(store.deliveredNotificationIdentifier(for: route.notificationId))}}diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/dismissConversation.toml b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/dismissConversation.tomlnew file mode 100644index 000000000..ef9bbdd66--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/dismissConversation.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-dismissConversation"+description = "Enables the dismissConversation command without any pre-configured scope."+commands.allow = ["dismissConversation"]++[[permission]]+identifier = "deny-dismissConversation"+description = "Denies the dismissConversation command without any pre-configured scope."+commands.deny = ["dismissConversation"]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.mdindex 652597971..2a62a0039 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-dismissConversation`++</td>+<td>++Enables the dismissConversation command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`mobile-push:deny-dismissConversation`++</td>+<td>++Denies the dismissConversation command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`mobile-push:allow-dismissNotification`</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.jsonindex 787fcbc2e..aae6a73e5 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 dismissConversation command without any pre-configured scope.",+ "type": "string",+ "const": "allow-dismissConversation",+ "markdownDescription": "Enables the dismissConversation command without any pre-configured scope."+ },+ {+ "description": "Denies the dismissConversation command without any pre-configured scope.",+ "type": "string",+ "const": "deny-dismissConversation",+ "markdownDescription": "Denies the dismissConversation command without any pre-configured scope."+ },{"description": "Enables the dismissNotification command without any pre-configured scope.","type": "string",diff --git a/src/desktop/src-tauri/plugins/mobile-push/src/lib.rs b/src/desktop/src-tauri/plugins/mobile-push/src/lib.rsindex d471a90b5..a2d4eaada 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, DismissRequest, ListenRequest, PermissionResponse,- RegistrationSnapshot, UnlistenRequest,+ AcknowledgeRequest, Activation, DismissConversationRequest, 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.rsindex 3f8d26870..d267b3aee 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, DismissRequest, Error, ListenRequest, PermissionResponse,- RegistrationSnapshot, UnlistenRequest,+ AcknowledgeRequest, Activation, DismissConversationRequest, DismissRequest, Error,+ ListenRequest, PermissionResponse, RegistrationSnapshot, UnlistenRequest,};use serde::de::DeserializeOwned;use tauri::{@@ -68,10 +68,24 @@ impl<R: Runtime> MobilePush<R> {}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 dismiss_conversation(+ &self,+ viewer_user_id: String,+ target_id: String,+ ) -> Result<(), Error> {self.0.run_mobile_plugin_async(- "dismissNotification",- DismissRequest { notification_id },+ "dismissConversation",+ DismissConversationRequest {+ viewer_user_id,+ target_id,+ },).await.map_err(Into::into)diff --git a/src/desktop/src-tauri/plugins/mobile-push/src/models.rs b/src/desktop/src-tauri/plugins/mobile-push/src/models.rsindex b3f138659..21efeed08 100644--- a/src/desktop/src-tauri/plugins/mobile-push/src/models.rs+++ b/src/desktop/src-tauri/plugins/mobile-push/src/models.rs@@ -38,6 +38,13 @@ pub struct DismissRequest {pub notification_id: String,}+#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct DismissConversationRequest {+ pub viewer_user_id: String,+ pub target_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.rsindex 992235c36..4c77aee22 100644--- a/src/desktop/src-tauri/src/lib.rs+++ b/src/desktop/src-tauri/src/lib.rs@@ -96,6 +96,7 @@ fn run_mobile(mut builder: tauri::Builder<tauri::Wry>) {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_dismiss_conversation,mobile_system_notification_runtime::mobile_system_notification_listen,mobile_system_notification_runtime::mobile_system_notification_unlisten,native_oauth_runtime::native_oauth_snapshot,@@ -171,6 +172,7 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {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_dismiss_conversation,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.rsindex 46e7a52ed..90b300742 100644--- a/src/desktop/src-tauri/src/mobile_system_notification.rs+++ b/src/desktop/src-tauri/src/mobile_system_notification.rs@@ -48,6 +48,18 @@ fn safe_id(value: &str) -> bool {.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))}+#[cfg_attr(not(mobile), allow(dead_code))]+pub fn validate_target_id(target_id: &str) -> Result<(), MobileSystemNotificationError> {+ if safe_id(target_id) {+ Ok(())+ } else {+ Err(MobileSystemNotificationError::new(+ "invalid_request",+ "Notification target id is invalid",+ ))+ }+}+fn uuid(value: &str) -> bool {let bytes = value.as_bytes();bytes.len() == 36@@ -259,4 +271,14 @@ mod tests {assert!(validate_notification_id("4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e").is_ok());assert!(validate_notification_id("bad").is_err());}++ #[test]+ fn uses_the_same_safe_id_contract_for_viewers_and_targets() {+ for value in ["viewer_1", "channel-2", &"a".repeat(128)] {+ assert!(validate_target_id(value).is_ok());+ }+ for value in ["", "../viewer", "channel:1", &"a".repeat(129)] {+ assert!(validate_target_id(value).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.rsindex 3e932cd0e..7c3f3b123 100644--- a/src/desktop/src-tauri/src/mobile_system_notification_runtime.rs+++ b/src/desktop/src-tauri/src/mobile_system_notification_runtime.rs@@ -1,7 +1,7 @@use crate::mobile_system_notification::{validate_activation, validate_notification_id, validate_permission, validate_provider_token,- validate_snapshot, Activation, MobileSystemNotificationError, PermissionResponse,- RegistrationSnapshot,+ validate_snapshot, validate_target_id, Activation, MobileSystemNotificationError,+ PermissionResponse, RegistrationSnapshot,};use crate::native_command_guard::guard;use tauri::{ipc::Channel, Manager, WebviewWindow};@@ -111,6 +111,24 @@ pub async fn mobile_system_notification_dismiss(Ok(())}+#[tauri::command]+pub async fn mobile_system_notification_dismiss_conversation(+ window: WebviewWindow,+ viewer_user_id: String,+ target_id: String,+) -> Result<(), MobileSystemNotificationError> {+ guard(&window)+ .map_err(|code| MobileSystemNotificationError::new(code, "Caller is not trusted"))?;+ validate_target_id(&viewer_user_id)?;+ validate_target_id(&target_id)?;+ window+ .app_handle()+ .mobile_push()+ .dismiss_conversation(viewer_user_id, target_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.rsindex 592a6da4f..1e57801ae 100644--- a/src/desktop/src-tauri/src/system_notifications.rs+++ b/src/desktop/src-tauri/src/system_notifications.rs@@ -37,6 +37,57 @@ pub enum NotificationTarget {},}+#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]+#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]+pub enum NotificationConversation {+ Server {+ #[serde(rename = "serverId")]+ server_id: String,+ #[serde(rename = "channelId")]+ channel_id: String,+ },+ Dm {+ #[serde(rename = "channelId")]+ channel_id: String,+ },+}++impl NotificationConversation {+ fn valid(&self) -> bool {+ match self {+ Self::Server {+ server_id,+ channel_id,+ } => valid_id(server_id) && valid_id(channel_id),+ Self::Dm { channel_id } => valid_id(channel_id),+ }+ }++ fn matches(&self, target: &NotificationTarget) -> bool {+ match (self, target) {+ (+ Self::Server {+ server_id,+ channel_id,+ },+ NotificationTarget::Server {+ server_id: target_server,+ channel_id: target_channel,+ ..+ },+ ) => server_id == target_server && channel_id == target_channel,+ (+ Self::Dm { channel_id },+ NotificationTarget::Dm {+ channel_id: target_channel,+ ..+ },+ ) => channel_id == target_channel,+ _ => false,+ }+ }+}+impl NotificationTarget {fn message_id(&self) -> &str {match self {@@ -96,6 +147,8 @@ struct RecentNotification {message_id: String,target: NotificationTarget,activated: bool,+ #[serde(default)]+ dismissed: bool,}#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]@@ -149,6 +202,7 @@ impl NotificationRecord {message_id: candidate.target.message_id().to_string(),target: candidate.target.clone(),activated: false,+ dismissed: false,});if self.recent.len() > MAX_RECENT {self.recent.drain(0..self.recent.len() - MAX_RECENT);@@ -184,6 +238,30 @@ impl NotificationRecord {item.activated = false;true}++ fn notification_ids(+ &self,+ viewer_user_id: &str,+ conversation: &NotificationConversation,+ ) -> Vec<String> {+ self.recent+ .iter()+ .filter(|item| {+ !item.dismissed+ && item.viewer_user_id == viewer_user_id+ && conversation.matches(&item.target)+ })+ .map(|item| item.notification_id.clone())+ .collect()+ }++ fn complete_dismissals(&mut self, notification_ids: &[String]) {+ for item in &mut self.recent {+ if notification_ids.contains(&item.notification_id) {+ item.dismissed = true;+ }+ }+ }}struct Notifications<T> {@@ -496,47 +574,114 @@ pub fn desktop_system_notification_retry_activation(}#[tauri::command]-pub fn desktop_system_notification_dismiss(+pub async fn desktop_system_notification_dismiss(window: WebviewWindow,+ state: tauri::State<'_, DesktopSystemNotificationState>,notification_id: String,) -> Result<(), &'static str> {guard(&window)?;if !valid_notification_id(¬ification_id) {return Err("notification_invalid");}- dismiss_notification(¬ification_id).map_err(|_| "notification_unavailable")+ dismiss_notifications_confirmed(&[notification_id.clone()])+ .await+ .map_err(|_| "notification_unavailable")?;+ state.transact(|record| {+ record.complete_dismissals(&[notification_id]);+ Ok(())+ })+}++#[tauri::command]+pub async fn desktop_system_notification_dismiss_conversation(+ window: WebviewWindow,+ state: tauri::State<'_, DesktopSystemNotificationState>,+ viewer_user_id: String,+ target: NotificationConversation,+) -> Result<(), &'static str> {+ guard(&window)?;+ if !valid_id(&viewer_user_id) || !target.valid() {+ return Err("notification_invalid");+ }+ let notification_ids = state+ .record+ .lock()+ .map_err(|_| "store_unavailable")?+ .notification_ids(&viewer_user_id, &target);+ if notification_ids.is_empty() {+ return Ok(());+ }+ dismiss_notifications_confirmed(¬ification_ids)+ .await+ .map_err(|_| "notification_unavailable")?;+ state.transact(|record| {+ record.complete_dismissals(¬ification_ids);+ Ok(())+ })}#[cfg(target_os = "macos")]-fn dismiss_notification(notification_id: &str) -> Result<(), ()> {+async fn dismiss_notifications_confirmed(notification_ids: &[String]) -> Result<(), ()> {+ use block2::RcBlock;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(())+ use objc2_user_notifications::{UNNotification, UNUserNotificationCenter};+ use std::ptr::NonNull;++ let receiver = {+ let identifiers = notification_ids+ .iter()+ .map(|value| NSString::from_str(value))+ .collect::<Vec<_>>();+ let identifier_refs = identifiers.iter().map(|value| &**value).collect::<Vec<_>>();+ let center = UNUserNotificationCenter::currentNotificationCenter();+ center.removeDeliveredNotificationsWithIdentifiers(&NSArray::from_slice(&identifier_refs));+ let requested = notification_ids.to_vec();+ let (sender, receiver) = std::sync::mpsc::channel();+ let completion = RcBlock::new(move |notifications: NonNull<NSArray<UNNotification>>| {+ let notifications = unsafe { notifications.as_ref() };+ let remains = notifications.iter().any(|notification| {+ requested.contains(¬ification.request().identifier().to_string())+ });+ let _ = sender.send(if remains { Err(()) } else { Ok(()) });+ });+ center.getDeliveredNotificationsWithCompletionHandler(&completion);+ receiver+ };+ wait_for_macos_completion(receiver).await}#[cfg(windows)]-fn dismiss_notification(notification_id: &str) -> Result<(), ()> {+async fn dismiss_notifications_confirmed(notification_ids: &[String]) -> 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(|_| ())+ let history = ToastNotificationManager::History().map_err(|_| ())?;+ for notification_id in notification_ids {+ history+ .RemoveGroupedTagWithId(+ &HSTRING::from(notification_id.as_str()),+ &HSTRING::from(WINDOWS_NOTIFICATION_GROUP),+ &HSTRING::from(WINDOWS_APP_ID),+ )+ .map_err(|_| ())?;+ }+ let delivered = history+ .GetHistoryWithId(&HSTRING::from(WINDOWS_APP_ID))+ .map_err(|_| ())?;+ for index in 0..delivered.Size().map_err(|_| ())? {+ let toast = delivered.GetAt(index).map_err(|_| ())?;+ let tag = toast.Tag().map_err(|_| ())?.to_string();+ let group = toast.Group().map_err(|_| ())?.to_string();+ if group == WINDOWS_NOTIFICATION_GROUP && notification_ids.contains(&tag) {+ return Err(());+ }+ }+ Ok(())}#[cfg(target_os = "linux")]-fn dismiss_notification(_notification_id: &str) -> Result<(), ()> {- Ok(())+async fn dismiss_notifications_confirmed(_notification_ids: &[String]) -> Result<(), ()> {+ Err(())}#[cfg(target_os = "macos")]@@ -774,6 +919,25 @@ mod tests {}}+ fn candidate_in(+ viewer: &str,+ server_id: &str,+ channel_id: &str,+ message_id: &str,+ ) -> NotificationCandidate {+ NotificationCandidate {+ viewer_user_id: viewer.into(),+ title: "Ada".into(),+ body: "Hello".into(),+ target: NotificationTarget::Server {+ server_id: server_id.into(),+ channel_id: channel_id.into(),+ message_id: message_id.into(),+ seq: 1,+ },+ }+ }+#[test]fn deterministic_ids_are_stable_scoped_and_uuid_shaped() {let first = deterministic_notification_id("viewer_1", "message_1");@@ -826,6 +990,119 @@ mod tests {assert!(restored.recent[0].activated);}+ #[test]+ fn conversation_dismissal_is_exact_across_messages_conversations_and_accounts() {+ let mut record = NotificationRecord::new();+ let same_first = record+ .claim(&candidate_in(+ "viewer_1",+ "server_1",+ "channel_1",+ "message_1",+ ))+ .unwrap();+ let same_second = record+ .claim(&candidate_in(+ "viewer_1",+ "server_1",+ "channel_1",+ "message_2",+ ))+ .unwrap();+ let other_channel = record+ .claim(&candidate_in(+ "viewer_1",+ "server_1",+ "channel_2",+ "message_3",+ ))+ .unwrap();+ let other_viewer = record+ .claim(&candidate_in(+ "viewer_2",+ "server_1",+ "channel_1",+ "message_4",+ ))+ .unwrap();+ let conversation = NotificationConversation::Server {+ server_id: "server_1".to_string(),+ channel_id: "channel_1".to_string(),+ };++ assert_eq!(+ record.notification_ids("viewer_1", &conversation),+ vec![same_first.clone(), same_second.clone()],+ );+ record.complete_dismissals(&[same_first.clone(), same_second.clone()]);+ assert_eq!(+ record.notification_ids("viewer_1", &conversation),+ Vec::<String>::new()+ );+ assert!(record+ .claim(&candidate_in(+ "viewer_1",+ "server_1",+ "channel_1",+ "message_1"+ ))+ .is_none());+ assert!(record+ .recent+ .iter()+ .any(|item| item.notification_id == other_channel));+ assert!(record+ .recent+ .iter()+ .any(|item| item.notification_id == other_viewer));++ let restored = NotificationRecord::restore(serde_json::to_value(record).unwrap()).unwrap();+ assert_eq!(+ restored.notification_ids("viewer_1", &conversation),+ Vec::<String>::new()+ );+ assert!(restored+ .recent+ .iter()+ .any(|item| item.notification_id == same_first));+ assert!(restored+ .recent+ .iter()+ .any(|item| item.notification_id == same_second));+ }++ #[test]+ fn old_records_without_a_dismissed_field_restore_as_delivered() {+ let id = deterministic_notification_id("viewer_1", "message_1");+ let record = NotificationRecord::restore(serde_json::json!({+ "version": 1,+ "recent": [{+ "notificationId": id,+ "viewerUserId": "viewer_1",+ "messageId": "message_1",+ "target": {+ "kind": "server",+ "serverId": "server_1",+ "channelId": "channel_1",+ "messageId": "message_1",+ "seq": 1+ },+ "activated": false+ }]+ }))+ .unwrap();+ assert_eq!(+ record.notification_ids(+ "viewer_1",+ &NotificationConversation::Server {+ server_id: "server_1".into(),+ channel_id: "channel_1".into(),+ },+ ),+ vec![id],+ );+ }+#[test]fn restore_rejects_unknown_or_malformed_state() {assert!(NotificationRecord::restore(serde_json::json!({diff --git a/src/queue-worker/src/mobile-push.test.ts b/src/queue-worker/src/mobile-push.test.tsindex 7614bad4b..9c28065b8 100644--- a/src/queue-worker/src/mobile-push.test.ts+++ b/src/queue-worker/src/mobile-push.test.ts@@ -89,6 +89,7 @@ function dependencies() {notificationId: "notification-1",messageId: "message-1",targetId: "channel-1",+ viewerUserId: "user-1",},})),createFcmAccessToken: vi.fn(async () => "access-token"),diff --git a/src/queue-worker/src/notification-payload.test.ts b/src/queue-worker/src/notification-payload.test.tsindex dbce77adc..a61b84644 100644--- a/src/queue-worker/src/notification-payload.test.ts+++ b/src/queue-worker/src/notification-payload.test.ts@@ -51,6 +51,7 @@ describe("mobile notification payload", () => {notificationId: payload.notificationId,messageId: "message-1",targetId: "channel-1",+ viewerUserId: "user-1",},})expect(JSON.stringify(payload)).not.toContain("https://example.test")@@ -95,6 +96,7 @@ describe("mobile notification payload", () => {notificationId: payload.notificationId,messageId: "message-1",targetId: "channel-1",+ viewerUserId: "user-1",})})diff --git a/src/queue-worker/src/notification-payload.ts b/src/queue-worker/src/notification-payload.tsindex 1690c800a..5bf7f69df 100644--- a/src/queue-worker/src/notification-payload.ts+++ b/src/queue-worker/src/notification-payload.ts@@ -11,6 +11,7 @@ export interface PushNotificationPayload {notificationId: stringmessageId: stringtargetId: string+ viewerUserId: string}}@@ -66,6 +67,7 @@ export async function buildPushNotificationPayload(notificationId,messageId: target.messageId,targetId: target.channelId,+ viewerUserId: userId,},}}diff --git a/src/queue-worker/src/providers/apns.test.ts b/src/queue-worker/src/providers/apns.test.tsindex 1e8b5a603..c2ab4bed3 100644--- a/src/queue-worker/src/providers/apns.test.ts+++ b/src/queue-worker/src/providers/apns.test.ts@@ -13,6 +13,7 @@ const payload = {notificationId: "4cb8126e-4842-5c26-8d3f-02031c3d014b",messageId: "message-1",targetId: "channel-1",+ viewerUserId: "user-1",},}diff --git a/src/queue-worker/src/providers/fcm.test.ts b/src/queue-worker/src/providers/fcm.test.tsindex c2705e29f..986d00945 100644--- a/src/queue-worker/src/providers/fcm.test.ts+++ b/src/queue-worker/src/providers/fcm.test.ts@@ -9,6 +9,7 @@ const payload = {notificationId: "4cb8126e-4842-5c26-8d3f-02031c3d014b",messageId: "message-1",targetId: "channel-1",+ viewerUserId: "user-1",},}@@ -181,7 +182,10 @@ describe("FCM HTTP v1 adapter", () => {android: {priority: "high",collapse_key: payload.notificationId,- notification: { tag: payload.notificationId, sound: "default" },+ notification: {+ tag: `alook:v2:${payload.route.viewerUserId}:${payload.route.targetId}:${payload.notificationId}`,+ sound: "default",+ },},},})diff --git a/src/queue-worker/src/providers/fcm.ts b/src/queue-worker/src/providers/fcm.tsindex b6b06f9b2..c1193e8af 100644--- a/src/queue-worker/src/providers/fcm.ts+++ b/src/queue-worker/src/providers/fcm.ts@@ -11,6 +11,14 @@ export interface FcmConfig {privateKey: string}+function mobilePushNotificationTag(+ viewerUserId: string,+ targetId: string,+ notificationId: string,+): string {+ return `alook:v2:${viewerUserId}:${targetId}:${notificationId}`+}+function base64Url(value: string | ArrayBuffer): string {const bytes = typeof value === "string"? new TextEncoder().encode(value)@@ -124,7 +132,11 @@ export async function sendFcmNotification(priority: "high",collapse_key: input.payload.notificationId,notification: {- tag: input.payload.notificationId,+ tag: mobilePushNotificationTag(+ input.payload.route.viewerUserId,+ input.payload.route.targetId,+ input.payload.notificationId,+ ),sound: "default",},},diff --git a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.tsnew file mode 100644index 000000000..9a717521c--- /dev/null+++ b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts@@ -0,0 +1,175 @@+import React from "react"+import { render } from "@/test/react-dom-harness"+import { beforeEach, describe, expect, it, vi } from "vitest"+import DmPage from "./page"++const {+ mockDismissConversation,+ mockDmMessages,+ mockDms,+ mockStore,+} = vi.hoisted(() => ({+ mockDismissConversation: vi.fn(),+ mockDms: {+ dms: [] as Array<{+ id: string+ userId: string+ name: string+ avatar: string+ }>,+ isLoading: false,+ },+ mockDmMessages: {+ navigationBlocked: false,+ },+ mockStore: {+ registerUiHandlers: vi.fn(),+ setCurrentChannelId: vi.fn(),+ },+}))++vi.mock("next/navigation", () => ({+ useParams: () => ({ dmId: "dm_1" }),+ useSearchParams: () => new URLSearchParams(),+}))+vi.mock("sonner", () => ({ toast: vi.fn() }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))+vi.mock("@/components/community/channels/dm-header", () => ({ DmHeader: () => null }))+vi.mock("@/components/community/channels/dm-loading-frame", () => ({+ DmLoadingFrame: () => React.createElement("div", { "data-testid": "dm-loading" }),+}))+vi.mock("@/components/community/avatar", () => ({ Avatar: () => null }))+vi.mock("@/components/community/messages/message-list", () => ({ MessageList: () => null }))+vi.mock("@/components/community/messages/message-context-sheet", () => ({+ MessageContextSheet: () => null,+}))+vi.mock("@/components/community/messages/composer", () => ({ Composer: () => null }))+vi.mock("@/components/community/messages/conversation-footer-shell", () => ({+ ConversationFooterShell: ({ children }: { children: React.ReactNode }) => children,+ ConversationFooterSlotProvider: ({ children }: { children: React.ReactNode }) => children,+}))+vi.mock("@/stores/community", () => ({+ useCommunityStore: { getState: () => mockStore },+ useUiHandlers: () => ({}),+ useTypingUsersForScope: () => [],+ useTypingNamesForScope: () => ({}),+}))+vi.mock("@/lib/community/testids", () => ({ tid: { dmBlockedNotice: "dm-blocked" } }))+vi.mock("@/lib/community/profile-read", () => ({ readCommunityProfile: vi.fn() }))+vi.mock("@/lib/community/display-name", () => ({+ makeUserNameResolver: () => (userId: string) => userId,+}))+vi.mock("@/hooks/community/use-dms", () => ({ useDms: () => mockDms }))+vi.mock("@/hooks/community/use-friends", () => ({+ useFriends: () => ({ friends: [], blocked: [] }),+}))+vi.mock("@/hooks/community/use-messages", () => ({+ useDmMessages: () => ({+ messages: [],+ isLoading: false,+ hasMoreOlder: false,+ hasMoreNewer: false,+ isFetchingOlder: false,+ isFetchingNewer: false,+ fetchOlder: vi.fn(),+ fetchNewer: vi.fn(),+ jumpToPresent: vi.fn(),+ presentVersion: 0,+ latestSeq: 0,+ isPending: false,+ isError: false,+ refetch: vi.fn(),+ navigationBlocked: mockDmMessages.navigationBlocked,+ anchorReconciled: false,+ }),+}))+vi.mock("@/hooks/community/use-dm-read-state", () => ({+ useDmReadStateSnapshot: () => ({ snapshot: null, isFetching: false }),+}))+vi.mock("@/lib/community/message-read-projection", () => ({+ resolveMessageReadProjection: () => ({ newDividerBefore: undefined, anchorFound: false }),+}))+vi.mock("@/hooks/community/use-dm-watermark", () => ({ useDmWatermark: vi.fn() }))+vi.mock("@/hooks/community/use-channel-ref-directory", () => ({+ useChannelRefDirectory: () => ({+ directory: [],+ isResolved: true,+ isLoading: false,+ isError: false,+ refetch: vi.fn(),+ }),+}))+vi.mock("@/lib/community/channel-ref-extension", () => ({ toChannelRefCandidate: vi.fn() }))+vi.mock("@/hooks/community/mutations", () => ({+ useAddReactionApi: () => vi.fn(),+ useToggleReactionApi: () => vi.fn(),+ useToggleMark: () => vi.fn(),+ useSetChannelNotif: () => ({ mutate: vi.fn() }),+}))+vi.mock("@/hooks/community/use-dm-message-sender", () => ({+ useDmMessageSender: () => ({ accept: vi.fn(), retry: vi.fn() }),+}))+vi.mock("@/stores/community/message-stream", () => ({+ useMessageStreamStore: { getState: () => ({ dispatch: vi.fn() }) },+}))+vi.mock("@/contexts/community/current-user", () => ({+ useCurrentUser: () => ({ id: "viewer_1", name: "Viewer", avatar: "V" }),+}))+vi.mock("@/hooks/community/use-community-ws", () => ({+ communityWsSubscribe: vi.fn(),+ communityWsUnsubscribe: vi.fn(),+ communityWsSendTyping: vi.fn(),+ communityWsEndTyping: vi.fn(),+}))+vi.mock("@/lib/community-onboarding", () => ({+ advanceCommunityOnboarding: vi.fn(),+ readCommunityOnboardingState: () => null,+}))+vi.mock("@alook/shared", () => ({ notifLevelDisplay: () => "all" }))+vi.mock("@/hooks/community/use-notification-settings", () => ({+ useNotificationSettings: () => ({ channel: {} }),+}))+vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))+vi.mock("@/lib/community/reply-content", () => ({ displayReplyContent: () => "" }))+vi.mock("@/lib/community-db/projections", () => ({+ useCanonicalProfilesByUserId: () => new Map(),+ useReadStateProjection: () => null,+}))+vi.mock("@/hooks/community/use-native-system-notifications", () => ({+ useNativeSystemNotificationConversationDismissal: (...args: unknown[]) =>+ mockDismissConversation(...args),+}))++describe("DM notification dismissal readiness", () => {+ beforeEach(() => {+ mockDismissConversation.mockClear()+ mockDmMessages.navigationBlocked = false+ mockDms.dms = []+ mockDms.isLoading = false+ })++ it.each([+ ["resolved", [{ id: "dm_1", userId: "peer_1", name: "Peer", avatar: "P" }], false, false, true],+ ["blocked", [{ id: "dm_1", userId: "peer_1", name: "Peer", avatar: "P" }], false, true, false],+ ["pending", [], true, false, false],+ ["notFound", [], false, false, false],+ ] as const)("passes the exact %s readiness state to dismissal", (+ _state,+ dms,+ isLoading,+ navigationBlocked,+ expectedReady,+ ) => {+ mockDms.dms = [...dms]+ mockDms.isLoading = isLoading+ mockDmMessages.navigationBlocked = navigationBlocked++ render(React.createElement(DmPage))++ expect(mockDismissConversation).toHaveBeenCalledExactlyOnceWith(+ "viewer_1",+ { kind: "dm", channelId: "dm_1" },+ expectedReady,+ )+ })+})diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex ba02eb4a6..b1899b2e3 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -60,6 +60,7 @@ import {useCanonicalProfilesByUserId,useReadStateProjection,} from "@/lib/community-db/projections"+import { useNativeSystemNotificationConversationDismissal } from "@/hooks/community/use-native-system-notifications"// Thin re-mount wrapper — same reason as the server-side channel view: the// dynamic segment reuses the same component instance across DM switches, so@@ -421,6 +422,10 @@ function DmView() {dmsLoading,messagesLoading,})+ useNativeSystemNotificationConversationDismissal(currentUser.id, {+ kind: "dm",+ channelId: dmId,+ }, !navigationBlocked && !loadingOwnership.fullFramePending && !loadingOwnership.notFound && !!dm)if (navigationBlocked) {return <DmLoadingFrame reserveBackSlot={bp === "mobile"} />diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.tsindex f1d4094f4..89d96d3cc 100644--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts@@ -25,6 +25,7 @@ const {mockNavigationGate,mockCurrentChannelId,mockCanManageServer,+ mockDismissConversation,} = vi.hoisted(() => ({mockRouter: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },mockUiHandlers: { replacePath: vi.fn(), goBackMobile: vi.fn() },@@ -41,6 +42,7 @@ const {mockNavigationGate: { allowed: true },mockCurrentChannelId: { value: "channel_1" as string | null },mockCanManageServer: vi.fn((role?: string | null) => role === "owner" || role === "admin"),+ mockDismissConversation: vi.fn(),mockRouteModel: {server: {id: "server_1",@@ -179,6 +181,10 @@ vi.mock("@/contexts/community/current-user", () => ({vi.mock("@/hooks/community/use-channel-route-model", () => ({useChannelRouteModel: () => mockRouteModel,}))+vi.mock("@/hooks/community/use-native-system-notifications", () => ({+ useNativeSystemNotificationConversationDismissal: (...args: unknown[]) =>+ mockDismissConversation(...args),+}))vi.mock("@/hooks/community/use-thread-split-mode", () => ({useThreadSplitMode: () => ({ containerRef: vi.fn(), mode: mockSplitMode.value }),}))@@ -346,6 +352,7 @@ describe("ChannelRoute message surface ownership", () => {mockCommitLastCommunityRoute.mockClear()mockSetLastChannel.mockClear()mockClearLastChannel.mockClear()+ mockDismissConversation.mockClear()mockNavigationGate.allowed = truemockCurrentChannelId.value = "channel_1"mockMemberViewModel.myRole = "member"@@ -593,6 +600,7 @@ describe("ChannelRoute message surface ownership", () => {categories: [{ channels: [{ id: "channel_2", name: "survivor", type: "text" }] }],},})+ mockDismissConversation.mockClear()act(() => {renderer.rerender(React.createElement(ChannelRoute, {serverParam: "server_1",@@ -602,9 +610,19 @@ describe("ChannelRoute message surface ownership", () => {expect(mockClearLastChannel).toHaveBeenCalledExactlyOnceWith("server_1")expect(mockRouter.replace).toHaveBeenCalledWith("/c/channels/server_1/channel_2")+ expect(mockDismissConversation).toHaveBeenCalledWith(+ "viewer_1",+ { kind: "server", serverId: "server_1", channelId: "channel_1" },+ false,+ )+ expect(mockDismissConversation).not.toHaveBeenCalledWith(+ "viewer_1",+ { kind: "server", serverId: "server_1", channelId: "channel_1" },+ true,+ )})- it("commits only a ready channel route for the active account", () => {+ it("commits and dismisses only a ready top-level channel for the active account", () => {mockedUseChannelMessageFeed.mockReturnValue(feed())act(() => {render(React.createElement(ChannelRoute, {@@ -616,6 +634,56 @@ describe("ChannelRoute message surface ownership", () => {"viewer_1","/c/channels/server_1/channel_1",)+ expect(mockDismissConversation).toHaveBeenCalledExactlyOnceWith(+ "viewer_1",+ { kind: "server", serverId: "server_1", channelId: "channel_1" },+ true,+ )+ })++ it.each([+ ["thread", () => configureThreadRoute()],+ ["forum", () => Object.assign(mockRouteModel, {+ channel: { id: "channel_1", name: "forum", type: "forum" },+ isForum: true,+ })],+ ] as const)("dismisses a ready %s surface with the exact viewer and target", (_surface, setup) => {+ setup()+ mockedUseChannelMessageFeed.mockReturnValue(feed())++ render(React.createElement(ChannelRoute, {+ serverParam: "server_1",+ channelId: "channel_1",+ }))++ expect(mockDismissConversation).toHaveBeenCalledExactlyOnceWith(+ "viewer_1",+ { kind: "server", serverId: "server_1", channelId: "channel_1" },+ true,+ )+ })++ it.each([+ ["denied", () => { mockNavigationGate.allowed = false }],+ ["pending", () => {+ mockRouteModel.routeLifecycle = "pending"+ mockRouteModel.routeHydrated = false+ }],+ ["redirect", () => { mockCurrentChannelId.value = "previous_channel" }],+ ] as const)("does not dismiss while the server surface is %s", (_state, setup) => {+ setup()+ mockedUseChannelMessageFeed.mockReturnValue(feed())++ render(React.createElement(ChannelRoute, {+ serverParam: "server_1",+ channelId: "channel_1",+ }))++ expect(mockDismissConversation).toHaveBeenCalledExactlyOnceWith(+ "viewer_1",+ { kind: "server", serverId: "server_1", channelId: "channel_1" },+ false,+ )})it.each([diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsxindex d156e3fa6..44a2814cf 100644--- a/src/web/src/components/community/channels/channel-route.tsx+++ b/src/web/src/components/community/channels/channel-route.tsx@@ -41,6 +41,7 @@ import { useQueryClient } from "@tanstack/react-query"import { useCommunityWsStore } from "@/stores/community/ws"import { useConversationNavigationGate } from "@/lib/community/conversation-navigation-proof"import { resolveConversationSubtype } from "@/lib/community/conversation-subtype"+import { useNativeSystemNotificationConversationDismissal } from "@/hooks/community/use-native-system-notifications"const THREAD_VIEW_PARAM = "threadView"@@ -220,6 +221,11 @@ export function ChannelRoute({ serverParam, channelId }: {routeModel.routeHydrated &&(!isForumPostChild || !forumPostOpener.isLoading) &&navigationGate.allowed+ useNativeSystemNotificationConversationDismissal(currentUser.id, {+ kind: "server",+ serverId,+ channelId,+ }, channelHydrated)// Route memory is an access-bearing navigation decision. Structural hints// can choose the skeleton, but only live data plus the current access gate// may commit the destination for a later cold entry.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.tsindex 29d74c39e..8ae5f0aa1 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@@ -4,10 +4,14 @@ import {createDesktopSystemNotificationActivationController,createDesktopSystemNotificationInboxOpener,type DesktopSystemNotificationInboxDeps,+ useNativeSystemNotificationConversationDismissal,useNativeSystemNotifications,} from "./use-native-system-notifications"import type { DesktopSystemNotificationActivation } from "@/lib/community/system-notification-route"-import { createNativeSystemNotificationDismissalQueue } from "@/lib/community/native-system-notification-dismissal"+import {+ createNativeSystemNotificationConversationDismissalQueue,+ createNativeSystemNotificationDismissalQueue,+} from "@/lib/community/native-system-notification-dismissal"const hookMocks = vi.hoisted(() => ({desktop: true,@@ -16,6 +20,7 @@ const hookMocks = vi.hoisted(() => ({take: vi.fn(),retryActivation: vi.fn(async () => undefined),dismiss: vi.fn(async () => undefined),+ dismissConversation: vi.fn(async () => undefined),revalidate: vi.fn(),mobileListen: vi.fn(),mobileCheck: vi.fn(),@@ -26,6 +31,7 @@ const hookMocks = vi.hoisted(() => ({mobileDelete: vi.fn(),mobileTake: vi.fn(),mobileDismiss: vi.fn(async () => undefined),+ mobileDismissConversation: vi.fn(async () => undefined),mobileRevalidate: vi.fn(),}))vi.mock("@alook/shared", async () => {@@ -46,6 +52,7 @@ vi.mock("@/lib/community/desktop-system-notification", async () => {takeDesktopSystemNotificationActivation: hookMocks.take,retryDesktopSystemNotificationActivation: hookMocks.retryActivation,dismissDesktopSystemNotification: hookMocks.dismiss,+ dismissDesktopSystemNotificationConversation: hookMocks.dismissConversation,}})vi.mock("@/lib/community/system-notification-route", async () => {@@ -69,6 +76,7 @@ vi.mock("@/lib/community/mobile-system-notification", async () => {deleteMobileSystemNotificationRegistration: hookMocks.mobileDelete,takeMobileSystemNotificationActivation: hookMocks.mobileTake,dismissMobileSystemNotification: hookMocks.mobileDismiss,+ dismissMobileSystemNotificationConversation: hookMocks.mobileDismissConversation,revalidateMobileSystemNotificationActivation: hookMocks.mobileRevalidate,}})@@ -88,6 +96,7 @@ afterEach(() => {hookMocks.desktop = truehookMocks.mobile = falsewindow.sessionStorage.clear()+ window.localStorage.clear()document.body.replaceChildren()vi.useRealTimers()vi.unstubAllGlobals()@@ -365,6 +374,112 @@ describe("desktop notification Inbox fallback", () => {})describe("native system notification hook", () => {+ it("queues only after the exact conversation is ready and retries after recreation", async () => {+ const target = { kind: "server" as const, serverId: "server_1", channelId: "channel_1" }+ const pending = renderHook(() => useNativeSystemNotificationConversationDismissal(+ "viewer_1",+ target,+ false,+ ))+ expect(hookMocks.dismissConversation).not.toHaveBeenCalled()+ pending.unmount()++ hookMocks.dismissConversation.mockRejectedValueOnce(new Error("native unavailable"))+ const first = renderHook(() => useNativeSystemNotificationConversationDismissal(+ "viewer_1",+ target,+ true,+ ))+ await waitFor(() => expect(hookMocks.dismissConversation).toHaveBeenCalledExactlyOnceWith(+ "viewer_1",+ target,+ ))+ await act(async () => { await Promise.resolve() })+ expect(window.localStorage.length).toBe(1)+ first.unmount()++ hookMocks.dismissConversation.mockResolvedValueOnce(undefined)+ const restored = renderHook(() => useNativeSystemNotificationConversationDismissal(+ "viewer_1",+ target,+ true,+ ))+ await waitFor(() => expect(hookMocks.dismissConversation).toHaveBeenCalledTimes(2))+ await waitFor(() => expect(window.localStorage.length).toBe(0))+ restored.unmount()+ })++ it("dismisses a ready mobile DM by exact viewer and channel only", async () => {+ hookMocks.desktop = false+ hookMocks.mobile = true+ const target = { kind: "dm" as const, channelId: "dm_1" }++ const rendered = renderHook(() => useNativeSystemNotificationConversationDismissal(+ "viewer_1",+ target,+ true,+ ))++ await waitFor(() => expect(hookMocks.mobileDismissConversation)+ .toHaveBeenCalledExactlyOnceWith("viewer_1", "dm_1"))+ expect(hookMocks.dismissConversation).not.toHaveBeenCalled()+ await waitFor(() => expect(window.localStorage.length).toBe(0))+ rendered.unmount()+ })++ it("persists each remaining desktop conversation until its own dismissal completes", async () => {+ const firstTarget = {+ kind: "server" as const,+ serverId: "server_1",+ channelId: "channel_1",+ }+ const secondTarget = {+ kind: "server" as const,+ serverId: "server_1",+ channelId: "channel_2",+ }+ const queue = createNativeSystemNotificationConversationDismissalQueue({+ getItem: (key) => window.localStorage.getItem(key),+ setItem: (key, value) => window.localStorage.setItem(key, value),+ removeItem: (key) => window.localStorage.removeItem(key),+ })+ expect(queue.queue("desktop", "viewer_1", firstTarget)).toBe(true)+ expect(queue.queue("desktop", "viewer_1", secondTarget)).toBe(true)++ let resolveFirst = () => undefined+ let resolveSecond = () => undefined+ const firstDismissal = new Promise<void>((resolve) => { resolveFirst = resolve })+ const secondDismissal = new Promise<void>((resolve) => { resolveSecond = resolve })+ hookMocks.dismissConversation+ .mockImplementationOnce(() => firstDismissal)+ .mockImplementationOnce(() => secondDismissal)+ hookMocks.listen.mockResolvedValue(vi.fn())+ hookMocks.take.mockResolvedValue(null)++ const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))+ await waitFor(() => expect(hookMocks.dismissConversation).toHaveBeenCalledTimes(2))++ await act(async () => {+ resolveFirst()+ await firstDismissal+ })+ expect(JSON.parse(window.localStorage.getItem(+ "alook:native-system-notification:conversation-dismissals",+ )!)).toEqual([{+ version: 1,+ platform: "desktop",+ viewerUserId: "viewer_1",+ target: secondTarget,+ }])++ await act(async () => {+ resolveSecond()+ await secondDismissal+ })+ await waitFor(() => expect(window.localStorage.length).toBe(0))+ rendered.unmount()+ })+it("does nothing in the browser", () => {hookMocks.desktop = falseconst rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))diff --git a/src/web/src/hooks/community/use-native-system-notifications.ts b/src/web/src/hooks/community/use-native-system-notifications.tsindex 0bdf9379f..a467951c4 100644--- a/src/web/src/hooks/community/use-native-system-notifications.ts+++ b/src/web/src/hooks/community/use-native-system-notifications.ts@@ -4,6 +4,7 @@ import { useEffect } from "react"import { isDesktop, isMobile } from "@alook/shared"import {dismissDesktopSystemNotification,+ dismissDesktopSystemNotificationConversation,listenDesktopSystemNotificationActivations,retryDesktopSystemNotificationActivation,takeDesktopSystemNotificationActivation,@@ -21,6 +22,7 @@ import {createMobileSystemNotificationRegistrationController,deleteMobileSystemNotificationRegistration,dismissMobileSystemNotification,+ dismissMobileSystemNotificationConversation,listenMobileSystemNotificationSignals,postMobileSystemNotificationRegistration,requestMobileSystemNotificationPermission,@@ -29,9 +31,72 @@ import {snapshotMobileSystemNotificationRegistration,takeMobileSystemNotificationActivation,} from "@/lib/community/mobile-system-notification"-import { createNativeSystemNotificationDismissalQueue } from "@/lib/community/native-system-notification-dismissal"+import {+ createNativeSystemNotificationConversationDismissalQueue,+ createNativeSystemNotificationDismissalQueue,+ type NativeSystemNotificationConversation,+ type NativeSystemNotificationPlatform,+} from "@/lib/community/native-system-notification-dismissal"const activeNativeDismissals = new Set<string>()+const activeConversationDismissals = new Set<string>()++function conversationKey(target: NativeSystemNotificationConversation) {+ return target.kind === "dm"+ ? `dm:${target.channelId}`+ : `server:${target.serverId}:${target.channelId}`+}++function dismissNativeSystemNotificationConversation(+ platform: NativeSystemNotificationPlatform,+ viewerUserId: string,+ target: NativeSystemNotificationConversation,+) {+ if (platform === "desktop") {+ return dismissDesktopSystemNotificationConversation(viewerUserId, target)+ }+ return dismissMobileSystemNotificationConversation(viewerUserId, target.channelId)+}++function drainNativeSystemNotificationConversationDismissals(+ platform: NativeSystemNotificationPlatform,+ viewerUserId: string,+ queue: ReturnType<typeof createNativeSystemNotificationConversationDismissalQueue>,+) {+ for (const target of queue.pending(platform, viewerUserId)) {+ const key = `${platform}:${viewerUserId}:${conversationKey(target)}`+ if (activeConversationDismissals.has(key)) continue+ activeConversationDismissals.add(key)+ void dismissNativeSystemNotificationConversation(platform, viewerUserId, target)+ .then(() => { queue.complete(platform, viewerUserId, target) })+ .catch(() => undefined)+ .finally(() => { activeConversationDismissals.delete(key) })+ }+}++export function useNativeSystemNotificationConversationDismissal(+ viewerUserId: string,+ target: NativeSystemNotificationConversation,+ ready: boolean,+) {+ const kind = target.kind+ const channelId = target.channelId+ const serverId = target.kind === "server" ? target.serverId : undefined+ useEffect(() => {+ if (!ready || (!isDesktop() && !isMobile())) return+ const platform = isDesktop() ? "desktop" : "mobile"+ const dismissalTarget: NativeSystemNotificationConversation = kind === "server"+ ? { kind, serverId: serverId!, channelId }+ : { kind, channelId }+ const queue = createNativeSystemNotificationConversationDismissalQueue({+ getItem: (storageKey) => window.localStorage.getItem(storageKey),+ setItem: (storageKey, value) => window.localStorage.setItem(storageKey, value),+ removeItem: (storageKey) => window.localStorage.removeItem(storageKey),+ })+ queue.queue(platform, viewerUserId, dismissalTarget)+ drainNativeSystemNotificationConversationDismissals(platform, viewerUserId, queue)+ }, [channelId, kind, ready, serverId, viewerUserId])+}function dismissPendingNativeSystemNotification(platform: "desktop" | "mobile",@@ -254,6 +319,11 @@ export function useNativeSystemNotifications(viewerUserId: string) {now: () => Date.now(),})const pathname = new URL(window.location.href).pathname+ const conversationDismissals = createNativeSystemNotificationConversationDismissalQueue({+ getItem: (key) => window.localStorage.getItem(key),+ setItem: (key, value) => window.localStorage.setItem(key, value),+ removeItem: (key) => window.localStorage.removeItem(key),+ })const inbox = createDesktopSystemNotificationInboxOpener({getItem: (key) => window.sessionStorage.getItem(key),setItem: (key, value) => window.sessionStorage.setItem(key, value),@@ -267,6 +337,11 @@ export function useNativeSystemNotifications(viewerUserId: string) {})if (isDesktop()) {+ const drainConversations = () => drainNativeSystemNotificationConversationDismissals(+ "desktop",+ viewerUserId,+ conversationDismissals,+ )const dismissPending = () => dismissPendingNativeSystemNotification("desktop",pathname,@@ -274,7 +349,10 @@ export function useNativeSystemNotifications(viewerUserId: string) {dismissDesktopSystemNotification,)dismissPending()+ drainConversations()window.addEventListener("focus", dismissPending)+ window.addEventListener("focus", drainConversations)+ window.addEventListener("online", drainConversations)const browserDeps: DesktopSystemNotificationActivationDeps = {listen: listenDesktopSystemNotificationActivations,take: takeDesktopSystemNotificationActivation,@@ -291,6 +369,8 @@ export function useNativeSystemNotifications(viewerUserId: string) {void controller.connect().catch(() => controller.dispose())return () => {window.removeEventListener("focus", dismissPending)+ window.removeEventListener("focus", drainConversations)+ window.removeEventListener("online", drainConversations)controller.dispose()inbox.dispose()}@@ -334,6 +414,7 @@ export function useNativeSystemNotifications(viewerUserId: string) {const synchronize = () => {dismissPending()+ drainNativeSystemNotificationConversationDismissals("mobile", viewerUserId, conversationDismissals)void registration.sync()void activation.drain()}@@ -344,6 +425,7 @@ export function useNativeSystemNotifications(viewerUserId: string) {document.addEventListener("visibilitychange", onVisibilityChange)void inbox.resume()+ drainNativeSystemNotificationConversationDismissals("mobile", viewerUserId, conversationDismissals)void (async () => {try {const stop = await listenMobileSystemNotificationSignals(synchronize)diff --git a/src/web/src/lib/community/desktop-system-notification.test.ts b/src/web/src/lib/community/desktop-system-notification.test.tsindex ceeeb5726..5c76140e6 100644--- a/src/web/src/lib/community/desktop-system-notification.test.ts+++ b/src/web/src/lib/community/desktop-system-notification.test.ts@@ -5,6 +5,7 @@ import { communityKeys } from "@/lib/query-keys"import {buildDesktopSystemNotificationCandidate,dismissDesktopSystemNotification,+ dismissDesktopSystemNotificationConversation,listenDesktopSystemNotificationActivations,resolveDesktopSystemNotificationCandidate,retryDesktopSystemNotificationActivation,@@ -437,6 +438,18 @@ describe("desktop system notification activation bridge", () => {)})+ it("dismisses only one exact account and conversation scope", async () => {+ invoke.mockResolvedValueOnce(undefined)+ const target = { kind: "server" as const, serverId: "server_1", channelId: "channel_1" }+ await expect(+ dismissDesktopSystemNotificationConversation("viewer_1", target),+ ).resolves.toBeUndefined()+ expect(invoke).toHaveBeenCalledWith(+ "desktop_system_notification_dismiss_conversation",+ { viewerUserId: "viewer_1", target },+ )+ })+it("re-arms exactly one native notification id", async () => {invoke.mockResolvedValueOnce(undefined)const notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"diff --git a/src/web/src/lib/community/desktop-system-notification.ts b/src/web/src/lib/community/desktop-system-notification.tsindex 9784a8f47..d5a7abe4b 100644--- a/src/web/src/lib/community/desktop-system-notification.ts+++ b/src/web/src/lib/community/desktop-system-notification.ts@@ -176,3 +176,10 @@ export async function retryDesktopSystemNotificationActivation(notificationId: sexport async function dismissDesktopSystemNotification(notificationId: string): Promise<void> {await tauriInvoke("desktop_system_notification_dismiss", { notificationId })}++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 })+}diff --git a/src/web/src/lib/community/mobile-system-notification.test.ts b/src/web/src/lib/community/mobile-system-notification.test.tsindex 1dae0b8d9..f854ebb31 100644--- a/src/web/src/lib/community/mobile-system-notification.test.ts+++ b/src/web/src/lib/community/mobile-system-notification.test.ts@@ -6,6 +6,7 @@ import {createMobileSystemNotificationRegistrationController,deleteMobileSystemNotificationRegistration,dismissMobileSystemNotification,+ dismissMobileSystemNotificationConversation,listenMobileSystemNotificationSignals,parseMobileSystemNotificationActivation,parseMobileSystemNotificationPermission,@@ -176,6 +177,21 @@ describe("mobile notification native adapter", () => {{ notificationId },)await expect(dismissMobileSystemNotification("bad")).rejects.toThrow("invalid_notification_id")++ nativeMocks.invoke.mockResolvedValueOnce(undefined)+ await expect(+ dismissMobileSystemNotificationConversation("viewer_1", "channel_1"),+ ).resolves.toBeUndefined()+ expect(nativeMocks.invoke).toHaveBeenLastCalledWith(+ "mobile_system_notification_dismiss_conversation",+ { viewerUserId: "viewer_1", targetId: "channel_1" },+ )+ await expect(+ dismissMobileSystemNotificationConversation("viewer_1", "../channel"),+ ).rejects.toThrow("invalid_target_id")+ await expect(+ dismissMobileSystemNotificationConversation("../viewer", "channel_1"),+ ).rejects.toThrow("invalid_viewer_user_id")})it("bridges native signals and swallows unlisten failures", async () => {diff --git a/src/web/src/lib/community/mobile-system-notification.ts b/src/web/src/lib/community/mobile-system-notification.tsindex 357167b70..e05a4fd49 100644--- a/src/web/src/lib/community/mobile-system-notification.ts+++ b/src/web/src/lib/community/mobile-system-notification.ts@@ -200,6 +200,15 @@ export async function dismissMobileSystemNotification(notificationId: string): Pawait tauriInvoke("mobile_system_notification_dismiss", { notificationId })}+export async function dismissMobileSystemNotificationConversation(+ viewerUserId: string,+ targetId: string,+): Promise<void> {+ if (!isSafeId(viewerUserId)) throw new Error("invalid_viewer_user_id")+ if (!isSafeId(targetId)) throw new Error("invalid_target_id")+ await tauriInvoke("mobile_system_notification_dismiss_conversation", { viewerUserId, targetId })+}+export async function postMobileSystemNotificationRegistration(snapshot: MobileSystemNotificationRegistration,fetchImpl: typeof fetch = fetch,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.tsindex e1403f71a..c6fa906a7 100644--- a/src/web/src/lib/community/native-system-notification-dismissal.test.ts+++ b/src/web/src/lib/community/native-system-notification-dismissal.test.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi } from "vitest"import {+ createNativeSystemNotificationConversationDismissalQueue,createNativeSystemNotificationDismissalQueue,type NativeSystemNotificationDismissalDeps,} from "./native-system-notification-dismissal"@@ -74,3 +75,81 @@ describe("native notification dismissal handoff", () => {expect(removeItem).toHaveBeenCalledOnce()})})++describe("native notification conversation dismissal retry queue", () => {+ const serverTarget = {+ kind: "server" as const,+ serverId: "server_1",+ channelId: "channel_1",+ }+ const otherTarget = {+ kind: "server" as const,+ serverId: "server_1",+ channelId: "channel_2",+ }++ it("survives recreation and consumes only the exact account and target", () => {+ const values = new Map<string, string>()+ const first = createNativeSystemNotificationConversationDismissalQueue(deps(values))+ expect(first.queue("desktop", "viewer_1", serverTarget)).toBe(true)+ expect(first.queue("desktop", "viewer_1", otherTarget)).toBe(true)++ const restored = createNativeSystemNotificationConversationDismissalQueue(deps(values))+ expect(restored.pending("desktop", "viewer_2")).toEqual([])+ expect(restored.pending("mobile", "viewer_1")).toEqual([])+ expect(restored.pending("desktop", "viewer_1")).toEqual([serverTarget, otherTarget])++ expect(restored.complete("desktop", "viewer_2", serverTarget)).toBe(false)+ expect(restored.complete("desktop", "viewer_1", serverTarget)).toBe(true)+ expect(restored.pending("desktop", "viewer_1")).toEqual([otherTarget])+ })++ it("deduplicates one scope without consuming it on a native failure", () => {+ const values = new Map<string, string>()+ const queue = createNativeSystemNotificationConversationDismissalQueue(deps(values))+ expect(queue.queue("mobile", "viewer_1", serverTarget)).toBe(true)+ expect(queue.queue("mobile", "viewer_1", serverTarget)).toBe(true)+ expect(queue.pending("mobile", "viewer_1")).toEqual([serverTarget])+ })++ it("round-trips an exact DM target", () => {+ const values = new Map<string, string>()+ const queue = createNativeSystemNotificationConversationDismissalQueue(deps(values))+ const dmTarget = { kind: "dm" as const, channelId: "dm_1" }++ expect(queue.queue("mobile", "viewer_1", dmTarget)).toBe(true)+ expect(queue.pending("mobile", "viewer_1")).toEqual([dmTarget])+ expect(queue.complete("mobile", "viewer_1", dmTarget)).toBe(true)+ expect(values.size).toBe(0)+ })++ it("contains corrupt-storage cleanup and write failures", () => {+ const corruptValues = new Map([+ ["alook:native-system-notification:conversation-dismissals", "corrupt"],+ ])+ const removeItem = vi.fn((key: string) => { corruptValues.delete(key) })+ const corrupt = createNativeSystemNotificationConversationDismissalQueue(deps(+ corruptValues,+ { removeItem },+ ))++ expect(corrupt.pending("desktop", "viewer_1")).toEqual([])+ expect(removeItem).toHaveBeenCalledOnce()+ expect(corruptValues.size).toBe(0)++ const removeBlocked = createNativeSystemNotificationConversationDismissalQueue(deps(+ new Map([["alook:native-system-notification:conversation-dismissals", "corrupt"]]),+ { removeItem: () => { throw new Error("blocked") } },+ ))+ expect(removeBlocked.pending("desktop", "viewer_1")).toEqual([])++ const writeBlocked = createNativeSystemNotificationConversationDismissalQueue(deps(+ new Map(),+ { setItem: () => { throw new Error("blocked") } },+ ))+ expect(writeBlocked.queue("mobile", "viewer_1", {+ kind: "dm",+ channelId: "dm_1",+ })).toBe(false)+ })+})diff --git a/src/web/src/lib/community/native-system-notification-dismissal.ts b/src/web/src/lib/community/native-system-notification-dismissal.tsindex 78f4f82b9..7344163ef 100644--- a/src/web/src/lib/community/native-system-notification-dismissal.ts+++ b/src/web/src/lib/community/native-system-notification-dismissal.ts@@ -1,5 +1,9 @@export type NativeSystemNotificationPlatform = "desktop" | "mobile"+export type NativeSystemNotificationConversation =+ | { kind: "server"; serverId: string; channelId: string }+ | { kind: "dm"; channelId: string }+type PendingDismissal = {version: 1platform: NativeSystemNotificationPlatform@@ -22,6 +26,116 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-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"])+const CONVERSATION_KEY = "alook:native-system-notification:conversation-dismissals"+const CONVERSATION_VERSION = 1 as const+const MAX_CONVERSATION_DISMISSALS = 64++type PendingConversationDismissal = {+ version: 1+ platform: NativeSystemNotificationPlatform+ viewerUserId: string+ target: NativeSystemNotificationConversation+}++function validSafeId(value: unknown): value is string {+ return typeof value === "string" && new RegExp(`^${SAFE_ID}$`).test(value)+}++function validConversation(value: unknown): value is NativeSystemNotificationConversation {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false+ const target = value as Record<string, unknown>+ if (target.kind === "dm") {+ return Object.keys(target).length === 2 && validSafeId(target.channelId)+ }+ return target.kind === "server"+ && Object.keys(target).length === 3+ && validSafeId(target.serverId)+ && validSafeId(target.channelId)+}++function sameConversation(+ left: NativeSystemNotificationConversation,+ right: NativeSystemNotificationConversation,+) {+ return left.kind === right.kind+ && left.channelId === right.channelId+ && (left.kind === "dm" || (right.kind === "server" && left.serverId === right.serverId))+}++export function createNativeSystemNotificationConversationDismissalQueue(+ deps: Pick<NativeSystemNotificationDismissalDeps, "getItem" | "setItem" | "removeItem">,+) {+ function remove() {+ try { deps.removeItem(CONVERSATION_KEY) } catch {}+ }++ function read(): PendingConversationDismissal[] {+ let raw: string | null+ try { raw = deps.getItem(CONVERSATION_KEY) } catch { return [] }+ if (raw === null) return []+ try {+ const values = JSON.parse(raw) as unknown+ if (!Array.isArray(values) || values.length > MAX_CONVERSATION_DISMISSALS) throw new Error()+ const valid = values.every((value) => {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false+ const entry = value as Record<string, unknown>+ return Object.keys(entry).length === 4+ && entry.version === CONVERSATION_VERSION+ && (entry.platform === "desktop" || entry.platform === "mobile")+ && validSafeId(entry.viewerUserId)+ && validConversation(entry.target)+ })+ if (!valid) throw new Error()+ return values as PendingConversationDismissal[]+ } catch {+ remove()+ return []+ }+ }++ function write(values: PendingConversationDismissal[]) {+ try {+ if (values.length === 0) deps.removeItem(CONVERSATION_KEY)+ else deps.setItem(CONVERSATION_KEY, JSON.stringify(values))+ return true+ } catch {+ return false+ }+ }++ return {+ queue(+ platform: NativeSystemNotificationPlatform,+ viewerUserId: string,+ target: NativeSystemNotificationConversation,+ ) {+ if (!validSafeId(viewerUserId) || !validConversation(target)) return false+ const values = read()+ if (values.some((entry) => entry.platform === platform+ && entry.viewerUserId === viewerUserId+ && sameConversation(entry.target, target))) return true+ return write([...values, { version: CONVERSATION_VERSION, platform, viewerUserId, target }]+ .slice(-MAX_CONVERSATION_DISMISSALS))+ },+ pending(platform: NativeSystemNotificationPlatform, viewerUserId: string) {+ if (!validSafeId(viewerUserId)) return []+ return read()+ .filter((entry) => entry.platform === platform && entry.viewerUserId === viewerUserId)+ .map((entry) => entry.target)+ },+ complete(+ platform: NativeSystemNotificationPlatform,+ viewerUserId: string,+ target: NativeSystemNotificationConversation,+ ) {+ const values = read()+ const next = values.filter((entry) => !(entry.platform === platform+ && entry.viewerUserId === viewerUserId+ && sameConversation(entry.target, target)))+ return next.length !== values.length && write(next)+ },+ }+}export function createNativeSystemNotificationDismissalQueue(deps: NativeSystemNotificationDismissalDeps,