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(notifications): consume system notifications and unify click navigation (#934)
Generb22aa6b815af
diff --git a/scripts/ci/mobile-system-notification.test.ts b/scripts/ci/mobile-system-notification.test.tsindex f60258f26..ec32f7eee 100644--- a/scripts/ci/mobile-system-notification.test.ts+++ b/scripts/ci/mobile-system-notification.test.ts@@ -192,9 +192,10 @@ describe("mobile system notification contract", () => {})it("installs the iOS notification delegate synchronously before deferred app work", () => {- const initializer = iosPlugin.slice(- iosPlugin.indexOf("override init()"),- iosPlugin.indexOf("\n deinit"),+ const plugin = iosPlugin.slice(iosPlugin.indexOf("final class MobilePushPlugin: Plugin"))+ const initializer = plugin.slice(+ plugin.indexOf("override init()"),+ plugin.indexOf("\n deinit"),)const delegateAssignment = initializer.indexOf("UNUserNotificationCenter.current().delegate = bridge.notificationHandler",diff --git a/src/desktop/src-tauri/Cargo.toml b/src/desktop/src-tauri/Cargo.tomlindex 7cb7dea68..be870f01d 100644--- a/src/desktop/src-tauri/Cargo.toml+++ b/src/desktop/src-tauri/Cargo.toml@@ -36,7 +36,7 @@ tauri-plugin-notification = "2"tauri-plugin-updater = "2"tauri-plugin-dialog = "2"tauri-plugin-clipboard-manager = "2"-tokio = { version = "1", features = ["macros"] }+tokio = { version = "1", features = ["macros", "time"] }command-group = "5.0.1"tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }@@ -48,7 +48,7 @@ objc2-foundation = { version = "=0.3.2", features = ["NSArray", "NSDictionary",block2 = "=0.6.2"objc2-app-kit = { version = "=0.3.2", features = ["NSView", "NSWindow", "NSColor"] }objc2-user-notifications = { version = "=0.3.2", default-features = false, features = ["std", "UNNotification", "UNNotificationContent", "UNNotificationRequest", "UNNotificationResponse", "UNNotificationSound", "UNNotificationTrigger", "UNUserNotificationCenter", "block2"] }-objc2-web-kit = { version = "=0.3.2", features = ["WKWebView"], default-features = false }+objc2-web-kit = { version = "=0.3.2", features = ["WKWebView", "block2"], default-features = false }[target."cfg(windows)".dependencies]webview2-com = "=0.39.1"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 0984ef397..ead91d789 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@@ -51,6 +51,7 @@ class AlookFirebaseMessagingService : FirebaseMessagingService() {requestCode,notification,)+ MobilePushPlugin.signalCurrent()}companion object {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 dfe20b46a..70e1f86f2 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@@ -230,13 +230,62 @@ final class MobilePushStore {}}+func mobilePushPresentationScript(_ route: MobilePushRoute) -> String? {+ guard let viewer = route.viewerUserId,+ let data = try? JSONSerialization.data(withJSONObject: ["viewerUserId": viewer, "targetId": route.targetId]),+ let identity = String(data: data, encoding: .utf8)+ else { return nil }+ return "(()=>{try{return window.alookNativeNotificationPresentationV1?.(\(identity))===true?'suppress':'present'}catch{return 'present'}})()"+}++final class MobilePushPresentationCompletion: @unchecked Sendable {+ private let lock = NSLock()+ private var completion: (@Sendable (UNNotificationPresentationOptions) -> Void)?+ private var deadline: DispatchWorkItem?++ init(_ completion: @escaping @Sendable (UNNotificationPresentationOptions) -> Void) {+ self.completion = completion+ let deadline = DispatchWorkItem { [weak self] in self?.finish(suppress: false) }+ self.deadline = deadline+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + .milliseconds(500), execute: deadline)+ }++ @discardableResult+ func finish(suppress: Bool) -> Bool {+ lock.lock()+ let callback = completion+ completion = nil+ let timeout = deadline+ deadline = nil+ lock.unlock()+ guard let callback else { return false }+ timeout?.cancel()+ callback(suppress ? [] : [.banner, .list, .sound])+ return true+ }++ deinit { finish(suppress: false) }+}+private final class MobilePushNotificationHandler: NSObject, UNUserNotificationCenterDelegate {func userNotificationCenter(_ center: UNUserNotificationCenter,willPresent notification: UNNotification,- withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void+ withCompletionHandler completionHandler: @escaping @Sendable (UNNotificationPresentationOptions) -> Void) {- completionHandler([.banner, .list, .sound])+ guard let route = MobilePushRoute.from(notification.request.content.userInfo),+ let script = mobilePushPresentationScript(route)+ else { completionHandler([.banner, .list, .sound]); return }+ let decision = MobilePushPresentationCompletion(completionHandler)+ DispatchQueue.main.async {+ guard let webview = MobilePushBridge.shared.plugin?.presentationWebview else {+ decision.finish(suppress: false)+ return+ }+ webview.evaluateJavaScript(script) { result, error in+ decision.finish(suppress: error == nil && (result as? String) == "suppress")+ }+ }}func userNotificationCenter(@@ -404,6 +453,12 @@ final class MobilePushPlugin: Plugin {private let bridge = MobilePushBridge.sharedprivate var listener: Channel?private var lifecycleObserver: NSObjectProtocol?+ weak var presentationWebview: WKWebView?++ override public func load(webview: WKWebView) {+ super.load(webview: webview)+ presentationWebview = webview+ }override init() {super.init()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 8784227fd..fc8c01925 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@@ -1,7 +1,41 @@import XCTest+import UserNotifications@testable import tauri_plugin_mobile_pushfinal class MobilePushPluginTests: XCTestCase {+ func testPresentationRequiresViewerAndUsesOnlyIdentityInThePureScript() {+ let route = MobilePushRoute(notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e", messageId: "message_1", targetId: "channel_1")+ XCTAssertNil(mobilePushPresentationScript(route))+ let script = mobilePushPresentationScript(MobilePushRoute(notificationId: route.notificationId, messageId: route.messageId, targetId: route.targetId, viewerUserId: "viewer_1"))!+ XCTAssertTrue(script.contains("alookNativeNotificationPresentationV1"))+ XCTAssertTrue(script.contains("===true"))+ XCTAssertFalse(script.contains(route.notificationId))+ XCTAssertFalse(script.contains(route.messageId))+ }++ func testPresentationAuthorizationCompletesOnceAndCancelsFallback() {+ let completed = expectation(description: "one empty completion")+ completed.assertForOverFulfill = true+ let decision = MobilePushPresentationCompletion { options in+ XCTAssertTrue(options.isEmpty)+ completed.fulfill()+ }+ XCTAssertTrue(decision.finish(suppress: true))+ XCTAssertFalse(decision.finish(suppress: false))+ wait(for: [completed], timeout: 1)+ }++ func testPresentationTimeoutUsesNormalOptionsAndRejectsLateAuthorization() {+ let completed = expectation(description: "normal deadline completion")+ completed.assertForOverFulfill = true+ let decision = MobilePushPresentationCompletion { options in+ XCTAssertEqual(options, [.banner, .list, .sound])+ completed.fulfill()+ }+ wait(for: [completed], timeout: 2)+ XCTAssertFalse(decision.finish(suppress: true))+ }+func testRouteAcceptsOnlyCanonicalAllowlistedValues() {XCTAssertEqual(MobilePushRoute.create(diff --git a/src/desktop/src-tauri/src/system_notifications.rs b/src/desktop/src-tauri/src/system_notifications.rsindex 1e57801ae..b44f2543a 100644--- a/src/desktop/src-tauri/src/system_notifications.rs+++ b/src/desktop/src-tauri/src/system_notifications.rs@@ -89,6 +89,13 @@ impl NotificationConversation {}impl NotificationTarget {+ #[cfg(any(target_os = "macos", test))]+ fn channel_id(&self) -> &str {+ match self {+ Self::Server { channel_id, .. } | Self::Dm { channel_id, .. } => channel_id,+ }+ }+fn message_id(&self) -> &str {match self {Self::Server { message_id, .. } | Self::Dm { message_id, .. } => message_id,@@ -239,6 +246,19 @@ impl NotificationRecord {true}+ #[cfg(any(target_os = "macos", test))]+ fn presentation_identity(&self, notification_id: &str) -> Option<(String, String)> {+ self.recent+ .iter()+ .find(|item| item.notification_id == notification_id)+ .map(|item| {+ (+ item.viewer_user_id.clone(),+ item.target.channel_id().to_string(),+ )+ })+ }+fn notification_ids(&self,viewer_user_id: &str,@@ -505,6 +525,8 @@ pub async fn desktop_system_notification_show(})?;return Err("notification_unavailable");}+ #[cfg(any(windows, target_os = "linux"))]+ state.notify();Ok(())}@@ -764,6 +786,169 @@ async fn wait_for_macos_completion(.map_err(|_| ())?}+#[cfg(target_os = "macos")]+struct SendablePresentationCompletion(+ block2::RcBlock<dyn Fn(objc2_user_notifications::UNNotificationPresentationOptions)>,+);++// SAFETY: This is only Apple's escaping UN presentation completion. Apple permits+// its invocation from any queue. The owned heap copy is taken once under a mutex;+// no WebKit object, arbitrary block, or borrowed delegate value crosses threads.+#[cfg(target_os = "macos")]+unsafe impl Send for SendablePresentationCompletion {}++#[cfg(target_os = "macos")]+struct PresentationCompletion {+ pending: Mutex<Option<SendablePresentationCompletion>>,+ deadline: Mutex<Option<tauri::async_runtime::JoinHandle<()>>>,+}++#[cfg(target_os = "macos")]+impl PresentationCompletion {+ fn new(owned: SendablePresentationCompletion) -> Arc<Self> {+ let decision = Arc::new(Self {+ pending: Mutex::new(Some(owned)),+ deadline: Mutex::new(None),+ });+ let deadline_decision = decision.clone();+ let deadline = tauri::async_runtime::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;+ deadline_decision.finish(false);+ });+ {+ let mut slot = decision+ .deadline+ .lock()+ .unwrap_or_else(|error| error.into_inner());+ if decision+ .pending+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .is_some()+ {+ *slot = Some(deadline);+ } else {+ deadline.abort();+ }+ }+ decision+ }++ fn finish(&self, suppress: bool) -> bool {+ let completion = self+ .pending+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .take();+ let Some(completion) = completion else {+ return false;+ };+ if let Some(deadline) = self+ .deadline+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .take()+ {+ deadline.abort();+ }+ completion.0.call((macos_presentation_options(suppress),));+ true+ }+}++#[cfg(target_os = "macos")]+impl Drop for PresentationCompletion {+ fn drop(&mut self) {+ self.finish(false);+ }+}++#[cfg(target_os = "macos")]+fn macos_presentation_options(+ suppress: bool,+) -> objc2_user_notifications::UNNotificationPresentationOptions {+ use objc2_user_notifications::UNNotificationPresentationOptions as Options;+ if suppress {+ Options::empty()+ } else {+ Options::Banner | Options::List | Options::Sound+ }+}++#[cfg(target_os = "macos")]+fn decide_macos_presentation(+ app: &AppHandle,+ identifier: String,+ completion: &block2::DynBlock<+ dyn Fn(objc2_user_notifications::UNNotificationPresentationOptions),+ >,+) {+ use block2::RcBlock;+ use objc2::{runtime::AnyObject, MainThreadMarker};+ use objc2_foundation::{NSError, NSString};+ use objc2_web_kit::WKWebView;++ let identity = app+ .try_state::<DesktopSystemNotificationState>()+ .and_then(|state| state.record.lock().ok()?.presentation_identity(&identifier));+ let Some((viewer, target)) = identity else {+ completion.call((macos_presentation_options(false),));+ return;+ };+ // SAFETY: The delegate supplies a valid block with this exact signature.+ // Heap-copy it before returning from the delegate callback.+ let owned = unsafe { RcBlock::copy(completion as *const _ as *mut _) };+ let Some(owned) = owned else {+ completion.call((macos_presentation_options(false),));+ return;+ };+ let decision = PresentationCompletion::new(SendablePresentationCompletion(owned));+ let Some(window) = app.get_webview_window("main") else {+ decision.finish(false);+ return;+ };+ let identity = serde_json::json!({ "viewerUserId": viewer, "targetId": target });+ let script = format!("(()=>{{try{{return window.alookNativeNotificationPresentationV1?.({identity})===true?'suppress':'present'}}catch{{return 'present'}}}})()");+ let main_decision = decision.clone();+ let app = app.clone();+ if window+ .with_webview(move |platform| {+ if MainThreadMarker::new().is_none() {+ main_decision.finish(false);+ return;+ }+ let result_decision = main_decision.clone();+ let callback = RcBlock::new(move |result: *mut AnyObject, error: *mut NSError| {+ // SAFETY: WK owns these callback arguments until this invocation ends.+ let suppress = error.is_null()+ && unsafe { result.as_ref() }+ .and_then(|value| value.downcast_ref::<NSString>())+ .is_some_and(|value| value.to_string() == "suppress");+ if result_decision.finish(suppress) && suppress {+ if let Some(state) = app.try_state::<DesktopSystemNotificationState>() {+ let _ = state.transact(|record| {+ record.complete_dismissals(&[identifier.clone()]);+ Ok(())+ });+ }+ }+ });+ // SAFETY: Tauri supplies the live WKWebView on the main thread. This+ // borrowed pointer is used only here; WK copies its escaping completion.+ unsafe {+ let webview = &*platform.inner().cast::<WKWebView>();+ webview.evaluateJavaScript_completionHandler(+ &NSString::from_str(&script),+ Some(&callback),+ );+ }+ })+ .is_err()+ {+ decision.finish(false);+ }+}+#[cfg(target_os = "macos")]fn install_macos_delegate(app: &AppHandle) {use block2::DynBlock;@@ -793,12 +978,14 @@ fn install_macos_delegate(app: &AppHandle) {fn will_present(&self,_center: &UNUserNotificationCenter,- _notification: &UNNotification,+ notification: &UNNotification,completion: &DynBlock<dyn Fn(UNNotificationPresentationOptions)>,) {- completion.call((UNNotificationPresentationOptions::Banner- | UNNotificationPresentationOptions::List- | UNNotificationPresentationOptions::Sound,));+ decide_macos_presentation(+ &self.ivars().app,+ notification.request().identifier().to_string(),+ completion,+ );}#[unsafe(method(userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:))]@@ -938,6 +1125,75 @@ mod tests {}}+ #[test]+ fn presentation_identity_uses_only_the_original_bounded_record_including_dismissed_items() {+ let mut record = NotificationRecord::new();+ let id = record.claim(&candidate("viewer_1", "message_1")).unwrap();+ record.complete_dismissals(&[id.clone()]);+ assert_eq!(+ record.presentation_identity(&id),+ Some(("viewer_1".into(), "channel_1".into()))+ );+ assert_eq!(record.presentation_identity("unknown"), None);+ }++ #[cfg(target_os = "macos")]+ fn presentation_test_completion(+ ) -> (Arc<PresentationCompletion>, std::sync::mpsc::Receiver<u64>) {+ let (sender, receiver) = std::sync::mpsc::channel();+ let callback = block2::RcBlock::new(+ move |options: objc2_user_notifications::UNNotificationPresentationOptions| {+ sender.send(options.bits() as u64).unwrap();+ },+ );+ (+ PresentationCompletion::new(SendablePresentationCompletion(callback)),+ receiver,+ )+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn presentation_first_completion_wins_and_cancels_the_deadline() {+ let (decision, receiver) = presentation_test_completion();+ assert!(decision.finish(true));+ assert!(!decision.finish(false));+ assert_eq!(receiver.recv().unwrap(), 0);+ assert!(receiver+ .recv_timeout(std::time::Duration::from_millis(600))+ .is_err());+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn presentation_deadline_shows_normally_and_late_true_cannot_consume_it() {+ let (decision, receiver) = presentation_test_completion();+ assert_eq!(+ receiver+ .recv_timeout(std::time::Duration::from_secs(2))+ .unwrap(),+ macos_presentation_options(false).bits() as u64+ );+ assert!(!decision.finish(true));+ assert!(receiver.try_recv().is_err());+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn presentation_racing_outcomes_take_the_completion_once() {+ let (decision, receiver) = presentation_test_completion();+ let fallback = decision.clone();+ let thread = std::thread::spawn(move || fallback.finish(false));+ let authorized = decision.finish(true);+ let normal = thread.join().unwrap();+ assert_ne!(authorized, normal);+ assert_eq!(+ receiver.recv().unwrap(),+ macos_presentation_options(authorized).bits() as u64+ );+ assert!(receiver.try_recv().is_err());+ }+#[test]fn deterministic_ids_are_stable_scoped_and_uuid_shaped() {let first = deterministic_notification_id("viewer_1", "message_1");diff --git a/src/web/src/app/c/@sidebar/messages/[messageId]/page.tsx b/src/web/src/app/c/@sidebar/messages/[messageId]/page.tsxnew file mode 100644index 000000000..6b6e586bf--- /dev/null+++ b/src/web/src/app/c/@sidebar/messages/[messageId]/page.tsx@@ -0,0 +1,3 @@+export default function MessageSidebar() {+ return null+}diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsxindex 0f42c9a31..8395f744c 100644--- a/src/web/src/app/c/community-shell.tsx+++ b/src/web/src/app/c/community-shell.tsx@@ -18,7 +18,6 @@ import {} from "@/contexts/community/current-user"import { useCommunityWs } from "@/hooks/community/use-community-ws"import { useNotificationSettings } from "@/hooks/community/use-notification-settings"-import { useNativeSystemNotifications } from "@/hooks/community/use-native-system-notifications"import { useAccountAttention } from "@/hooks/community/use-account-attention"import { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"import { CommunityOnboardingForm } from "@/components/community/onboarding/community-onboarding-form"@@ -97,7 +96,6 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {useNotificationSettings()useAccountAttention()- useNativeSystemNotifications(currentUser.id)// Wire the WS handler once for the whole community subtree. `viewerUserId`// powers the `me` flag on incoming reactions — passing null would leave that// flag stuck at false for the viewer's own reactions.diff --git a/src/web/src/app/c/messages/[messageId]/page.tsx b/src/web/src/app/c/messages/[messageId]/page.tsxnew file mode 100644index 000000000..2880888bb--- /dev/null+++ b/src/web/src/app/c/messages/[messageId]/page.tsx@@ -0,0 +1,6 @@+import { MessageRoute } from "@/components/community/messages/message-route"++export default async function MessagePage({ params }: { params: Promise<{ messageId: string }> }) {+ const { messageId } = await params+ return <MessageRoute messageId={messageId} />+}diff --git a/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsx b/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsxindex 4a73f9d84..af22dbccb 100644--- a/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsx+++ b/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsx@@ -3,6 +3,7 @@ import { ChannelHeaderSkeleton } from "./channel-header"import { ConversationMessageSkeleton } from "./conversation-message-skeleton"import { ForumViewSkeleton } from "./forum-view"import { ComposerSkeleton } from "../messages/composer"+import { tid } from "@/lib/community/testids"/** Inert main-area placeholder used until canonical route metadata proves the subtype. */export function ConversationResolutionPendingFrame({@@ -15,6 +16,7 @@ export function ConversationResolutionPendingFrame({<><ChannelHeaderSkeleton kind="forum" /><main+ data-testid={tid.conversationResolutionPending}aria-busy="true"aria-label="Loading forum"data-community-conversation-subtype="forum"@@ -30,6 +32,7 @@ export function ConversationResolutionPendingFrame({<><ChannelHeaderSkeleton kind={subtype} /><main+ data-testid={tid.conversationResolutionPending}aria-busy="true"aria-label={subtype === "thread" ? "Loading thread" : "Loading conversation"}data-community-conversation-subtype={subtype}@@ -43,6 +46,7 @@ export function ConversationResolutionPendingFrame({}return (<main+ data-testid={tid.conversationResolutionPending}aria-busy="true"aria-label="Resolving conversation"data-community-conversation-subtype="unknown"diff --git a/src/web/src/components/community/messages/message-route.dom.test.tsx b/src/web/src/components/community/messages/message-route.dom.test.tsxnew file mode 100644index 000000000..7f82722e3--- /dev/null+++ b/src/web/src/components/community/messages/message-route.dom.test.tsx@@ -0,0 +1,103 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { createElement, type PropsWithChildren } from "react"+import { act, fireEvent, render, screen, waitFor } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { CommunityRouteContext } from "../shell/community-route-context"+import type { CommunityNavigationController } from "../shell/use-community-navigation-controller"+import { normalizeCommunityHref } from "@/lib/community/community-route"+import { communityKeys } from "@/lib/query-keys"+import { ApiError } from "@/lib/errors"+import { MessageRoute } from "./message-route"+const api = vi.hoisted(()=>({read:vi.fn()}))+vi.mock("@/lib/community/account-cache-lifecycle", async importOriginal => ({+ ...await importOriginal<typeof import("@/lib/community/account-cache-lifecycle")>(),+ apiFetchCommunity: async (path:string, options:{assertActive?:()=>void}) => {+ options.assertActive?.()+ try { const result=await api.read(path); options.assertActive?.();return result }+ catch(error){options.assertActive?.();throw error}+ },+}))+vi.mock("../shell/community-pending-frame",()=>({CommunityPendingFrame:()=>createElement("div",{role:"status"},"Loading")}))+let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>+let revision=0+let href="/c/messages/message_1"+let navigation:CommunityNavigationController+const openInbox=vi.fn()+beforeEach(async()=>{+ owner=await createCommunityQueryOwner("viewer")+ vi.clearAllMocks();api.read.mockReset();revision=0;href="/c/messages/message_1"+ navigation={publishedHref:href,navigationPending:false,pendingHref:null,+ captureIntent:()=>{const original=revision;return()=>original===revision},+ push:vi.fn(),pushImmediate:vi.fn(),replace:vi.fn(()=>{revision++}),resolveAndPush:vi.fn(),cancelPendingNavigation:vi.fn()}+})+const wrapper=({children}:PropsWithChildren)=>createElement(CommunityTestProvider,{client:owner.client,registry:owner.registry,userId:"viewer",retainOwner:true},+ createElement(CommunityRouteContext,{value:{breakpoint:"desktop",ownerDeleteRouteScope:undefined,frame:{...normalizeCommunityHref(href),revision},navigation,openInbox}},children))+describe("ordinary message page",()=>{+ it.each(["dm","text","forum","thread"])("resolves a %s through the permission door then replaces with its bare conversation URL",async type=>{+ api.read.mockResolvedValueOnce({id:"message_1",channelId:"actual_channel"})+ .mockResolvedValueOnce({id:"actual_channel",type,serverId:type==="dm"?null:"actual_server",archived:false})+ render(<MessageRoute messageId="message_1"/>,{wrapper})+ await waitFor(()=>expect(navigation.replace).toHaveBeenCalledExactlyOnceWith(type==="dm"?"/c/me/actual_channel":"/c/channels/actual_server/actual_channel"))+ expect(api.read.mock.calls.map(([path])=>path)).toEqual(["/api/community/messages/message_1","/api/community/channels/actual_channel"])+ })+ it("does not use a cached canonical message as permission proof",async()=>{+ owner.client.setQueryData(communityKeys.message("message_1"),{id:"message_1",channelId:"cached_channel"})+ api.read.mockRejectedValueOnce(new ApiError("Denied",403))+ render(<MessageRoute messageId="message_1"/>,{wrapper})+ await screen.findByRole("alert")+ expect(navigation.replace).not.toHaveBeenCalled()+ fireEvent.click(screen.getByRole("button",{name:"Open Inbox"}))+ expect(openInbox).toHaveBeenCalledOnce()+ expect(api.read).toHaveBeenCalledExactlyOnceWith("/api/community/messages/message_1")+ })+ it.each(["archived","denied","wrong channel"])("shows the normal unavailable state for %s metadata",async reason=>{+ api.read.mockResolvedValueOnce({id:"message_1",channelId:"channel_1"}).mockResolvedValueOnce({+ id:reason==="wrong channel"?"other":"channel_1",type:"text",serverId:"server_1",+ archived:reason==="archived",accessDecision:{canRead:reason!=="denied"},+ })+ render(<MessageRoute messageId="message_1"/>,{wrapper})+ expect(await screen.findByRole("alert")).toHaveTextContent("This conversation is unavailable")+ expect(navigation.replace).not.toHaveBeenCalled()+ expect(screen.queryByRole("button",{name:"Retry"})).toBeNull()+ })+ it("does not start a resolver for a retained leaf or a pending checkpoint",()=>{+ href="/c/me/friends";navigation.publishedHref=href;navigation.navigationPending=true+ render(<MessageRoute messageId="message_1"/>,{wrapper})+ expect(api.read).not.toHaveBeenCalled();expect(screen.getByRole("status")).toBeVisible()+ })+ it("retries a failed ordinary network read from the visible Retry action",async()=>{+ api.read.mockRejectedValue(new TypeError("Network unavailable"))+ render(<MessageRoute messageId="message_1"/>,{wrapper})+ expect(await screen.findByRole("alert", {}, {timeout:4000})).toHaveTextContent("Could not open this conversation")+ expect(api.read).toHaveBeenCalledTimes(2)+ expect(navigation.replace).not.toHaveBeenCalled()+ api.read.mockResolvedValueOnce({id:"message_1",channelId:"channel_1"})+ .mockResolvedValueOnce({id:"channel_1",type:"dm",serverId:null,archived:false})+ fireEvent.click(screen.getByRole("button",{name:"Retry"}))+ await waitFor(()=>expect(navigation.replace).toHaveBeenCalledExactlyOnceWith("/c/me/channel_1"))+ expect(api.read.mock.calls.map(([path])=>path)).toEqual([+ "/api/community/messages/message_1", "/api/community/messages/message_1",+ "/api/community/messages/message_1", "/api/community/channels/channel_1",+ ])+ })+ it("ignores a delayed message after a newer navigation before capturing a channel token",async()=>{+ let release!:(value:unknown)=>void+ api.read.mockReturnValueOnce(new Promise(resolve=>{release=resolve}))+ render(<MessageRoute messageId="message_1"/>,{wrapper})+ await waitFor(()=>expect(api.read).toHaveBeenCalledOnce())+ revision+++ await act(async()=>release({id:"message_1",channelId:"channel_1"}))+ expect(api.read).toHaveBeenCalledOnce();expect(navigation.replace).not.toHaveBeenCalled()+ })+ it("ignores delayed channel authorization after the originating account retires",async()=>{+ let release!:(value:unknown)=>void+ api.read.mockResolvedValueOnce({id:"message_1",channelId:"channel_1"})+ .mockReturnValueOnce(new Promise(resolve=>{release=resolve}))+ render(<MessageRoute messageId="message_1"/>,{wrapper})+ await waitFor(()=>expect(api.read).toHaveBeenCalledTimes(2))+ act(()=>owner.registry.runtime.lifecycle.setState(state=>({active:false,generation:state.generation+1})))+ await act(async()=>release({id:"channel_1",type:"text",serverId:"server_1"}))+ expect(navigation.replace).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/components/community/messages/message-route.tsx b/src/web/src/components/community/messages/message-route.tsxnew file mode 100644index 000000000..26dad68b7--- /dev/null+++ b/src/web/src/components/community/messages/message-route.tsx@@ -0,0 +1,80 @@+"use client"++import { useEffect, useLayoutEffect, useRef } from "react"+import { useQuery, useQueryClient } from "@tanstack/react-query"+import { useCommunityRouteFrame } from "../shell/community-route-context"+import { CommunityPendingFrame } from "../shell/community-pending-frame"+import { Button } from "@/components/ui/button"+import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"+import type { OpenerPayload } from "@/hooks/community/use-message"+import type { ChannelMetadata } from "@/hooks/community/channel-metadata"+import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"+import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"+import { normalizeCommunityHref } from "@/lib/community/community-route"+import { retryConversationRead, withConversationReadDeadline } from "@/lib/community/conversation-read"+import { systemNotificationHref } from "@/lib/community/system-notification-route"+import { communityKeys } from "@/lib/query-keys"+import { ApiError } from "@/lib/errors"+import { tid } from "@/lib/community/testids"++const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/++export function MessageRoute({ messageId }: { messageId: string }) {+ const client = useQueryClient()+ const { frame, navigation, openInbox } = useCommunityRouteFrame()+ const href = `/c/messages/${encodeURIComponent(messageId)}`+ const active = SAFE_ID.test(messageId) && frame.pathname === href+ && normalizeCommunityHref(navigation.publishedHref).pathname === href && !navigation.navigationPending+ const current = useRef({ active, navigation })+ useLayoutEffect(() => { current.current = { active, navigation } }, [active, navigation])+ const source = useCommunityViewSource(`message-route:${messageId}`, active)+ const query = useQuery({+ queryKey: communityKeys.messageRoute(messageId), enabled: active, gcTime: 0, staleTime: 0,+ retry: retryConversationRead, networkMode: "always",+ queryFn: async ({ signal }) => {+ const original = source.capture()+ const intent = current.current.navigation.captureIntent()+ const account = captureCommunityLiveSnapshotToken(client)+ const assertCurrent = () => {+ original()+ if (!current.current.active || !intent()) throw new DOMException("Retired message route", "AbortError")+ assertCommunityLiveSnapshotTokenCurrent(client, account, signal)+ }+ return withConversationReadDeadline(AbortSignal.any([signal, original.signal]), async (readSignal) => {+ assertCurrent()+ const message = await apiFetchCommunity<OpenerPayload>(`/api/community/messages/${encodeURIComponent(messageId)}`,+ { signal: readSignal, assertActive: assertCurrent }, account)+ assertCurrent()+ if (message.id !== messageId || !message.channelId || !SAFE_ID.test(message.channelId)) throw new ApiError("Conversation unavailable", 404)+ const channel = captureCommunityLiveSnapshotToken(client, message.channelId)+ const assertChannel = () => { assertCurrent(); assertCommunityLiveSnapshotTokenCurrent(client, channel, readSignal) }+ const metadata = await apiFetchCommunity<ChannelMetadata>(`/api/community/channels/${encodeURIComponent(message.channelId)}`,+ { signal: readSignal, assertActive: assertChannel }, channel)+ assertChannel()+ if (metadata.id !== message.channelId || metadata.archived || metadata.accessDecision?.canRead === false) throw new ApiError("Conversation unavailable", 404)+ let destination: string+ if (metadata.type === "dm" && metadata.serverId === null) {+ destination = systemNotificationHref({ kind: "dm", channelId: metadata.id })+ } else if (["text", "forum", "thread"].includes(metadata.type) && metadata.serverId && SAFE_ID.test(metadata.serverId)) {+ destination = systemNotificationHref({ kind: "server", serverId: metadata.serverId, channelId: metadata.id })+ } else throw new ApiError("Conversation unavailable", 404)+ return { href: destination, assertCurrent: assertChannel }+ })+ },+ })+ useEffect(() => {+ if (!active || !query.data || query.isFetching || query.isError) return+ try { query.data.assertCurrent() } catch { return }+ navigation.replace(query.data.href)+ }, [active, navigation, query.data, query.isError, query.isFetching])++ if (!active || !query.isError) return <CommunityPendingFrame href={href} />+ const unavailable = query.error instanceof ApiError && [403, 404].includes(query.error.status)+ return <main className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-6">+ <p role="alert" data-testid={tid.messageRouteAlert(messageId)} className="text-sm text-muted-foreground">{unavailable ? "This conversation is unavailable." : "Could not open this conversation."}</p>+ <div className="flex gap-2">+ {!unavailable && <Button variant="outline" onClick={() => void query.refetch()}>Retry</Button>}+ <Button onClick={openInbox}>Open Inbox</Button>+ </div>+ </main>+}diff --git a/src/web/src/components/community/shell/community-route-context.tsx b/src/web/src/components/community/shell/community-route-context.tsxindex 58ba62bdd..202a7d6c5 100644--- a/src/web/src/components/community/shell/community-route-context.tsx+++ b/src/web/src/components/community/shell/community-route-context.tsx@@ -1,31 +1,9 @@"use client"-import { createContext, useContext } from "react"-import type { Breakpoint } from "@/hooks/use-mobile"-import type { CommunityCommittedFrame } from "@/lib/community/community-route"-import type { ShellFrameProps } from "./shell-frame-types"-import type { CommunityNavigationController } from "./use-community-navigation-controller"--export const CommunityRouteContext = createContext<{- breakpoint: Breakpoint- frame: CommunityCommittedFrame- navigation: CommunityNavigationController- ownerDeleteRouteScope: ShellFrameProps["ownerDeleteRouteScope"]-} | null>(null)--export function useCommunityRouteFrame() {- const context = useContext(CommunityRouteContext)- if (!context) throw new Error("Missing community route frame")- return context-}--export const CommunityServerRouteContext = createContext<{- serverId: string- serverParam: string-} | null>(null)--export function useCommunityServerRoute() {- const context = useContext(CommunityServerRouteContext)- if (!context) throw new Error("Missing server content route")- return context-}+export {+ CommunityRouteContext,+ CommunityServerRouteContext,+ useCommunityRouteFrame,+ useCommunityServerRoute,+ type NativeNotificationConversationConsumer,+} from "@/contexts/community/route-frame"diff --git a/src/web/src/components/community/shell/shell-frame.dom.test.ts b/src/web/src/components/community/shell/shell-frame.dom.test.tsindex 3a0bb8c87..4646631d0 100644--- a/src/web/src/components/community/shell/shell-frame.dom.test.ts+++ b/src/web/src/components/community/shell/shell-frame.dom.test.ts@@ -1,11 +1,18 @@import { createCommunityQueryOwner } from "@/test/community-query-owner"import { CommunityTestProvider } from "@/test/community-owner-fixture"import type { QueryClient } from "@tanstack/react-query"-import { createElement } from "react"+import { createElement, useCallback, useLayoutEffect, type ReactNode } from "react"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import { render as renderDom } from "@/test/react-dom-harness"+import { act, fireEvent, render as renderDom, screen } from "@/test/react-dom-harness"import { ShellFrame } from "./shell-frame"import { communityKeys } from "@/lib/query-keys"+import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"+import { CommunityShellLayout } from "./community-shell-layout"+import { UserBarExtensionSlot } from "./user-bar-extension-slot"+import { useCommunityRouteFrame } from "./community-route-context"+import { tid } from "@/lib/community/testids"+import type { ShellFrameView } from "./shell-frame-view"+import type { useShellInboxController } from "./use-shell-inbox-controller"const mocks = vi.hoisted(() => {const serverCache = new Set<string>()@@ -17,6 +24,11 @@ const mocks = vi.hoisted(() => {cancelPendingNavigation: vi.fn(),}return {+ nativeNotifications: vi.fn(),+ lifecycle: false,+ viewerId: "viewer",+ openChanges: vi.fn(),+ outsideAction: vi.fn(),currentHref: { current: "/c/channels/s1" },pendingHref: { current: null as string | null },navigationPending: { current: false },@@ -61,6 +73,8 @@ const mocks = vi.hoisted(() => {}})+vi.mock("@/hooks/community/use-native-system-notifications", () => ({useNativeSystemNotifications: (...args: unknown[]) => mocks.nativeNotifications(...args)}))+vi.mock("@/hooks/community/community-ws/scope-eviction", () => ({flushOwnerServerDeleteRouteCommit: (...args: unknown[]) => mocks.flushOwnerDelete(...args),}))@@ -72,18 +86,36 @@ vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint.curvi.mock("@/lib/community-onboarding", () => ({useCommunityOnboarding: () => mocks.onboardingState.current,}))-vi.mock("./use-community-navigation-controller", () => ({- useCommunityNavigationController: () => ({- publishedHref: mocks.currentHref.current,- navigationPending: mocks.navigationPending.current,- pendingHref: mocks.pendingHref.current,- push: mocks.push,- replace: mocks.replace,- prefetch: vi.fn(),- resolveAndPush: vi.fn(),- cancelPendingNavigation: mocks.handlers.cancelPendingNavigation,- }),+vi.mock("next/navigation", () => ({+ usePathname: () => mocks.currentHref.current.split("?")[0],+ useSearchParams: () => new URLSearchParams(mocks.currentHref.current.split("?")[1]),+ useRouter: () => ({ push: mocks.push, replace: mocks.replace, prefetch: vi.fn() }),+}))+vi.mock("@/lib/community/navigation-metadata", () => ({ prepareNavigationMetadata: vi.fn(async () => undefined) }))+vi.mock("react-resizable-panels", () => ({+ useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),}))+vi.mock("@/components/ui/resizable", () => {+ const Panel = ({ children }: { children: ReactNode }) => createElement("div", null, children)+ return { ResizablePanelGroup: Panel, ResizablePanel: Panel, ResizableHandle: () => null }+})+vi.mock("./use-hydrated-client", () => ({ useHydratedClient: () => true }))+vi.mock("./use-community-navigation-controller", async (importOriginal) => {+ const { useCommunityNavigationController } = await importOriginal<typeof import("./use-community-navigation-controller")>()+ return { useCommunityNavigationController: (frame: Parameters<typeof useCommunityNavigationController>[0]) => {+ const actual = useCommunityNavigationController(frame)+ return mocks.lifecycle ? actual : {+ publishedHref: mocks.currentHref.current,+ navigationPending: mocks.navigationPending.current,+ pendingHref: mocks.pendingHref.current,+ push: mocks.push,+ replace: mocks.replace,+ prefetch: vi.fn(),+ resolveAndPush: vi.fn(),+ cancelPendingNavigation: mocks.handlers.cancelPendingNavigation,+ }+ } }+})vi.mock("@/stores/community", async (importOriginal) => ({ ...await importOriginal<typeof import("@/stores/community")>(),useCommunityStore: Object.assign(vi.fn(), {getState: () => ({ registerUiHandlers: mocks.registerUiHandlers }),@@ -93,7 +125,7 @@ vi.mock("@/stores/community/ws", async (importOriginal) => ({ ...await importOriuseCommunityWsStore: (selector: (state: { accessEpoch: number }) => unknown) => selector({ accessEpoch: 0 }),}))vi.mock("@/contexts/community/current-user", () => ({- useCurrentUser: () => ({ id: "viewer" }),+ useCurrentUser: () => ({ id: mocks.viewerId }),}))vi.mock("@/lib/community-db/projections", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community-db/projections")>(),useServerTreeProjection: () => mocks.projectedServer.current,@@ -109,9 +141,15 @@ vi.mock("./use-shell-profile-controller", () => ({useShellProfileController: () => mocks.profile,}))vi.mock("./use-shell-inbox-controller", () => ({- useShellInboxController: (options: unknown) => {+ useShellInboxController: (options: Parameters<typeof useShellInboxController>[0]) => {mocks.inboxOptions(options)- return mocks.inbox+ const inbox = useInboxAutoCollapse(options)+ const changeInboxOpen = inbox.onOpenChange+ const onOpenChange = useCallback((open: boolean) => {+ mocks.openChanges(open)+ changeInboxOpen(open)+ }, [changeInboxOpen])+ return mocks.lifecycle ? { ...inbox, onOpenChange } : mocks.inbox},}))vi.mock("./use-shell-daemon-update-controller", () => ({@@ -120,7 +158,27 @@ vi.mock("./use-shell-daemon-update-controller", () => ({vi.mock("./shell-frame-view", () => ({ShellFrameView: (props: Record<string, unknown>) => {mocks.viewProps.current = props- return createElement("div", { "data-testid": "shell-frame-view" })+ if (!mocks.lifecycle) return createElement("div", { "data-testid": "shell-frame-view" })+ const view = props as Parameters<typeof ShellFrameView>[0]+ return createElement(CommunityShellLayout, {+ breakpoint: view.breakpoint,+ surface: view.checkpoint.surface,+ preserveHiddenMobileModules: true,+ rail: null,+ sidebar: createElement("button", { onClick: mocks.outsideAction }, "Outside action"),+ main: view.children,+ userBar: createElement("div", { "data-testid": tid.userBar },+ view.userBarExtension.active === "inbox" ? createElement(UserBarExtensionSlot, {+ active: "inbox", inbox: "Inbox contents", update: null, eligibleMachines: [],+ onDismiss: view.dismissUserBarExtension, onRequestUpdate: vi.fn(),+ }) : null,+ createElement("button", {+ "data-testid": tid.inboxTrigger,+ "aria-expanded": view.userBarExtension.active === "inbox",+ onClick: () => view.onUserBarInboxOpenChange(view.userBarExtension.active !== "inbox"),+ }, "Inbox trigger"),+ ),+ })},}))@@ -139,12 +197,55 @@ function checkpoint() {return mocks.viewProps.current.checkpoint as Record<string, unknown>}+function renderInboxLifecycle(href = "/c/messages/unavailable", breakpoint = "mobile") {+ mocks.lifecycle = true+ mocks.breakpoint.current = breakpoint+ mocks.currentHref.current = href+ let frameHref = href+ let context!: ReturnType<typeof useCommunityRouteFrame>+ function Action() {+ const current = useCommunityRouteFrame()+ useLayoutEffect(() => { context = current }, [current])+ return createElement("button", { onClick: current.openInbox }, "Open Inbox")+ }+ const node = () => createElement(ShellFrame, {+ ...baseProps, view: "dm", activeServerId: undefined, frameHref,+ }, createElement(Action))+ const renderer = render(node())+ return {+ get context() { return context },+ update(options: { publishedHref?: string; frameHref?: string; viewerId?: string } = {}) {+ if (options.publishedHref !== undefined) mocks.currentHref.current = options.publishedHref+ if (options.frameHref !== undefined) frameHref = options.frameHref+ if (options.viewerId !== undefined) mocks.viewerId = options.viewerId+ renderer.rerender(node())+ },+ unmount: renderer.unmount,+ }+}++function expectVisibleInbox() {+ expect(screen.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "true")+ expect(screen.getAllByTestId(tid.userBarExtension)).toHaveLength(1)+ const overlay = screen.getByTestId(tid.inboxTrigger).closest("[data-slot='community-user-bar-overlay']")!+ expect(overlay).not.toHaveAttribute("inert")+ expect(overlay).not.toHaveAttribute("aria-hidden", "true")+ expect(overlay.classList.contains("hidden")).toBe(false)+ expect(screen.getByTestId(tid.userBarExtension)).toHaveTextContent("Inbox contents")+}+describe("ShellFrame orchestration", () => {beforeEach(async () => {const owner = await createCommunityQueryOwner()queryClient = owner.clientconst register = owner.runtime.ui.actions.registerUiHandlersvi.spyOn(owner.runtime.ui.actions, "registerUiHandlers").mockImplementation((handlers) => { mocks.registerUiHandlers(handlers); register(handlers) })+ mocks.lifecycle = false+ mocks.viewerId = "viewer"+ mocks.openChanges.mockReset()+ mocks.outsideAction.mockReset()+ mocks.push.mockReset()+ mocks.replace.mockReset()mocks.currentHref.current = "/c/channels/s1"mocks.pendingHref.current = nullmocks.navigationPending.current = false@@ -408,4 +509,113 @@ describe("ShellFrame orchestration", () => {renderer.rerender(createElement(ShellFrame, baseProps, "mobile"))expect(mocks.railOptions).toHaveBeenLastCalledWith(expect.objectContaining({ breakpoint: "mobile" }))})++ describe("shared Open Inbox commit handoff", () => {+ it("opens once after exact frame, publication and auto-collapse, then keeps outside action before dismiss", () => {+ const shell = renderInboxLifecycle()+ const overlay = screen.getByTestId(tid.inboxTrigger).closest("[data-slot='community-user-bar-overlay']")!+ expect(overlay).toHaveAttribute("inert")+ expect(overlay.classList.contains("hidden")).toBe(true)+ fireEvent.click(screen.getByRole("button", { name: "Open Inbox" }))+ expect(mocks.push).toHaveBeenCalledExactlyOnceWith("/c/me")+ expect(shell.context.navigation.navigationPending).toBe(true)+ expect(screen.queryByTestId(tid.userBarExtension)).toBeNull()+ shell.update({ publishedHref: "/c/me" })+ expect(shell.context.navigation.navigationPending).toBe(true)+ expect(mocks.openChanges).not.toHaveBeenCalled()+ shell.update({ frameHref: "/c/me" })+ expect(shell.context.navigation.navigationPending).toBe(false)+ expectVisibleInbox()+ expect(mocks.openChanges).toHaveBeenCalledExactlyOnceWith(true)+ shell.update()+ expect(mocks.openChanges).toHaveBeenCalledTimes(1)+ fireEvent.click(screen.getByRole("button", { name: "Outside action" }))+ expect(mocks.outsideAction).toHaveBeenCalledTimes(1)+ expect(mocks.openChanges).toHaveBeenLastCalledWith(false)+ expect(mocks.outsideAction.mock.invocationCallOrder[0]).toBeLessThan(mocks.openChanges.mock.invocationCallOrder[1]!)+ expect(screen.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "false")+ })++ it("waits for publication when the exact frame settles first", () => {+ const shell = renderInboxLifecycle()+ fireEvent.click(screen.getByRole("button", { name: "Open Inbox" }))+ shell.update({ frameHref: "/c/me" })+ expect(shell.context.navigation.navigationPending).toBe(false)+ expect(mocks.openChanges).not.toHaveBeenCalled()+ shell.update({ publishedHref: "/c/me" })+ expectVisibleInbox()+ expect(mocks.openChanges).toHaveBeenCalledExactlyOnceWith(true)+ })++ it.each([["desktop", "/c/messages/unavailable"], ["mobile", "/c/me"]])(+ "keeps direct opening on %s at %s", (breakpoint, href) => {+ const shell = renderInboxLifecycle(href, breakpoint)+ act(() => shell.context.openInbox!())+ expect(mocks.push).not.toHaveBeenCalled()+ expectVisibleInbox()+ fireEvent.click(screen.getByTestId(tid.inboxTrigger))+ expect(screen.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "false")+ },+ )++ it.each(["push", "replace", "resolver", "cancel", "Back"])(+ "discards the request on %s and does not revive on a later same URL", async (entry) => {+ const shell = renderInboxLifecycle()+ fireEvent.click(screen.getByRole("button", { name: "Open Inbox" }))+ await act(async () => {+ const nav = shell.context.navigation+ if (entry === "push") nav.push("/c/me/friends")+ if (entry === "replace") nav.replace("/c/me/friends")+ if (entry === "resolver") await nav.resolveAndPush(async () => "/c/me/friends")+ if (entry === "cancel") nav.cancelPendingNavigation()+ if (entry === "Back") window.dispatchEvent(new Event("popstate"))+ })+ shell.update({ publishedHref: "/c/me", frameHref: "/c/me" })+ shell.update({ publishedHref: "/c/me/friends", frameHref: "/c/me/friends" })+ shell.update({ publishedHref: "/c/me", frameHref: "/c/me" })+ expect(mocks.openChanges).not.toHaveBeenCalledWith(true)+ expect(screen.queryByTestId(tid.userBarExtension)).toBeNull()+ },+ )++ it("discards on account change even if the original account returns before the destination", () => {+ const shell = renderInboxLifecycle()+ fireEvent.click(screen.getByRole("button", { name: "Open Inbox" }))+ shell.update({ viewerId: "other-viewer" })+ shell.update({ viewerId: "viewer" })+ shell.update({ publishedHref: "/c/me", frameHref: "/c/me" })+ expect(mocks.openChanges).not.toHaveBeenCalledWith(true)+ })++ it("clears a synchronous push failure and cannot reopen on a later destination commit", () => {+ const shell = renderInboxLifecycle()+ mocks.push.mockImplementationOnce(() => { throw new Error("push failed") })+ act(() => { expect(() => shell.context.openInbox!()).toThrow("push failed") })+ expect(shell.context.navigation.navigationPending).toBe(false)+ expect(shell.context.navigation.pendingHref).toBeNull()+ shell.update({ publishedHref: "/c/me", frameHref: "/c/me" })+ expect(mocks.openChanges).not.toHaveBeenCalledWith(true)+ })++ it("loses the request on unmount", () => {+ const shell = renderInboxLifecycle()+ fireEvent.click(screen.getByRole("button", { name: "Open Inbox" }))+ shell.unmount()+ renderInboxLifecycle("/c/me")+ expect(mocks.openChanges).not.toHaveBeenCalledWith(true)+ expect(screen.queryByTestId(tid.userBarExtension)).toBeNull()+ })++ it("keeps a repeated external request pending until its latest exact commit", () => {+ const shell = renderInboxLifecycle()+ fireEvent.click(screen.getByRole("button", { name: "Open Inbox" }))+ act(() => shell.context.openInbox!())+ expect(mocks.push).toHaveBeenCalledTimes(2)+ expect(mocks.openChanges).not.toHaveBeenCalled()+ shell.update({ publishedHref: "/c/me", frameHref: "/c/me" })+ expectVisibleInbox()+ expect(mocks.openChanges).toHaveBeenCalledExactlyOnceWith(true)+ })+ })+})diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxindex c74f5983b..18646e8ee 100644--- a/src/web/src/components/community/shell/shell-frame.tsx+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -21,7 +21,8 @@ import { communityKeys } from "@/lib/query-keys"import { useCommunityWsStore } from "@/stores/community/ws"import { useCurrentUser } from "@/contexts/community/current-user"-import { CommunityRouteContext } from "./community-route-context"+import { useNativeSystemNotifications } from "@/hooks/community/use-native-system-notifications"+import { CommunityRouteContext, type NativeNotificationConversationConsumer } from "./community-route-context"import { ShellFrameView } from "./shell-frame-view"import { useShellRailController } from "./use-shell-rail-controller"import { useShellProfileController } from "./use-shell-profile-controller"@@ -57,6 +58,7 @@ export function ShellFrame(props: ShellFrameProps) {onOpenActiveServerInvite,ownerDeleteRouteScope,} = props+ const notificationConsumer = useRef<NativeNotificationConversationConsumer | null>(null)const queryClient = useQueryClient()const currentUser = useCurrentUser()const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)@@ -182,6 +184,37 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommittinbox.onOpenChange(true)dispatchUserBarExtension({ type: "extension.open", extension: "inbox" })}, [daemonUpdate, dispatchUserBarExtension, inbox, profile, userBarExtension.active])+ const [inboxOpenRequest, setInboxOpenRequest] = useAtom(useCreateAtom<{+ viewerId: string+ isCurrent: () => boolean+ } | null>(null))+ const openInbox = useCallback(() => {+ setInboxOpenRequest(null)+ if (breakpoint !== "mobile" || (committedFrame.surface !== "detail" && checkpoint.surface !== "detail")) {+ onUserBarInboxOpenChange(true)+ return+ }+ const request = {+ viewerId: currentUser.id,+ isCurrent: navigation.captureIntent({ nextCommitHref: "/c/me" }),+ }+ navigation.push("/c/me")+ setInboxOpenRequest(request)+ }, [breakpoint, checkpoint.surface, committedFrame.surface, currentUser.id, navigation, onUserBarInboxOpenChange, setInboxOpenRequest])+ useEffect(() => {+ if (!inboxOpenRequest) return+ if (inboxOpenRequest.viewerId !== currentUser.id || !inboxOpenRequest.isCurrent()) {+ setInboxOpenRequest(null)+ return+ }+ if (navigation.navigationPending || navigation.pendingHref !== null+ || navigation.publishedHref !== "/c/me" || committedFrame.href !== "/c/me"+ || checkpoint.surface !== "list") return+ setInboxOpenRequest(null)+ onUserBarInboxOpenChange(true)+ }, [checkpoint.surface, committedFrame.href, currentUser.id, inboxOpenRequest, navigation.navigationPending,+ navigation.pendingHref, navigation.publishedHref, onUserBarInboxOpenChange, setInboxOpenRequest])+ useNativeSystemNotifications(currentUser.id, committedFrame, navigation, notificationConsumer)const onUserBarOpenProfile = useCallback<ReturnType<typeof useShellProfileController>["openProfile"]>((name,event,@@ -269,7 +302,7 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt}, [goBackMobile, profile.openProfile, profile.previewAttachment, profile.previewImage, rail.navigate, navigation.cancelPendingNavigation, navigation.push, navigation.replace, queryClient])return (- <CommunityRouteContext value={{ breakpoint, frame: committedFrame, navigation, ownerDeleteRouteScope }}>+ <CommunityRouteContext value={{ breakpoint, frame: committedFrame, navigation, ownerDeleteRouteScope, openInbox, notificationConsumer }}><ShellFrameViewbreakpoint={breakpoint}checkpoint={checkpoint}diff --git a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.tsindex 03e11eca4..fc3b7a81d 100644--- a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts+++ b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts@@ -126,11 +126,16 @@ function renderShell(breakpoint: "mobile" | "desktop" = "mobile", queryClient =return {queryClient,get navigation() { return navigation },- commit(href: string, revision: number) {- mocks.pathname = href+ commit(href: string, revision: number, publish = true) {+ if (publish) mocks.pathname = hrefcommittedFrame = frame(href, revision)renderer.rerender(createElement(QueryClientProvider, { client: queryClient }, createElement(Capture)))},+ publish(href: string) {+ mocks.pathname = href+ renderer.rerender(createElement(QueryClientProvider, { client: queryClient }, createElement(Capture)))+ },+ unmount: renderer.unmount,}}@@ -275,4 +280,119 @@ describe("Shell input and explicit navigation ownership", () => {expect(mocks.push).toHaveBeenCalledTimes(1)expect(mocks.replace).not.toHaveBeenCalled()})++ describe("optional exact next-commit qualification", () => {+ it("retains only its own exact commit while default capture still retires", () => {+ const shell = renderShell("desktop")+ const ownCommit = shell.navigation.captureIntent({ nextCommitHref: target })+ expect(ownCommit()).toBe(false)+ act(() => shell.navigation.push(target))+ const ordinary = shell.navigation.captureIntent()+ expect(ownCommit()).toBe(true)+ expect(ordinary()).toBe(true)+ shell.publish(target)+ expect(shell.navigation.navigationPending).toBe(true)+ shell.commit(target, 1)+ expect(shell.navigation.navigationPending).toBe(false)+ expect(ordinary()).toBe(false)+ expect(ownCommit()).toBe(true)+ shell.commit(target, 1)+ expect(ownCommit()).toBe(true)+ shell.commit(nextTarget, 2)+ shell.commit(target, 3)+ expect(ownCommit()).toBe(false)+ })++ it("preserves own frame settlement until its separately published URL arrives", () => {+ const shell = renderShell("desktop")+ const ownCommit = shell.navigation.captureIntent({ nextCommitHref: target })+ act(() => shell.navigation.push(target))+ shell.commit(target, 1, false)+ expect(shell.navigation.navigationPending).toBe(false)+ expect(shell.navigation.publishedHref).not.toBe(target)+ expect(ownCommit()).toBe(true)+ shell.publish(target)+ expect(ownCommit()).toBe(true)+ })++ it.each(["push", "pushImmediate", "replace", "resolver", "cancel", "Back"])(+ "retires at a competing %s entry and rejects a later identical destination", async (entry) => {+ const shell = renderShell("desktop")+ const ownCommit = shell.navigation.captureIntent({ nextCommitHref: target })+ act(() => shell.navigation.push(target))+ await act(async () => {+ if (entry === "push") shell.navigation.push(nextTarget)+ if (entry === "pushImmediate") shell.navigation.pushImmediate(nextTarget)+ if (entry === "replace") shell.navigation.replace(nextTarget)+ if (entry === "resolver") await shell.navigation.resolveAndPush(async () => nextTarget)+ if (entry === "cancel") shell.navigation.cancelPendingNavigation()+ if (entry === "Back") window.dispatchEvent(new Event("popstate"))+ })+ expect(ownCommit()).toBe(false)+ shell.commit(nextTarget, 1)+ act(() => shell.navigation.push(target))+ shell.commit(target, 2)+ expect(ownCommit()).toBe(false)+ },+ )++ it("rejects an intervening unrelated frame even if the pending target later commits", () => {+ const shell = renderShell("desktop")+ const ownCommit = shell.navigation.captureIntent({ nextCommitHref: target })+ act(() => shell.navigation.push(target))+ shell.commit(nextTarget, 1)+ expect(ownCommit()).toBe(false)+ shell.commit(target, 2)+ expect(shell.navigation.navigationPending).toBe(false)+ expect(ownCommit()).toBe(false)+ })++ it.each(["push", "pushImmediate", "replace"] as const)(+ "discards a synchronous %s failure before any later same-URL commit", (entry) => {+ const shell = renderShell("desktop")+ const ownCommit = shell.navigation.captureIntent({ nextCommitHref: target })+ mocks[entry === "replace" ? "replace" : "push"].mockImplementationOnce(() => { throw new Error("router failed") })+ act(() => { expect(() => shell.navigation[entry](target)).toThrow("router failed") })+ expect(shell.navigation.navigationPending).toBe(false)+ expect(shell.navigation.pendingHref).toBeNull()+ expect(ownCommit()).toBe(false)+ act(() => shell.navigation.push(target))+ shell.commit(target, 1)+ expect(ownCommit()).toBe(false)+ },+ )++ it("does not clear a newer pending intent when an older router call throws", () => {+ const shell = renderShell("desktop")+ const ownCommit = shell.navigation.captureIntent({ nextCommitHref: target })+ mocks.push.mockImplementationOnce(() => {+ shell.navigation.push(nextTarget)+ throw new Error("old push failed")+ })+ act(() => { expect(() => shell.navigation.push(target)).toThrow("old push failed") })+ expect(shell.navigation.pendingHref).toBe(nextTarget)+ expect(shell.navigation.navigationPending).toBe(true)+ expect(ownCommit()).toBe(false)+ })++ it("retires a settled qualification on a same-URL no-op without changing default capture", () => {+ const shell = renderShell("desktop")+ const ownCommit = shell.navigation.captureIntent({ nextCommitHref: target })+ act(() => shell.navigation.push(target))+ shell.commit(target, 1)+ const ordinary = shell.navigation.captureIntent()+ act(() => shell.navigation.push(target))+ expect(ownCommit()).toBe(false)+ expect(ordinary()).toBe(true)+ })++ it("retires on unmount", () => {+ const shell = renderShell("desktop")+ const ownCommit = shell.navigation.captureIntent({ nextCommitHref: target })+ act(() => shell.navigation.push(target))+ shell.unmount()+ expect(ownCommit()).toBe(false)+ })+ })+})diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.ts b/src/web/src/components/community/shell/use-community-navigation-controller.tsindex 91cf3464a..479fb0c39 100644--- a/src/web/src/components/community/shell/use-community-navigation-controller.ts+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts@@ -20,18 +20,8 @@ import {type CommunityCommittedFrame,} from "@/lib/community/community-route"import { cancelActiveConversationNavigationProof } from "@/lib/community/conversation-navigation-proof"--export type CommunityNavigationController = {- captureIntent: () => () => boolean- publishedHref: string- navigationPending: boolean- pendingHref: string | null- push: ReturnType<typeof useRouter>["push"]- pushImmediate: (href: string) => void- replace: (href: string) => void- resolveAndPush: (resolve: () => Promise<string>) => Promise<boolean>- cancelPendingNavigation: () => void-}+import type { CommunityNavigationController } from "@/contexts/community/route-frame"+export type { CommunityNavigationController } from "@/contexts/community/route-frame"export function useCommunityNavigationController(committedFrame: CommunityCommittedFrame,@@ -50,11 +40,27 @@ export function useCommunityNavigationController(}, [])const committedFrameRef = useRef(committedFrame)useLayoutEffect(() => { committedFrameRef.current = committedFrame }, [committedFrame])- const captureIntent = useCallback(() => {- const revision = gateRef.current.revision+ const settledIntentRef = useRef<{+ revision: number+ frameRevision: number+ href: string+ } | null>(null)+ const captureIntent = useCallback<CommunityNavigationController["captureIntent"]>((options) => {+ const revision = gateRef.current.revision + (options ? 1 : 0)const frameRevision = committedFrameRef.current.revision- return () => mountedRef.current && revision === gateRef.current.revision- && frameRevision === committedFrameRef.current.revision+ const targetHref = options ? normalizeCommunityHref(options.nextCommitHref).href : null+ const targetRevision = frameRevision + (targetHref !== null+ && normalizeCommunityHref(targetHref).leafKey !== committedFrameRef.current.leafKey ? 1 : 0)+ return () => {+ if (!mountedRef.current) return false+ if (revision === gateRef.current.revision && frameRevision === committedFrameRef.current.revision) return true+ const settled = settledIntentRef.current+ return targetHref !== null && settled !== null+ && settled.revision === revision && gateRef.current.revision === revision + 1+ && settled.frameRevision === targetRevision+ && settled.frameRevision === committedFrameRef.current.revision+ && settled.href === targetHref && committedFrameRef.current.href === targetHref+ }}, [])const pendingBaselineRevisionRef = useRef(committedFrame.revision)const pendingBaselineLeafRef = useRef(committedFrame.leafKey)@@ -79,6 +85,11 @@ export function useCommunityNavigationController(baselineRevision: pendingBaselineRevisionRef.current,})if (!settled) return+ settledIntentRef.current = {+ revision: gateRef.current.revision,+ frameRevision: committedFrame.revision,+ href: target.href,+ }supersedeNavigationIntent(gateRef.current)setNavigationPending(false)setPendingHref(null)@@ -93,9 +104,19 @@ export function useCommunityNavigationController(}}, [cancelPendingNavigation])+ const submitNavigation = useCallback((submit: () => void) => {+ const revision = gateRef.current.revision+ try {+ submit()+ } catch (error) {+ if (revision === gateRef.current.revision) cancelPendingNavigation()+ throw error+ }+ }, [cancelPendingNavigation])+const push = useCallback((...args: Parameters<typeof router.push>) => {const [href] = args- if (href === publishedHref && !navigationPending) { navigationNoop(href); return }+ if (href === publishedHref && !navigationPending) { settledIntentRef.current = null; navigationNoop(href); return }beginNavigation(href)void prepareNavigationMetadata(queryClient, href, "foreground")supersedeNavigationIntent(gateRef.current)@@ -109,11 +130,11 @@ export function useCommunityNavigationController(setNavigationPending(true)setPendingHref(href)})- router.push(...args)- }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setNavigationPending, setPendingHref])+ submitNavigation(() => router.push(...args))+ }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setNavigationPending, setPendingHref, submitNavigation])const pushImmediate = useCallback((href: string) => {- if (href === publishedHref && !navigationPending) { navigationNoop(href); return }+ if (href === publishedHref && !navigationPending) { settledIntentRef.current = null; navigationNoop(href); return }beginNavigation(href)void prepareNavigationMetadata(queryClient, href, "foreground")supersedeNavigationIntent(gateRef.current)@@ -125,11 +146,11 @@ export function useCommunityNavigationController(setNavigationPending(true)setPendingHref(href)})- router.push(href)- }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setNavigationPending, setPendingHref])+ submitNavigation(() => router.push(href))+ }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setNavigationPending, setPendingHref, submitNavigation])const replace = useCallback((href: string) => {- if (href === publishedHref && !navigationPending) { navigationNoop(href); return }+ if (href === publishedHref && !navigationPending) { settledIntentRef.current = null; navigationNoop(href); return }beginNavigation(href)void prepareNavigationMetadata(queryClient, href, "foreground")supersedeNavigationIntent(gateRef.current)@@ -138,8 +159,8 @@ export function useCommunityNavigationController(pendingBaselineLeafRef.current = committedFrame.leafKeysetNavigationPending(true)setPendingHref(href)- router.replace(href)- }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setNavigationPending, setPendingHref])+ submitNavigation(() => router.replace(href))+ }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setNavigationPending, setPendingHref, submitNavigation])const resolveAndPush = useCallback(async (resolve: () => Promise<string>) => {cancelActiveConversationNavigationProof(queryClient)diff --git a/src/web/src/contexts/community/route-frame.tsx b/src/web/src/contexts/community/route-frame.tsxnew file mode 100644index 000000000..64d54e946--- /dev/null+++ b/src/web/src/contexts/community/route-frame.tsx@@ -0,0 +1,50 @@+"use client"++import { createContext, useContext, type RefObject } from "react"+import type { useRouter } from "next/navigation"+import type { Breakpoint } from "@/hooks/use-mobile"+import type { CommunityCommittedFrame } from "@/lib/community/community-route"+import type { OwnerServerDeleteRouteToken } from "@/lib/community/eject-server"++export type CommunityNavigationController = {+ captureIntent: (options?: { nextCommitHref: string }) => () => boolean+ publishedHref: string+ navigationPending: boolean+ pendingHref: string | null+ push: ReturnType<typeof useRouter>["push"]+ pushImmediate: (href: string) => void+ replace: (href: string) => void+ resolveAndPush: (resolve: () => Promise<string>) => Promise<boolean>+ cancelPendingNavigation: () => void+}++export type NativeNotificationConversationConsumer = {+ matches: (viewerUserId: string, targetId: string) => boolean+ requestDismiss: () => void+}++export const CommunityRouteContext = createContext<{+ openInbox?: () => void+ notificationConsumer?: RefObject<NativeNotificationConversationConsumer | null>+ breakpoint: Breakpoint+ frame: CommunityCommittedFrame+ navigation: CommunityNavigationController+ ownerDeleteRouteScope: { serverId: string; token: OwnerServerDeleteRouteToken } | undefined+} | null>(null)++export function useCommunityRouteFrame() {+ const context = useContext(CommunityRouteContext)+ if (!context) throw new Error("Missing community route frame")+ return context+}++export const CommunityServerRouteContext = createContext<{+ serverId: string+ serverParam: string+} | null>(null)++export function useCommunityServerRoute() {+ const context = useContext(CommunityServerRouteContext)+ if (!context) throw new Error("Missing server content route")+ return context+}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 a80df79bb..5a8d6fda4 100644--- a/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts+++ b/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it, vi } from "vitest"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { createElement, type PropsWithChildren } from "react"import { act, waitFor, renderHook as renderOwnedHook } from "@/test/react-dom-harness"import { createCommunityQueryOwner } from "@/test/community-query-owner"@@ -6,16 +6,12 @@ import { CommunityTestProvider } from "@/test/community-owner-fixture"import { renderCommunityHook as renderHook } from "@/test/community-owner-harness"import {createDesktopSystemNotificationActivationController,- createDesktopSystemNotificationInboxOpener,- type DesktopSystemNotificationInboxDeps,useNativeSystemNotificationConversationDismissal,useNativeSystemNotifications,} from "./use-native-system-notifications"import type { DesktopSystemNotificationActivation } from "@/lib/community/system-notification-route"-import {- createNativeSystemNotificationConversationDismissalQueue,- createNativeSystemNotificationDismissalQueue,-} from "@/lib/community/native-system-notification-dismissal"+import { createNativeSystemNotificationDismissalQueue } from "@/lib/community/native-system-notification-dismissal"+const hookMocks = vi.hoisted(() => ({desktop: true,@@ -85,699 +81,193 @@ vi.mock("@/lib/community/mobile-system-notification", async () => {}})+import { normalizeCommunityHref } from "@/lib/community/community-route"+import { CommunityRouteContext, type NativeNotificationConversationConsumer } from "@/components/community/shell/community-route-context"+import type { CommunityNavigationController } from "@/components/community/shell/use-community-navigation-controller"const activation: DesktopSystemNotificationActivation = {notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",- target: {- kind: "server",- serverId: "server_1",- channelId: "channel_1",- messageId: "message_1",- seq: 4,- },+ target: { kind: "server", serverId: "server_1", channelId: "channel_1", messageId: "message_1", seq: 4 },}--afterEach(() => {- hookMocks.desktop = true- hookMocks.mobile = false- window.sessionStorage.clear()- window.localStorage.clear()- document.body.replaceChildren()- vi.useRealTimers()- vi.unstubAllGlobals()- vi.clearAllMocks()+const target = { kind: "server" as const, serverId: "server_1", channelId: "channel_1" }+const consumer = { current: null as NativeNotificationConversationConsumer | null }+let intentRevision = 0+let route: { frame: ReturnType<typeof normalizeCommunityHref> & {revision:number}; navigation: CommunityNavigationController; breakpoint: "desktop"; notificationConsumer: typeof consumer }+function setRoute(href: string, pending = false) {+ route = { breakpoint:"desktop", notificationConsumer:consumer, frame:{...normalizeCommunityHref(href),revision:intentRevision}, navigation:{+ publishedHref:href, navigationPending:pending, pendingHref:pending ? href : null,+ captureIntent:()=>{const revision=intentRevision;return ()=>revision===intentRevision},+ push:vi.fn(), pushImmediate:vi.fn(()=>{intentRevision++}), replace:vi.fn(), resolveAndPush:vi.fn(), cancelPendingNavigation:vi.fn(),+ }}+}+const wrapper = ({children}:PropsWithChildren) => createElement(CommunityRouteContext,{value:route},children)+function useNotifications() { useNativeSystemNotifications("viewer", route.frame, route.navigation, consumer) }+function presentation(identity:unknown) {+ return (window as Window & {alookNativeNotificationPresentationV1?:(value:unknown)=>boolean}).alookNativeNotificationPresentationV1?.(identity)+}+beforeEach(()=>{+ vi.resetAllMocks()+ hookMocks.desktop=true;hookMocks.mobile=false;consumer.current=null;intentRevision=0+ setRoute("/c/channels/server_1/channel_1")+ hookMocks.listen.mockResolvedValue(vi.fn());hookMocks.take.mockResolvedValue(null)+ hookMocks.dismiss.mockResolvedValue(undefined);hookMocks.dismissConversation.mockResolvedValue(undefined)+ hookMocks.mobileListen.mockResolvedValue(vi.fn());hookMocks.mobileTake.mockResolvedValue(null)+ hookMocks.mobileCheck.mockResolvedValue("denied");hookMocks.mobileDismiss.mockResolvedValue(undefined)+ hookMocks.mobileDismissConversation.mockResolvedValue(undefined)+ vi.spyOn(document,"visibilityState","get").mockReturnValue("visible")})--describe("desktop notification activation controller", () => {- it("drains a cold-start activation after registering the listener", async () => {- const calls: string[] = []- const controller = createDesktopSystemNotificationActivationController({- listen: vi.fn(async () => { calls.push("listen"); return () => calls.push("unlisten") }),- take: vi.fn(async () => { calls.push("take"); return activation }),- revalidate: vi.fn(async () => { calls.push("revalidate"); return "allowed" as const }),- retryActivation: vi.fn(),- queueDismiss: vi.fn(() => { calls.push("queueDismiss") }),- navigate: vi.fn(() => calls.push("navigate")),- openInbox: vi.fn(),- })- await controller.connect()- expect(calls).toEqual(["listen", "take", "revalidate", "queueDismiss", "navigate"])- controller.dispose()- expect(calls.at(-1)).toBe("unlisten")- })-- it("falls back to Inbox when the message is deleted or access is revoked", async () => {- const openInbox = vi.fn()- const navigate = vi.fn()- const retryActivation = vi.fn()- const controller = createDesktopSystemNotificationActivationController({- listen: vi.fn(async () => () => undefined),- take: vi.fn(async () => activation),- revalidate: vi.fn(async () => "invalid" as const),- retryActivation,- queueDismiss: vi.fn(),- navigate,- openInbox,- })- await controller.connect()- expect(openInbox).toHaveBeenCalledOnce()- expect(navigate).not.toHaveBeenCalled()- expect(retryActivation).not.toHaveBeenCalled()- })-- it("re-arms only a retryable activation before falling back to Inbox", async () => {- const calls: string[] = []- const retryActivation = vi.fn(async (notificationId: string) => {- calls.push(`retry:${notificationId}`)- })- const controller = createDesktopSystemNotificationActivationController({- listen: vi.fn(async () => () => undefined),- take: vi.fn(async () => activation),- revalidate: vi.fn(async () => {- calls.push("revalidate")- return "retryable" as const- }),- retryActivation,- queueDismiss: vi.fn(),- navigate: vi.fn(),- openInbox: vi.fn(async () => { calls.push("inbox") }),- })-- await controller.connect()- expect(calls).toEqual([- "revalidate",- `retry:${activation.notificationId}`,- "inbox",- ])- })-- it("still navigates when dismissal persistence fails", async () => {- const navigate = vi.fn()- const controller = createDesktopSystemNotificationActivationController({- listen: vi.fn(async () => () => undefined),- take: vi.fn(async () => activation),- revalidate: vi.fn(async () => "allowed" as const),- retryActivation: vi.fn(),- queueDismiss: vi.fn(() => { throw new Error("storage unavailable") }),- navigate,- openInbox: vi.fn(),+afterEach(()=>{window.localStorage.clear();window.sessionStorage.clear();vi.useRealTimers();vi.restoreAllMocks();vi.unstubAllGlobals()})+describe("notification activation",()=>{+ it("queues and navigates immediately without starting a HTTP precheck",async()=>{+ const fetch=vi.fn(()=>new Promise<Response>(()=>undefined));vi.stubGlobal("fetch",fetch)+ const calls:string[]=[]+ const controller=createDesktopSystemNotificationActivationController({+ listen:async()=>()=>undefined,take:async()=>activation,+ queueDismiss:()=>calls.push("queue"),navigate:(href)=>calls.push(href),})await controller.connect()- expect(navigate).toHaveBeenCalledExactlyOnceWith("/c/channels/server_1/channel_1")- })-- it("handles hot activation signals and ignores work after disposal", async () => {- let ready: (() => void) | undefined- const take = vi.fn()- .mockResolvedValueOnce(null)- .mockResolvedValueOnce(activation)- .mockResolvedValue(null)- const navigate = vi.fn()- const controller = createDesktopSystemNotificationActivationController({- listen: vi.fn(async (callback) => { ready = callback; return () => undefined }),- take,- revalidate: vi.fn(async () => "allowed" as const),- retryActivation: vi.fn(),- queueDismiss: vi.fn(),- navigate,- openInbox: vi.fn(),- })- await controller.connect()- ready?.()- await waitFor(() => expect(navigate).toHaveBeenCalledOnce())+ expect(calls).toEqual(["queue","/c/channels/server_1/channel_1"])+ expect(fetch).not.toHaveBeenCalled()controller.dispose()- ready?.()- await Promise.resolve()- expect(take).toHaveBeenCalledTimes(2)- })-- it("reruns a drain when a native signal arrives during an active take", async () => {- let ready: (() => void) | undefined- let releaseTake = (_value: DesktopSystemNotificationActivation | null) => undefined- const firstTake = new Promise<DesktopSystemNotificationActivation | null>((resolve) => {- releaseTake = resolve- })- const take = vi.fn()- .mockReturnValueOnce(firstTake)- .mockResolvedValueOnce(null)- const controller = createDesktopSystemNotificationActivationController({- listen: vi.fn(async (callback) => { ready = callback; return () => undefined }),- take,- revalidate: vi.fn(async () => "allowed" as const),- retryActivation: vi.fn(),- queueDismiss: vi.fn(),- navigate: vi.fn(),- openInbox: vi.fn(),- })-- const connecting = controller.connect()- await waitFor(() => expect(take).toHaveBeenCalledOnce())- ready?.()- releaseTake(null)- await connecting- expect(take).toHaveBeenCalledTimes(2)- })-- it("stops a listener that resolves after disposal", async () => {- let releaseListen = (_stop: () => void) => undefined- const listener = new Promise<() => void>((resolve) => { releaseListen = resolve })- const stop = vi.fn()- const controller = createDesktopSystemNotificationActivationController({- listen: vi.fn(() => listener),- take: vi.fn(),- revalidate: vi.fn(),- retryActivation: vi.fn(),- queueDismiss: vi.fn(),- navigate: vi.fn(),- openInbox: vi.fn(),- })-- const connecting = controller.connect()- controller.dispose()- releaseListen(stop)- await connecting- expect(stop).toHaveBeenCalledOnce()- })-})--function inboxDeps(- pending: Map<string, string>,- overrides: Partial<DesktopSystemNotificationInboxDeps> = {},-): DesktopSystemNotificationInboxDeps {- return {- getItem: (key) => pending.get(key) ?? null,- setItem: (key, value) => pending.set(key, value),- removeItem: (key) => { pending.delete(key) },- findTrigger: () => null,- navigateToCommunity: vi.fn(),- wait: async () => undefined,- now: () => 1_000,- pollAttempts: 2,- ...overrides,- }-}--describe("desktop notification Inbox fallback", () => {- it("keeps a timed-out intent for remount, navigates once, and clears only after a real click", async () => {- const pending = new Map<string, string>()- const firstNavigate = vi.fn()- const first = createDesktopSystemNotificationInboxOpener(inboxDeps(pending, {- navigateToCommunity: firstNavigate,- }))-- await first.open()- expect(firstNavigate).toHaveBeenCalledOnce()- expect([...pending.values()].map((value) => JSON.parse(value))).toEqual([- { version: 1, expiresAt: 301_000, navigationStarted: true },- ])- await first.open()- expect(firstNavigate).toHaveBeenCalledOnce()- first.dispose()-- const remountNavigate = vi.fn()- const click = vi.fn()- const remount = createDesktopSystemNotificationInboxOpener(inboxDeps(pending, {- findTrigger: () => ({ click }),- navigateToCommunity: remountNavigate,- }))- await remount.resume()- expect(click).toHaveBeenCalledOnce()- expect(remountNavigate).not.toHaveBeenCalled()- expect(pending.size).toBe(0)- })-- it("consumes a trigger that mounts late without navigating", async () => {- const pending = new Map<string, string>()- const click = vi.fn()- const navigate = vi.fn()- let probes = 0- const opener = createDesktopSystemNotificationInboxOpener(inboxDeps(pending, {- findTrigger: () => (++probes === 2 ? { click } : null),- navigateToCommunity: navigate,- }))-- await opener.open()- expect(click).toHaveBeenCalledOnce()- expect(navigate).not.toHaveBeenCalled()- expect(pending.size).toBe(0)- })-- it("cleans corrupt or expired state and has no side effects after disposal", async () => {- const pending = new Map([["alook:desktop-system-notification:inbox-intent", "corrupt"]])- const navigate = vi.fn()- const opener = createDesktopSystemNotificationInboxOpener(inboxDeps(pending, {- navigateToCommunity: navigate,- }))- await opener.resume()- expect(pending.size).toBe(0)-- pending.set("alook:desktop-system-notification:inbox-intent", JSON.stringify({- version: 1,- expiresAt: 999,- navigationStarted: false,- }))- await opener.resume()- expect(pending.size).toBe(0)-- let releaseWait = () => undefined- const wait = new Promise<void>((resolve) => { releaseWait = resolve })- const click = vi.fn()- let triggerReady = false- const active = createDesktopSystemNotificationInboxOpener(inboxDeps(pending, {- findTrigger: () => (triggerReady ? { click } : null),- navigateToCommunity: navigate,- wait: () => wait,- }))- const opening = active.open()- await Promise.resolve()- triggerReady = true- active.dispose()- releaseWait()- await opening- expect(click).not.toHaveBeenCalled()- expect(navigate).not.toHaveBeenCalled()- expect(pending.size).toBe(1)- })-- it("treats storage failures as unavailable persistence", async () => {- const removeFailure = createDesktopSystemNotificationInboxOpener(inboxDeps(new Map(), {- getItem: () => "corrupt",- removeItem: () => { throw new Error("blocked") },- }))- await removeFailure.resume()-- const readFailure = createDesktopSystemNotificationInboxOpener(inboxDeps(new Map(), {- getItem: () => { throw new Error("blocked") },- }))- await readFailure.resume()-- const writeFailure = createDesktopSystemNotificationInboxOpener(inboxDeps(new Map(), {- setItem: () => { throw new Error("blocked") },- }))- await writeFailure.open()- })-})--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("coalesces signals and retires a delayed take",async()=>{+ let wake!:()=>void;let release!:(value:DesktopSystemNotificationActivation|null)=>void+ const pending=new Promise<DesktopSystemNotificationActivation|null>(resolve=>{release=resolve})+ const take=vi.fn().mockReturnValueOnce(pending).mockResolvedValueOnce(null)+ const navigate=vi.fn()+ const controller=createDesktopSystemNotificationActivationController({listen:async cb=>{wake=cb;return()=>undefined},take,queueDismiss:vi.fn(),navigate})+ const connection=controller.connect();await waitFor(()=>expect(take).toHaveBeenCalledOnce())+ wake();release(activation);await connection+ expect(take).toHaveBeenCalledTimes(2);expect(navigate).toHaveBeenCalledOnce()+ controller.dispose();wake();expect(take).toHaveBeenCalledTimes(2)})-- 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 = false- const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))- expect(hookMocks.listen).not.toHaveBeenCalled()- rendered.unmount()- })-- it("dismisses on the loaded destination and retries a transient native failure", async () => {- const assign = vi.fn()- const stop = vi.fn()- vi.stubGlobal("location", { href: "https://alook.test/c", assign })- hookMocks.listen.mockResolvedValue(stop)+ it("uses the actual route commit to consume the clicked ID",async()=>{+ setRoute("/c/me/friends")hookMocks.take.mockResolvedValueOnce(activation)- hookMocks.revalidate.mockResolvedValue("allowed")-- const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))- await waitFor(() => expect(assign).toHaveBeenCalledWith(- "/c/channels/server_1/channel_1",- ))- expect(hookMocks.revalidate).toHaveBeenCalledWith(activation.target, expect.any(Function), expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function) }))+ const rendered=renderHook(useNotifications,{wrapper})+ await waitFor(()=>expect(route.navigation.pushImmediate).toHaveBeenCalledWith("/c/channels/server_1/channel_1"))expect(hookMocks.dismiss).not.toHaveBeenCalled()-- rendered.unmount()- expect(stop).toHaveBeenCalledOnce()-- hookMocks.take.mockResolvedValue(null)- hookMocks.dismiss- .mockRejectedValueOnce(new Error("native unavailable"))- .mockResolvedValueOnce(undefined)- vi.stubGlobal("location", {- href: "https://alook.test/c/channels/server_1/channel_1",- assign,- })- const destination = renderHook(() => useNativeSystemNotifications("viewer_1"))- await waitFor(() => expect(hookMocks.dismiss).toHaveBeenCalledOnce())- expect(window.sessionStorage.length).toBe(1)- await act(async () => { await Promise.resolve() })- window.dispatchEvent(new Event("focus"))- await waitFor(() => expect(hookMocks.dismiss).toHaveBeenCalledTimes(2))- expect(hookMocks.dismiss).toHaveBeenLastCalledWith(activation.notificationId)- await waitFor(() => expect(window.sessionStorage.length).toBe(0))- destination.unmount()- expect(stop).toHaveBeenCalledTimes(2)- })-- it("deduplicates concurrent destination mounts before native dismissal settles", async () => {- const notificationId = activation.notificationId- const dismissal = createNativeSystemNotificationDismissalQueue({- getItem: (key) => window.sessionStorage.getItem(key),- setItem: (key, value) => window.sessionStorage.setItem(key, value),- removeItem: (key) => window.sessionStorage.removeItem(key),- now: () => Date.now(),- })- dismissal.queue("desktop", notificationId, "/c/channels/server_1/channel_1")- vi.stubGlobal("location", {- href: "https://alook.test/c/channels/server_1/channel_1",- assign: vi.fn(),- })- hookMocks.listen.mockResolvedValue(vi.fn())- hookMocks.take.mockResolvedValue(null)- let resolveDismiss = () => undefined- hookMocks.dismiss.mockImplementation(() => new Promise<void>((resolve) => {- resolveDismiss = resolve- }))-- const owner = await createCommunityQueryOwner("viewer_1")- const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "viewer_1", retainOwner: true }, children)- const first = renderOwnedHook(() => useNativeSystemNotifications("viewer_1"), { wrapper })- const second = renderOwnedHook(() => useNativeSystemNotifications("viewer_1"), { wrapper })- await waitFor(() => expect(hookMocks.dismiss).toHaveBeenCalledOnce())- expect(window.sessionStorage.length).toBe(1)- resolveDismiss()- await waitFor(() => expect(window.sessionStorage.length).toBe(0))-- first.unmount()- second.unmount()- })-- it("persists an Inbox fallback, resumes it, and clears it after a real click", async () => {- vi.useFakeTimers()- const assign = vi.fn()- const stop = vi.fn()- vi.stubGlobal("location", { href: "https://alook.test/c/channels/server_1/channel_1", assign })- hookMocks.listen.mockResolvedValue(stop)- hookMocks.take.mockResolvedValueOnce(activation).mockResolvedValue(null)- hookMocks.revalidate.mockResolvedValue("invalid")-- const first = renderHook(() => useNativeSystemNotifications("viewer_1"))- await act(async () => {- await Promise.resolve()- await vi.advanceTimersByTimeAsync(2_000)- })- expect(assign).toHaveBeenCalledWith("https://alook.test/c")- expect(hookMocks.retryActivation).not.toHaveBeenCalled()- first.unmount()-- const button = document.createElement("button")- button.setAttribute("aria-label", "Inbox")- const click = vi.spyOn(button, "click")- document.body.append(button)- const second = renderHook(() => useNativeSystemNotifications("viewer_1"))- await act(async () => { await Promise.resolve() })- expect(click).toHaveBeenCalledOnce()- expect(window.sessionStorage.length).toBe(0)- second.unmount()- })-- it("re-arms the exact desktop activation on retryable validation failure", async () => {- const assign = vi.fn()- const stop = vi.fn()- const button = document.createElement("button")- button.setAttribute("aria-label", "Inbox")- const click = vi.spyOn(button, "click")- document.body.append(button)- vi.stubGlobal("location", { href: "https://alook.test/c/me/friends", assign })- hookMocks.listen.mockResolvedValue(stop)- hookMocks.take.mockResolvedValueOnce(activation).mockResolvedValue(null)- hookMocks.revalidate.mockResolvedValue("retryable")-- const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))- await waitFor(() => expect(hookMocks.retryActivation).toHaveBeenCalledExactlyOnceWith(- activation.notificationId,- ))- expect(click).toHaveBeenCalledOnce()- expect(assign).not.toHaveBeenCalled()+ setRoute("/c/me/friends",true);rendered.rerender()expect(hookMocks.dismiss).not.toHaveBeenCalled()-- rendered.unmount()- expect(stop).toHaveBeenCalledOnce()- })-- it("disposes the controller when native listener setup rejects", async () => {- hookMocks.listen.mockRejectedValue(new Error("native unavailable"))- hookMocks.take.mockResolvedValue(null)- const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))- await act(async () => { await Promise.resolve() })- expect(hookMocks.listen).toHaveBeenCalledOnce()- rendered.unmount()+ setRoute("/c/channels/server_1/channel_1");rendered.rerender()+ await waitFor(()=>expect(hookMocks.dismiss).toHaveBeenCalledExactlyOnceWith(activation.notificationId))+ await waitFor(()=>expect(window.sessionStorage.length).toBe(0));rendered.unmount()})-- it("uses one mobile listener for Web-ready registration and activation signals", async () => {+ it("queues a mobile activation before navigating and dismisses only its committed target", async () => {hookMocks.desktop = falsehookMocks.mobile = true- const calls: string[] = []- const assign = vi.fn()- const stop = vi.fn()- let signal: (() => void) | undefined- vi.stubGlobal("location", { href: "https://alook.test/c", assign })- hookMocks.mobileListen.mockImplementation(async (callback) => {- calls.push("listen")- signal = callback- return stop- })- hookMocks.mobileCheck.mockImplementation(async () => { calls.push("check"); return "granted" })- hookMocks.mobileSnapshot.mockImplementation(async () => {- calls.push("snapshot")- return {- installationId: "123e4567-e89b-42d3-a456-426614174000",- platform: "ios",- providerEnvironment: "sandbox",- providerToken: "token-00000000000",- }- })- hookMocks.mobilePost.mockImplementation(async () => { calls.push("post") })- hookMocks.mobileAck.mockImplementation(async () => { calls.push("ack") })- hookMocks.mobileTake- .mockImplementationOnce(async () => {- calls.push("take")- return {- notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",- messageId: "message_1",- targetId: "channel_1",- }- })- .mockImplementationOnce(async () => {- calls.push("take")- return {- notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",- messageId: "message_2",- targetId: "channel_1",- }- })- .mockImplementation(async () => { calls.push("take"); return null })- hookMocks.mobileRevalidate- .mockResolvedValueOnce({ href: "/c/me/channel_1" })- .mockResolvedValueOnce(null)-- const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))- await waitFor(() => expect(calls).toEqual([- "listen",- "check",- "take",- "snapshot",- "post",- "ack",- ]))- expect(hookMocks.mobileListen).toHaveBeenCalledOnce()- expect(assign).toHaveBeenCalledWith("/c/me/channel_1")- expect(hookMocks.mobileDismiss).not.toHaveBeenCalled()-- const button = document.createElement("button")- button.setAttribute("aria-label", "Inbox")- const click = vi.spyOn(button, "click")- document.body.append(button)- const visibilityState = vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible")- document.dispatchEvent(new Event("visibilitychange"))- await waitFor(() => expect(hookMocks.mobileCheck).toHaveBeenCalledTimes(2))- expect(hookMocks.mobileTake).toHaveBeenCalledTimes(2)- expect(click).toHaveBeenCalledOnce()-- signal?.()- await waitFor(() => expect(hookMocks.mobileCheck).toHaveBeenCalledTimes(3))- expect(hookMocks.mobileTake).toHaveBeenCalledTimes(3)- rendered.unmount()- visibilityState.mockRestore()- expect(stop).toHaveBeenCalledOnce()- })-- it("retries a mobile destination dismissal while the handoff is current", async () => {- hookMocks.desktop = false- hookMocks.mobile = true- const notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"- const dismissal = createNativeSystemNotificationDismissalQueue({+ setRoute("/c/me/friends")+ const clicked = { notificationId: activation.notificationId, messageId: "message_1", targetId: "channel_1" }+ hookMocks.mobileTake.mockResolvedValueOnce(clicked)+ const fetch = vi.fn(() => new Promise<Response>(() => undefined))+ vi.stubGlobal("fetch", fetch)+ const queue = createNativeSystemNotificationDismissalQueue({getItem: (key) => window.sessionStorage.getItem(key),setItem: (key, value) => window.sessionStorage.setItem(key, value),removeItem: (key) => window.sessionStorage.removeItem(key),now: () => Date.now(),})- dismissal.queue("mobile", notificationId, "/c/me/channel_1")- vi.stubGlobal("location", {- href: "https://alook.test/c/me/channel_1",- assign: vi.fn(),+ let queuedAtNavigation: string | null = null+ vi.mocked(route.navigation.pushImmediate).mockImplementation((href) => {+ queuedAtNavigation = queue.peek("mobile", "viewer", href)+ intentRevision++})- hookMocks.mobileListen.mockResolvedValue(vi.fn())- hookMocks.mobileCheck.mockResolvedValue("denied")- hookMocks.mobileTake.mockResolvedValue(null)- hookMocks.mobileDismiss- .mockRejectedValueOnce(new Error("native unavailable"))- .mockResolvedValueOnce(undefined)- const visibilityState = vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible")-- const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))- await waitFor(() => expect(hookMocks.mobileDismiss).toHaveBeenCalledOnce())- expect(window.sessionStorage.length).toBe(1)- await act(async () => { await Promise.resolve() })- document.dispatchEvent(new Event("visibilitychange"))- await waitFor(() => expect(hookMocks.mobileDismiss).toHaveBeenCalledTimes(2))+ const rendered = renderHook(useNotifications, { wrapper })+ await waitFor(() => expect(route.navigation.pushImmediate).toHaveBeenCalledExactlyOnceWith("/c/messages/message_1"))+ expect(queuedAtNavigation).toBe(clicked.notificationId)+ expect(queue.peek("mobile", "viewer", "/c/messages/message_1")).toBe(clicked.notificationId)+ expect(hookMocks.mobileRevalidate).not.toHaveBeenCalled()+ expect(fetch).not.toHaveBeenCalled()+ expect(hookMocks.mobileDismiss).not.toHaveBeenCalled()+ setRoute("/c/messages/message_1", true)+ rendered.rerender()+ expect(hookMocks.mobileDismiss).not.toHaveBeenCalled()+ setRoute("/c/messages/other_message")+ rendered.rerender()+ expect(hookMocks.mobileDismiss).not.toHaveBeenCalled()+ expect(queue.peek("mobile", "viewer", "/c/messages/message_1")).toBe(clicked.notificationId)+ setRoute("/c/messages/message_1")+ rendered.rerender()+ await waitFor(() => expect(hookMocks.mobileDismiss).toHaveBeenCalledExactlyOnceWith(clicked.notificationId))await waitFor(() => expect(window.sessionStorage.length).toBe(0))-rendered.unmount()- visibilityState.mockRestore()})-- it.each(["unmounted", "open"])("preserves the page when a foreground activation read fails with Inbox %s", async (inboxState) => {- vi.useFakeTimers()+ it("discards a delayed mobile activation after the hook retires", async () => {hookMocks.desktop = falsehookMocks.mobile = true- const assign = vi.fn()- vi.stubGlobal("location", { href: "https://alook.test/c/channels/server_1/channel_1", assign })- hookMocks.mobileListen.mockResolvedValue(vi.fn())- hookMocks.mobileCheck.mockResolvedValue("denied")- hookMocks.mobileTake.mockResolvedValueOnce(null).mockRejectedValue(new Error("native bridge unavailable"))- const button = document.createElement("button")- button.setAttribute("aria-label", "Close Inbox")- const click = vi.spyOn(button, "click")- if (inboxState === "open") document.body.append(button)- const visible = vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible")- const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))- await act(async () => { await vi.advanceTimersByTimeAsync(0) })- await act(async () => {- document.dispatchEvent(new Event("visibilitychange"))- await vi.advanceTimersByTimeAsync(2_100)- })- expect(hookMocks.mobileTake).toHaveBeenCalledTimes(2)- expect(assign).not.toHaveBeenCalled()- expect(click).not.toHaveBeenCalled()+ setRoute("/c/me/friends")+ const clicked = { notificationId: activation.notificationId, messageId: "message_1", targetId: "channel_1" }+ let release!: (value: typeof clicked) => void+ hookMocks.mobileTake.mockReturnValueOnce(new Promise<typeof clicked>(resolve => { release = resolve }))+ const rendered = renderHook(useNotifications, { wrapper })+ await waitFor(() => expect(hookMocks.mobileTake).toHaveBeenCalledOnce())+ rendered.unmount()+ await act(async () => { release(clicked) })+ expect(route.navigation.pushImmediate).not.toHaveBeenCalled()expect(window.sessionStorage.length).toBe(0)-- const nextActivation = {- notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",- messageId: "message_1",- targetId: "channel_1",- }- hookMocks.mobileTake.mockResolvedValueOnce(nextActivation)- hookMocks.mobileRevalidate.mockResolvedValueOnce({ href: "/c/me/channel_1" })- await act(async () => {- window.dispatchEvent(new Event("online"))- await vi.advanceTimersByTimeAsync(0)- })- expect(assign).toHaveBeenCalledExactlyOnceWith("/c/me/channel_1")+ expect(hookMocks.mobileDismiss).not.toHaveBeenCalled()+ })+})+describe("current native conversation",()=>{+ function useCurrent(ready=true) {useNotifications();useNativeSystemNotificationConversationDismissal("viewer",target,ready)}+ it("consumes an arrival after the initial ready dismissal has finished",async()=>{+ let wake!:()=>void;hookMocks.listen.mockImplementation(async cb=>{wake=cb;return()=>undefined})+ const rendered=renderHook(()=>useCurrent(),{wrapper})+ await waitFor(()=>expect(hookMocks.dismissConversation).toHaveBeenCalledOnce())+ await waitFor(()=>expect(window.localStorage.length).toBe(0))+ act(()=>wake());await waitFor(()=>expect(hookMocks.dismissConversation).toHaveBeenCalledTimes(2))rendered.unmount()- visible.mockRestore()})-+ it("retains and drains a newer demand received during cleanup",async()=>{+ let wake!:()=>void;let done!:()=>void+ hookMocks.listen.mockImplementation(async cb=>{wake=cb;return()=>undefined})+ hookMocks.dismissConversation.mockImplementationOnce(()=>new Promise<void>(resolve=>{done=resolve}))+ const rendered=renderHook(()=>useCurrent(),{wrapper})+ await waitFor(()=>expect(hookMocks.dismissConversation).toHaveBeenCalledOnce())+ act(()=>wake());expect(hookMocks.dismissConversation).toHaveBeenCalledOnce()+ await act(async()=>done())+ await waitFor(()=>expect(hookMocks.dismissConversation).toHaveBeenCalledTimes(2))+ await waitFor(()=>expect(window.localStorage.length).toBe(0));rendered.unmount()+ })+ it("keeps a failed revision until a new wake and has no retry timer",async()=>{+ let wake!:()=>void;hookMocks.listen.mockImplementation(async cb=>{wake=cb;return()=>undefined})+ hookMocks.dismissConversation.mockRejectedValueOnce(new Error("native unavailable"))+ const rendered=renderHook(()=>useCurrent(),{wrapper})+ await waitFor(()=>expect(hookMocks.dismissConversation).toHaveBeenCalledOnce())+ await act(async()=>{await Promise.resolve()});expect(window.localStorage.length).toBe(1)+ act(()=>wake());await waitFor(()=>expect(hookMocks.dismissConversation).toHaveBeenCalledTimes(2))+ await waitFor(()=>expect(window.localStorage.length).toBe(0));rendered.unmount()+ })+ it("authorizes presentation synchronously without queue or native side effects",async()=>{+ const rendered=renderHook(()=>useCurrent(),{wrapper})+ await waitFor(()=>expect(window.localStorage.length).toBe(0))+ const calls=hookMocks.dismissConversation.mock.calls.length+ expect(presentation({viewerUserId:"viewer",targetId:"channel_1"})).toBe(true)+ expect(presentation({viewerUserId:"other",targetId:"channel_1"})).toBe(false)+ expect(presentation({viewerUserId:"viewer",targetId:"channel_2"})).toBe(false)+ expect(presentation({viewerUserId:"viewer",targetId:"channel_1",extra:true})).toBe(false)+ expect(hookMocks.dismissConversation).toHaveBeenCalledTimes(calls)+ expect(window.localStorage.length).toBe(0)+ intentRevision+++ expect(presentation({viewerUserId:"viewer",targetId:"channel_1"})).toBe(false)+ rendered.unmount();expect(presentation({viewerUserId:"viewer",targetId:"channel_1"})).toBeUndefined()+ })+ it.each(["not ready","hidden","pending elsewhere","parent split"])("does not consume %s",async state=>{+ if(state==="hidden") vi.spyOn(document,"visibilityState","get").mockReturnValue("hidden")+ if(state==="pending elsewhere") setRoute("/c/channels/server_1/channel_1",true)+ if(state==="parent split") setRoute("/c/channels/server_1/channel_2")+ const rendered=renderHook(()=>useCurrent(state!=="not ready"),{wrapper})+ expect(presentation({viewerUserId:"viewer",targetId:"channel_1"})).toBe(false)+ expect(hookMocks.dismissConversation).not.toHaveBeenCalled();rendered.unmount()+ })+ it("consumes a ready mobile DM with the same single signal listener",async()=>{+ hookMocks.desktop=false;hookMocks.mobile=true;setRoute("/c/me/dm_1")+ let wake!:()=>void;hookMocks.mobileListen.mockImplementation(async cb=>{wake=cb;return()=>undefined})+ const rendered=renderHook(()=>{useNotifications();useNativeSystemNotificationConversationDismissal("viewer",{kind:"dm",channelId:"dm_1"},true)},{wrapper})+ await waitFor(()=>expect(hookMocks.mobileDismissConversation).toHaveBeenCalledExactlyOnceWith("viewer","dm_1"))+ await waitFor(()=>expect(window.localStorage.length).toBe(0))+ act(()=>wake());await waitFor(()=>expect(hookMocks.mobileDismissConversation).toHaveBeenCalledTimes(2))+ expect(hookMocks.mobileListen).toHaveBeenCalledOnce();rendered.unmount()+ })it("retries Native registration at one second and cancels later retry IO on retirement", async () => {vi.useFakeTimers()hookMocks.desktop = false@@ -788,7 +278,7 @@ describe("native system notification hook", () => {hookMocks.mobileTake.mockResolvedValue(null)const owner = await createCommunityQueryOwner("viewer_1")const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "viewer_1", retainOwner: true }, children)- const rendered = renderOwnedHook(() => useNativeSystemNotifications("viewer_1"), { wrapper })+ const rendered = renderOwnedHook(() => useNativeSystemNotifications("viewer_1", route.frame, route.navigation, consumer), { wrapper })const key = ["community", "native-notifications", "viewer_1", "mobile", "permission"]await act(async () => { await vi.advanceTimersByTimeAsync(0) })expect(hookMocks.mobileCheck).toHaveBeenCalledOnce()@@ -805,21 +295,4 @@ describe("native system notification hook", () => {expect(stop).toHaveBeenCalledOnce()})- it("continues mobile startup when native listener setup rejects", async () => {- hookMocks.desktop = false- hookMocks.mobile = true- hookMocks.mobileListen.mockRejectedValue(new Error("native unavailable"))- hookMocks.mobileCheck.mockResolvedValue("granted")- hookMocks.mobileSnapshot.mockResolvedValue({- installationId: "123e4567-e89b-42d3-a456-426614174000",- platform: "ios",- providerEnvironment: "sandbox",- })- hookMocks.mobileTake.mockResolvedValue(null)-- const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))- await waitFor(() => expect(hookMocks.mobileCheck).toHaveBeenCalledOnce())- expect(hookMocks.mobileTake).toHaveBeenCalledOnce()- rendered.unmount()- })})diff --git a/src/web/src/hooks/community/use-native-system-notifications.ts b/src/web/src/hooks/community/use-native-system-notifications.tsindex 359ac0736..0009c3c3f 100644--- a/src/web/src/hooks/community/use-native-system-notifications.ts+++ b/src/web/src/hooks/community/use-native-system-notifications.ts@@ -1,24 +1,23 @@"use client"-import { useEffect } from "react"+import { useEffect, useLayoutEffect, useRef, type RefObject } from "react"import { createStore } from "@tanstack/store"import { useQueryClient, QueryObserver, type QueryClient } from "@tanstack/react-query"import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"import { useCommunityViewSource } from "./use-community-view-source"import { isAbortError } from "@/lib/errors"+import { normalizeCommunityHref, type CommunityCommittedFrame } from "@/lib/community/community-route"+import { useCommunityRouteFrame, type NativeNotificationConversationConsumer, type CommunityNavigationController } from "@/contexts/community/route-frame"import { isDesktop, isMobile } from "@alook/shared"import {dismissDesktopSystemNotification,dismissDesktopSystemNotificationConversation,listenDesktopSystemNotificationActivations,- retryDesktopSystemNotificationActivation,takeDesktopSystemNotificationActivation,} from "@/lib/community/desktop-system-notification"import {- revalidateDesktopSystemNotificationTarget,systemNotificationHref,type DesktopSystemNotificationActivation,- type DesktopSystemNotificationTargetValidation,} from "@/lib/community/system-notification-route"import {acknowledgeMobileSystemNotificationRegistration,@@ -32,7 +31,6 @@ import {postMobileSystemNotificationRegistration,requestMobileSystemNotificationPermission,resumeMobileSystemNotificationRegistration,- revalidateMobileSystemNotificationActivation,snapshotMobileSystemNotificationRegistration,takeMobileSystemNotificationActivation,} from "@/lib/community/mobile-system-notification"@@ -99,14 +97,19 @@ function drainNativeSystemNotificationConversationDismissals(client: QueryClient,original: OriginalView,) {- for (const target of queue.pending(platform, viewerUserId)) {+ for (const { target, revision } of queue.pending(platform, viewerUserId)) {const key = ["community", "native-conversation-dismiss", platform, viewerUserId, conversationKey(target)]if (client.getMutationCache().findAll({ mutationKey: key, status: "pending" }).length) continuevoid nativeCommand(client, key, original, async () => {await dismissNativeSystemNotificationConversation(platform, viewerUserId, target)original()- queue.complete(platform, viewerUserId, target)- }).catch(() => undefined)+ queue.complete(platform, viewerUserId, target, revision)+ }).catch(() => undefined).finally(() => {+ try { original() } catch { return }+ if (queue.pending(platform, viewerUserId).some((entry) => conversationKey(entry.target) === conversationKey(target) && entry.revision !== revision)) {+ drainNativeSystemNotificationConversationDismissals(platform, viewerUserId, queue, client, original)+ }+ })}}@@ -116,7 +119,11 @@ export function useNativeSystemNotificationConversationDismissal(ready: boolean,) {const client = useQueryClient()+ const { frame, navigation, notificationConsumer: notificationConsumerRef } = useCommunityRouteFrame()+ const current = useRef({ frame, navigation })+ useLayoutEffect(() => { current.current = { frame, navigation } }, [frame, navigation])const source = useCommunityViewSource(`native-conversation-dismiss:${viewerUserId}:${target.channelId}`, ready)+ const captureIntent = navigation.captureIntentconst kind = target.kindconst channelId = target.channelIdconst serverId = target.kind === "server" ? target.serverId : undefined@@ -124,178 +131,71 @@ export function useNativeSystemNotificationConversationDismissal(if (!ready || (!isDesktop() && !isMobile())) returnconst platform = isDesktop() ? "desktop" : "mobile"const dismissalTarget: NativeSystemNotificationConversation = kind === "server"- ? { kind, serverId: serverId!, channelId }- : { kind, channelId }+ ? { 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, client, source.capture())- }, [channelId, client, kind, ready, serverId, source, viewerUserId])+ const original = source.capture()+ const intent = captureIntent()+ const consumer: NativeNotificationConversationConsumer = {+ matches: (viewer, targetId) => {+ try { original() } catch { return false }+ const route = current.current+ return viewer === viewerUserId && targetId === channelId && intent()+ && document.visibilityState === "visible" && !route.navigation.navigationPending+ && route.frame.pathname === systemNotificationHref(dismissalTarget)+ && normalizeCommunityHref(route.navigation.publishedHref).pathname === route.frame.pathname+ },+ requestDismiss: () => {+ if (!consumer.matches(viewerUserId, channelId)) return+ queue.queue(platform, viewerUserId, dismissalTarget)+ drainNativeSystemNotificationConversationDismissals(platform, viewerUserId, queue, client, original)+ },+ }+ const actual = current.current+ if (notificationConsumerRef && !actual.navigation.navigationPending+ && actual.frame.pathname === systemNotificationHref(dismissalTarget)+ && normalizeCommunityHref(actual.navigation.publishedHref).pathname === actual.frame.pathname) {+ notificationConsumerRef.current = consumer+ }+ consumer.requestDismiss()+ const onVisible = () => { if (document.visibilityState === "visible") consumer.requestDismiss() }+ document.addEventListener("visibilitychange", onVisible)+ return () => {+ document.removeEventListener("visibilitychange", onVisible)+ if (notificationConsumerRef?.current === consumer) notificationConsumerRef.current = null+ }+ }, [channelId, client, kind, ready, serverId, source, viewerUserId, notificationConsumerRef,+ frame.pathname, navigation.publishedHref, navigation.navigationPending, captureIntent])}function dismissPendingNativeSystemNotification(platform: "desktop" | "mobile",+ viewerUserId: string,pathname: string,dismissal: ReturnType<typeof createNativeSystemNotificationDismissalQueue>,dismiss: (notificationId: string) => Promise<void>,client: QueryClient,original: OriginalView,) {- const notificationId = dismissal.peek(platform, pathname)+ const notificationId = dismissal.peek(platform, viewerUserId, pathname)if (!notificationId) return- const key = ["community", "native-notification-dismiss", platform, pathname, notificationId]+ const key = ["community", "native-notification-dismiss", platform, viewerUserId, pathname, notificationId]if (client.getMutationCache().findAll({ mutationKey: key, status: "pending" }).length) returnvoid nativeCommand(client, key, original, async () => {await dismiss(notificationId)original()- dismissal.complete(platform, pathname, notificationId)+ dismissal.complete(platform, viewerUserId, pathname, notificationId)}).catch(() => undefined)}export type DesktopSystemNotificationActivationDeps = {listen: (ready: () => void) => Promise<() => void>take: () => Promise<DesktopSystemNotificationActivation | null>- revalidate: (- activation: DesktopSystemNotificationActivation,- ) => Promise<DesktopSystemNotificationTargetValidation>- retryActivation: (notificationId: string) => Promise<void>queueDismiss: (notificationId: string, href: string) => voidnavigate: (href: string) => void- openInbox: () => Promise<void> | void-}--type InboxIntent = {- version: 1- expiresAt: number- navigationStarted: boolean-}--export type DesktopSystemNotificationInboxDeps = {- getItem: (key: string) => string | null- setItem: (key: string, value: string) => void- removeItem: (key: string) => void- findTrigger: () => { click: () => void } | null- navigateToCommunity: () => void- wait: () => Promise<void>- now: () => number- pollAttempts?: number-}--const INBOX_INTENT_KEY = "alook:desktop-system-notification:inbox-intent"-const INBOX_INTENT_VERSION = 1-const INBOX_INTENT_TTL_MS = 5 * 60 * 1000-const INBOX_POLL_ATTEMPTS = 40--export function createDesktopSystemNotificationInboxOpener(- deps: DesktopSystemNotificationInboxDeps,-) {- const protocol = createStore({ disposed: false,- draining: null as Promise<void> | null });- function removeIntent() {- try {- deps.removeItem(INBOX_INTENT_KEY);- }- catch {- return;- }- }- function readIntent(): InboxIntent | null {- let raw: string | null;- try {- raw = deps.getItem(INBOX_INTENT_KEY);- }- catch {- return null;- }- if (raw === null)- return null;- try {- const value = JSON.parse(raw) as Partial<InboxIntent>;- if (value.version !== INBOX_INTENT_VERSION- || typeof value.expiresAt !== "number"- || !Number.isFinite(value.expiresAt)- || value.expiresAt <= deps.now()- || typeof value.navigationStarted !== "boolean"- || Object.keys(value).some((key) => !["version", "expiresAt", "navigationStarted"].includes(key))) {- removeIntent();- return null;- }- return value as InboxIntent;- }- catch {- removeIntent();- return null;- }- }- function writeIntent(intent: InboxIntent) {- try {- deps.setItem(INBOX_INTENT_KEY, JSON.stringify(intent));- return true;- }- catch {- return false;- }- }- function queueIntent() {- if (readIntent())- return true;- return writeIntent({- version: INBOX_INTENT_VERSION,- expiresAt: deps.now() + INBOX_INTENT_TTL_MS,- navigationStarted: false,- });- }- function consume() {- if (protocol.get().draining)- return protocol.get().draining;- const draining = Promise.resolve().then(async () => {- const attempts = Math.max(1, deps.pollAttempts ?? INBOX_POLL_ATTEMPTS);- for (let attempt = 0; attempt < attempts; attempt += 1) {- if (protocol.get().disposed || !readIntent())- return;- const trigger = deps.findTrigger();- if (trigger) {- if (protocol.get().disposed)- return;- trigger.click();- removeIntent();- return;- }- if (attempt + 1 < attempts)- await deps.wait();- }- if (protocol.get().disposed)- return;- const intent = readIntent();- if (!intent || intent.navigationStarted)- return;- if (!writeIntent({ ...intent, navigationStarted: true }))- return;- deps.navigateToCommunity();- }).finally(() => {- protocol.setState(state => ({ ...state, draining: null }));- });- protocol.setState(state => ({ ...state, draining }));- return protocol.get().draining;- }- return {- async open() {- if (protocol.get().disposed || !queueIntent())- return;- await consume();- },- async resume() {- if (protocol.get().disposed || !readIntent())- return;- await consume();- },- dispose() {- protocol.setState(state => ({ ...state, disposed: true }));- },- };}export function createDesktopSystemNotificationActivationController(@@ -317,26 +217,13 @@ export function createDesktopSystemNotificationActivationController(const activation = await deps.take().catch(() => null);if (!activation || protocol.get().disposed)continue;- const validation = await deps.revalidate(activation).catch(() => "retryable" as const);- if (protocol.get().disposed)- continue;- if (validation === "allowed") {- const href = systemNotificationHref(activation.target);- try {- deps.queueDismiss(activation.notificationId, href);- }- catch { }- if (!protocol.get().disposed)- deps.navigate(href);- }- else {- if (validation === "retryable") {- await deps.retryActivation(activation.notificationId).catch(() => undefined);- if (protocol.get().disposed)- continue;- }- await deps.openInbox();+ const href = systemNotificationHref(activation.target);+ try {+ deps.queueDismiss(activation.notificationId, href);}+ catch { }+ if (!protocol.get().disposed)+ deps.navigate(href);} while (protocol.get().rerun && !protocol.get().disposed);}finally {@@ -363,12 +250,31 @@ export function createDesktopSystemNotificationActivationController(};}-export function useNativeSystemNotifications(viewerUserId: string) {+export function useNativeSystemNotifications(+ viewerUserId: string,+ frame: CommunityCommittedFrame,+ navigation: CommunityNavigationController,+ notificationConsumer: RefObject<NativeNotificationConversationConsumer | null>,+) {+ const currentRoute = useRef({ frame, navigation })+ const committedDismissal = useRef<() => void>(() => undefined)+ useLayoutEffect(() => { currentRoute.current = { frame, navigation } }, [frame, navigation])const client = useQueryClient()const source = useCommunityViewSource(`native-notifications:${viewerUserId}`)useEffect(() => {const original = source.capture()original()+ const presentationWindow = window as Window & { alookNativeNotificationPresentationV1?: (identity: unknown) => boolean }+ const presentation = (identity: unknown) => {+ try { original() } catch { return false }+ if (!identity || typeof identity !== "object" || Array.isArray(identity)) return false+ const value = identity as Record<string, unknown>+ return Object.keys(value).length === 2 && typeof value.viewerUserId === "string"+ && typeof value.targetId === "string" && value.viewerUserId === viewerUserId+ && notificationConsumer.current?.matches(value.viewerUserId, value.targetId) === true+ }+ presentationWindow.alookNativeNotificationPresentationV1 = presentation+ const requestCurrentDismissal = () => { try { original() } catch { return }; notificationConsumer.current?.requestDismiss() }const key = (...parts: readonly unknown[]) => ["community", "native-notifications", viewerUserId, ...parts]const dismissal = createNativeSystemNotificationDismissalQueue({getItem: (key) => window.sessionStorage.getItem(key),@@ -376,23 +282,27 @@ export function useNativeSystemNotifications(viewerUserId: string) {removeItem: (key) => window.sessionStorage.removeItem(key),now: () => Date.now(),})- const pathname = new URL(window.location.href).pathnameconst 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),- removeItem: (key) => window.sessionStorage.removeItem(key),- findTrigger: () => { original(); return document.querySelector<HTMLButtonElement>(- 'button[aria-label="Inbox"], button[aria-label="Open Inbox"]',- ) },- navigateToCommunity: () => { original(); window.location.assign(new URL("/c", window.location.href).href) },- wait: () => new Promise<void>((resolve) => window.setTimeout(resolve, 50)),- now: () => Date.now(),- })+ const dismissPending = () => {+ try { original() } catch { return }+ const { frame: actualFrame, navigation: currentNavigation } = currentRoute.current+ if (currentNavigation.navigationPending+ || normalizeCommunityHref(currentNavigation.publishedHref).href !== actualFrame.href) return+ const platform = isDesktop() ? "desktop" : isMobile() ? "mobile" : null+ if (!platform) return+ dismissPendingNativeSystemNotification(platform, viewerUserId, actualFrame.pathname,+ dismissal, platform === "desktop" ? dismissDesktopSystemNotification : dismissMobileSystemNotification,+ client, original)+ }+ committedDismissal.current = dismissPending+ const releaseDismissal = () => {+ if (presentationWindow.alookNativeNotificationPresentationV1 === presentation) delete presentationWindow.alookNativeNotificationPresentationV1+ if (committedDismissal.current === dismissPending) committedDismissal.current = () => undefined+ }if (isDesktop()) {const drainConversations = () => drainNativeSystemNotificationConversationDismissals(@@ -400,52 +310,35 @@ export function useNativeSystemNotifications(viewerUserId: string) {viewerUserId,conversationDismissals, client, original,)- const dismissPending = () => dismissPendingNativeSystemNotification(- "desktop",- pathname,- dismissal,- dismissDesktopSystemNotification, client, original,- )dismissPending()drainConversations()window.addEventListener("focus", dismissPending)window.addEventListener("focus", drainConversations)+ window.addEventListener("focus", requestCurrentDismissal)window.addEventListener("online", drainConversations)const browserDeps: DesktopSystemNotificationActivationDeps = {- listen: listenDesktopSystemNotificationActivations,+ listen: (wake) => listenDesktopSystemNotificationActivations(() => { requestCurrentDismissal(); wake() }),take: () => nativeCommand(client, key("desktop", "take"), original, takeDesktopSystemNotificationActivation),- revalidate: ({ target }) => nativeRead(client, key("desktop", "target", target), original, (options) => revalidateDesktopSystemNotificationTarget(target, fetch, options)),- retryActivation: (id) => nativeCommand(client, key("desktop", "retry", id), original, () => retryDesktopSystemNotificationActivation(id)),queueDismiss: (notificationId, href) => {- original(); dismissal.queue("desktop", notificationId, href)+ original(); dismissal.queue("desktop", viewerUserId, notificationId, href)},- navigate: (href) => { original(); window.location.assign(href) },- openInbox: () => { original(); return inbox.open() },+ navigate: (href) => { original(); currentRoute.current.navigation.pushImmediate(href); dismissPending() },}const controller = createDesktopSystemNotificationActivationController(browserDeps)- void inbox.resume().catch(() => undefined)void controller.connect().catch(() => controller.dispose())return () => {window.removeEventListener("focus", dismissPending)window.removeEventListener("focus", drainConversations)+ window.removeEventListener("focus", requestCurrentDismissal)window.removeEventListener("online", drainConversations)controller.dispose()- inbox.dispose()+ releaseDismissal()}}- if (!isMobile()) {- inbox.dispose()- return- }+ if (!isMobile()) return releaseDismissalresumeMobileSystemNotificationRegistration()- const dismissPending = () => dismissPendingNativeSystemNotification(- "mobile",- pathname,- dismissal,- dismissMobileSystemNotification, client, original,- )dismissPending()const registration = createMobileSystemNotificationRegistrationController({@@ -461,17 +354,16 @@ export function useNativeSystemNotifications(viewerUserId: string) {})const activation = createMobileSystemNotificationActivationController({take: () => nativeCommand(client, key("mobile", "take"), original, takeMobileSystemNotificationActivation),- revalidate: (activation) => nativeRead(client, key("mobile", "target", activation.targetId, activation.messageId), original, (options) => revalidateMobileSystemNotificationActivation(activation, fetch, options)),queueDismiss: (notificationId, href) => {- original(); dismissal.queue("mobile", notificationId, href)+ original(); dismissal.queue("mobile", viewerUserId, notificationId, href)},- navigate: (href) => { original(); window.location.assign(href) },- openInbox: () => { original(); return inbox.open() },+ navigate: (href) => { original(); currentRoute.current.navigation.pushImmediate(href); dismissPending() },})let disposed = falselet unlisten: (() => void) | undefinedconst synchronize = () => {+ requestCurrentDismissal()dismissPending()drainNativeSystemNotificationConversationDismissals("mobile", viewerUserId, conversationDismissals, client, original)void registration.sync().catch(() => undefined)@@ -483,7 +375,6 @@ export function useNativeSystemNotifications(viewerUserId: string) {window.addEventListener("online", synchronize)document.addEventListener("visibilitychange", onVisibilityChange)- void inbox.resume().catch(() => undefined)drainNativeSystemNotificationConversationDismissals("mobile", viewerUserId, conversationDismissals, client, original)void (async () => {try {@@ -504,7 +395,8 @@ export function useNativeSystemNotifications(viewerUserId: string) {unlisten?.()registration.dispose()activation.dispose()- inbox.dispose()+ releaseDismissal()}- }, [viewerUserId, client, source])+ }, [viewerUserId, client, source, notificationConsumer])+ useEffect(() => { committedDismissal.current() }, [frame.href, navigation.publishedHref, navigation.navigationPending])}diff --git a/src/web/src/lib/community/community-route.test.ts b/src/web/src/lib/community/community-route.test.tsindex 8248f3079..e7b0de014 100644--- a/src/web/src/lib/community/community-route.test.ts+++ b/src/web/src/lib/community/community-route.test.ts@@ -318,3 +318,16 @@ describe("community route", () => {).toBe("/c/channels/server_1/channel_1")})})+++describe("ordinary message resolution route", () => {+ it("recognizes only one safe message ID", () => {+ expect(resolveCommunityModulePlan("/c/messages/message_1")).toMatchObject({route:"message-resolution",sidebar:{kind:"none"},main:{kind:"route-resolution"}})+ for (const href of ["/c/messages", "/c/messages/a/b", "/c/messages/%2F", "/c/messages/."]) expect(resolveCommunityModulePlan(href).route).toBe("unknown")+ })+ it("publishes a target checkpoint before a message leaf commits", () => {+ const committedFrame={...normalizeCommunityHref("/c/me/friends"),revision:1}+ expect(resolveCommunityCheckpointPlan({committedFrame,targetHref:"/c/messages/message_1",pending:true,targetReady:false})).toMatchObject({main:{kind:"target-skeleton",href:"/c/messages/message_1"}})+ expect(resolveCommunityCheckpointPlan({committedFrame,targetHref:"/c/unknown",pending:true,targetReady:false}).main.kind).toBe("keep")+ })+})diff --git a/src/web/src/lib/community/community-route.ts b/src/web/src/lib/community/community-route.tsindex c4cd31f76..ffd82bc47 100644--- a/src/web/src/lib/community/community-route.ts+++ b/src/web/src/lib/community/community-route.ts@@ -7,6 +7,7 @@ type CommunityModuleRoute =| "me-machines"| "me-bots"| "dm-detail"+ | "message-resolution"| "server-root"| "server-detail"| "server-settings-redirect"@@ -134,6 +135,11 @@ export function resolveCommunityModulePlan(href: string): CommunityModulePlan {}}+ if (segments[1] === "messages" && segments.length === 3 && /^[A-Za-z0-9_-]{1,128}$/.test(segments[2]!)) {+ return { route: "message-resolution", surface: "detail", rail: "community",+ sidebar: { kind: "none" }, main: { kind: "route-resolution" } }+ }+if (segments[1] === "me") {if (segments.length === 2) {return {@@ -300,7 +306,13 @@ export function resolveCommunityCheckpointPlan({}const target = normalizeCommunityHref(targetHref)- const targetMainKind = resolveCommunityModulePlan(target.href).main.kind+ const targetModule = resolveCommunityModulePlan(target.href)+ if (targetModule.route === "message-resolution" && target.leafKey !== committedFrame.leafKey) {+ return { mode: "cold-scope", surface: target.surface, targetHref: target.href,+ rail: { kind: "keep" }, sidebar: { kind: "keep" },+ main: { kind: "target-skeleton", href: target.href } }+ }+ const targetMainKind = targetModule.main.kindconst isConversationTarget = targetMainKind === "server-conversation" || targetMainKind === "dm"if (target.scope.kind === "unknown" || target.leafKey === committedFrame.leafKey) {return committedPlan(committedFrame, target.href)diff --git a/src/web/src/lib/community/desktop-system-notification.test.ts b/src/web/src/lib/community/desktop-system-notification.test.tsindex b74ecb260..5c3fb13a8 100644--- a/src/web/src/lib/community/desktop-system-notification.test.ts+++ b/src/web/src/lib/community/desktop-system-notification.test.ts@@ -9,7 +9,6 @@ import {dismissDesktopSystemNotificationConversation,listenDesktopSystemNotificationActivations,resolveDesktopSystemNotificationCandidate,- retryDesktopSystemNotificationActivation,showDesktopSystemNotification,takeDesktopSystemNotificationActivation,} from "./desktop-system-notification"@@ -443,13 +442,4 @@ describe("desktop system notification activation bridge", () => {)})- it("re-arms exactly one native notification id", async () => {- invoke.mockResolvedValueOnce(undefined)- const notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"- await expect(retryDesktopSystemNotificationActivation(notificationId)).resolves.toBeUndefined()- expect(invoke).toHaveBeenCalledWith(- "desktop_system_notification_retry_activation",- { notificationId },- )- })})diff --git a/src/web/src/lib/community/desktop-system-notification.ts b/src/web/src/lib/community/desktop-system-notification.tsindex 3c923d2d7..bc21c49cb 100644--- a/src/web/src/lib/community/desktop-system-notification.ts+++ b/src/web/src/lib/community/desktop-system-notification.ts@@ -165,10 +165,6 @@ export async function takeDesktopSystemNotificationActivation(): Promise<Desktopreturn parseDesktopSystemNotificationActivation(value)}-export async function retryDesktopSystemNotificationActivation(notificationId: string): Promise<void> {- await tauriInvoke("desktop_system_notification_retry_activation", { notificationId })-}-export async function dismissDesktopSystemNotification(notificationId: string): Promise<void> {await tauriInvoke("desktop_system_notification_dismiss", { notificationId })}diff --git a/src/web/src/lib/community/mobile-system-notification.test.ts b/src/web/src/lib/community/mobile-system-notification.test.tsindex f854ebb31..f245ea191 100644--- a/src/web/src/lib/community/mobile-system-notification.test.ts+++ b/src/web/src/lib/community/mobile-system-notification.test.ts@@ -13,7 +13,7 @@ import {parseMobileSystemNotificationRegistration,postMobileSystemNotificationRegistration,requestMobileSystemNotificationPermission,- revalidateMobileSystemNotificationActivation,+ mobileSystemNotificationHref,resumeMobileSystemNotificationRegistration,snapshotMobileSystemNotificationRegistration,suspendMobileSystemNotificationRegistration,@@ -279,17 +279,11 @@ describe("mobile notification HTTP adapter", () => {previousProviderToken: null,})await unregisterCurrentMobileSystemNotification()- await expect(revalidateMobileSystemNotificationActivation({- notificationId,- messageId: "message_1",- targetId: "channel_1",- })).resolves.toEqual({ href: "/c/me/channel_1" })expect(fetchImpl.mock.calls.map(([url]) => url)).toEqual(["/api/community/notifications/devices",`/api/community/notifications/devices/${installationId}`,`/api/community/notifications/devices/${installationId}`,- "/api/community/channels/channel_1/messages?anchor=message_1&limit=1",])})@@ -506,172 +500,47 @@ describe("mobile notification registration controller", () => {describe("mobile notification activation", () => {const activation = { notificationId, messageId: "message_1", targetId: "channel_1" }-- it.each([["channel", "text"], ["forum", "forum"], ["thread", "thread"]] as const)("opens chat pages after exact DM and %s revalidation", async (surfaceKind, type) => {- const dmFetch = vi.fn()- .mockResolvedValueOnce(new Response(JSON.stringify({- messages: [{ id: "message_1", seq: 9 }],- surfaceReceipt: { channelId: "channel_1", surfaceKind: "dm" },- })))- await expect(revalidateMobileSystemNotificationActivation(activation, dmFetch)).resolves.toEqual({- href: "/c/me/channel_1",- })-- const serverFetch = vi.fn()- .mockResolvedValueOnce(new Response(JSON.stringify({- messages: [{ id: "message_1", seq: 9 }],- surfaceReceipt: { channelId: "channel_1", surfaceKind },- })))- .mockResolvedValueOnce(new Response(JSON.stringify({- id: "channel_1",- serverId: "server_1",- type,- })))- await expect(revalidateMobileSystemNotificationActivation(activation, serverFetch)).resolves.toEqual({- href: "/c/channels/server_1/channel_1",- })- expect(serverFetch.mock.calls.map(([url]) => url)).toEqual([- "/api/community/channels/channel_1/messages?anchor=message_1&limit=1",- "/api/community/channels/channel_1",- ])- })-- it.each([- ["cold", "dm"], ["resume", "dm"],- ["cold", "channel"], ["resume", "channel"],- ] as const)("navigates %s %s activation without selecting a message", async (lifecycle, kind) => {- const fetchImpl = vi.fn()- .mockResolvedValueOnce(new Response(JSON.stringify({- messages: [{ id: activation.messageId, seq: 9 }],- surfaceReceipt: { channelId: activation.targetId, surfaceKind: kind },- })))- .mockResolvedValueOnce(new Response(JSON.stringify({- id: activation.targetId, serverId: "server_1", type: "text",- })))+ it.each(["cold", "resume"])("starts the ordinary message page immediately on %s activation", async (phase) => {+ const fetchImpl = vi.fn(() => new Promise<Response>(() => undefined))+ vi.stubGlobal("fetch", fetchImpl)const take = vi.fn()- if (lifecycle === "resume") take.mockResolvedValueOnce(null)+ if (phase === "resume") take.mockResolvedValueOnce(null)take.mockResolvedValueOnce(activation)const navigate = vi.fn()- const openInbox = vi.fn()const queueDismiss = vi.fn()- const controller = createMobileSystemNotificationActivationController({- take,- revalidate: (value) => revalidateMobileSystemNotificationActivation(value, fetchImpl),- queueDismiss,- navigate,- openInbox,- })- if (lifecycle === "resume") {- await controller.drain()- expect(navigate).not.toHaveBeenCalled()- }+ const controller = createMobileSystemNotificationActivationController({ take, queueDismiss, navigate })+ if (phase === "resume") await controller.drain()await controller.drain()- const href = kind === "dm" ? "/c/me/channel_1" : "/c/channels/server_1/channel_1"- expect(navigate).toHaveBeenCalledExactlyOnceWith(href)- expect(queueDismiss).toHaveBeenCalledExactlyOnceWith(notificationId, href)- expect(new URL(href, "https://example.test").search).toBe("")- expect(openInbox).not.toHaveBeenCalled()- controller.dispose()- })-- it.each([- ["deleted", new Response(null, { status: 404 })],- ["revoked", new Response(null, { status: 403 })],- ["wrong message", new Response(JSON.stringify({- messages: [{ id: "other", seq: 9 }],- surfaceReceipt: { channelId: "channel_1", surfaceKind: "dm" },- }))],- ["wrong target", new Response(JSON.stringify({- messages: [{ id: "message_1", seq: 9 }],- surfaceReceipt: { channelId: "other", surfaceKind: "dm" },- }))],- ["receipt extras", new Response(JSON.stringify({- messages: [{ id: "message_1", seq: 9 }],- surfaceReceipt: { channelId: "channel_1", surfaceKind: "dm", secret: true },- }))],- ["invalid surface", new Response(JSON.stringify({- messages: [{ id: "message_1", seq: 9 }],- surfaceReceipt: { channelId: "channel_1", surfaceKind: "private" },- }))],- ])("falls back for %s message-door results", async (_label, response) => {- await expect(revalidateMobileSystemNotificationActivation(- activation,- vi.fn(async () => response),- )).resolves.toBeNull()+ expect(navigate).toHaveBeenCalledExactlyOnceWith("/c/messages/message_1")+ expect(queueDismiss).toHaveBeenCalledExactlyOnceWith(notificationId, "/c/messages/message_1")+ expect(fetchImpl).not.toHaveBeenCalled()+ expect(mobileSystemNotificationHref(activation)).toBe("/c/messages/message_1")})-- it("opens Inbox for an unreadable destination but ignores unavailable activation reads", async () => {- const openInbox = vi.fn()+ it("preserves navigation on storage failure and ignores unavailable native reads", async () => {const navigate = vi.fn()const controller = createMobileSystemNotificationActivationController({- take: vi.fn()- .mockResolvedValueOnce(activation)- .mockRejectedValueOnce(new Error("invalid native response")),- revalidate: vi.fn().mockRejectedValueOnce(new Error("offline")),- queueDismiss: vi.fn(),- navigate,- openInbox,+ take: vi.fn().mockResolvedValueOnce(activation).mockRejectedValueOnce(new Error("native unavailable")),+ queueDismiss: () => { throw new Error("blocked") }, navigate,})await controller.drain()- expect(openInbox).toHaveBeenCalledTimes(1)await controller.drain()- expect(openInbox).toHaveBeenCalledTimes(1)- expect(navigate).not.toHaveBeenCalled()+ expect(navigate).toHaveBeenCalledExactlyOnceWith("/c/messages/message_1")})-- it("still navigates when dismissal persistence fails", async () => {+ it("drains a new signal after an active take and ignores a result after disposal", async () => {+ let resolve!: (value: typeof activation | null) => void+ const pending = new Promise<typeof activation | null>((done) => { resolve = done })+ const take = vi.fn().mockReturnValueOnce(pending).mockResolvedValueOnce(activation)const navigate = vi.fn()- const controller = createMobileSystemNotificationActivationController({- take: vi.fn(async () => activation),- revalidate: vi.fn(async () => ({ href: "/c/me/channel_1" })),- queueDismiss: vi.fn(() => { throw new Error("storage unavailable") }),- navigate,- openInbox: vi.fn(),- })- await controller.drain()- expect(navigate).toHaveBeenCalledExactlyOnceWith("/c/me/channel_1")- })-- it("coalesces a signal received while an activation drain is active", async () => {- let releaseTake = (_value: null) => undefined- const firstTake = new Promise<null>((resolve) => { releaseTake = resolve })- const take = vi.fn().mockReturnValueOnce(firstTake).mockResolvedValueOnce(null)- const controller = createMobileSystemNotificationActivationController({- take,- revalidate: vi.fn(),- queueDismiss: vi.fn(),- navigate: vi.fn(),- openInbox: vi.fn(),- })-+ const controller = createMobileSystemNotificationActivationController({ take, navigate, queueDismiss: vi.fn() })const first = controller.drain()- await vi.waitFor(() => expect(take).toHaveBeenCalledOnce())await controller.drain()- releaseTake(null)+ resolve(null)await firstexpect(take).toHaveBeenCalledTimes(2)- })-- it("rejects invalid server-channel payloads and network failures", async () => {- const messageResponse = () => new Response(JSON.stringify({- messages: [{ id: "message_1", seq: 9 }],- surfaceReceipt: { channelId: "channel_1", surfaceKind: "thread" },- }))- const invalidChannel = vi.fn()- .mockResolvedValueOnce(messageResponse())- .mockResolvedValueOnce(new Response(JSON.stringify({- id: "channel_1",- serverId: "server_1",- type: "dm",- })))- await expect(revalidateMobileSystemNotificationActivation(- activation,- invalidChannel,- )).resolves.toBeNull()-- await expect(revalidateMobileSystemNotificationActivation(- activation,- vi.fn(async () => { throw new Error("offline") }),- )).resolves.toBeNull()+ expect(navigate).toHaveBeenCalledOnce()+ take.mockReturnValueOnce(pending)+ controller.dispose()+ await controller.drain()+ expect(take).toHaveBeenCalledTimes(2)})})diff --git a/src/web/src/lib/community/mobile-system-notification.ts b/src/web/src/lib/community/mobile-system-notification.tsindex 526270b4a..6807b3d1b 100644--- a/src/web/src/lib/community/mobile-system-notification.ts+++ b/src/web/src/lib/community/mobile-system-notification.ts@@ -1,7 +1,6 @@import { isMobile, isTauri, tauriInvoke } from "@alook/shared"import { createStore } from "@tanstack/store"import { QueryClient } from "@tanstack/react-query"-import { systemNotificationHref } from "./system-notification-route"export type MobileSystemNotificationPermission = "granted" | "denied" | "prompt"@@ -20,10 +19,6 @@ export type MobileSystemNotificationActivation = {targetId: string}-export type MobileSystemNotificationDestination = {- href: string-}-const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iconst RETRY_DELAYS_MS = [1_000, 5_000, 30_000, 60_000] as const@@ -371,12 +366,8 @@ export function createMobileSystemNotificationRegistrationController(export type MobileSystemNotificationActivationDeps = {take: () => Promise<MobileSystemNotificationActivation | null>- revalidate: (- activation: MobileSystemNotificationActivation,- ) => Promise<MobileSystemNotificationDestination | null>queueDismiss: (notificationId: string, href: string) => voidnavigate: (href: string) => void- openInbox: () => Promise<void> | void}export function createMobileSystemNotificationActivationController(@@ -403,19 +394,13 @@ export function createMobileSystemNotificationActivationController(}if (!activation || protocol.get().disposed)continue;- const destination = await deps.revalidate(activation).catch(() => null);- if (protocol.get().disposed)- continue;- if (destination) {- try {- deps.queueDismiss(activation.notificationId, destination.href);- }- catch { }- if (!protocol.get().disposed)- deps.navigate(destination.href);+ const href = mobileSystemNotificationHref(activation);+ try {+ deps.queueDismiss(activation.notificationId, href);}- else- await deps.openInbox();+ catch { }+ if (!protocol.get().disposed)+ deps.navigate(href);} while (protocol.get().rerun && !protocol.get().disposed);}finally {@@ -430,76 +415,6 @@ export function createMobileSystemNotificationActivationController(};}-type SurfaceKind = "channel" | "forum" | "thread" | "dm"--function surfaceReceipt(value: unknown): { channelId: string; surfaceKind: SurfaceKind } | null {- if (!isObject(value) || !hasExactKeys(value, ["channelId", "surfaceKind"])) return null- if (!isSafeId(value.channelId)) return null- if (value.surfaceKind !== "channel"- && value.surfaceKind !== "forum"- && value.surfaceKind !== "thread"- && value.surfaceKind !== "dm") return null- return { channelId: value.channelId, surfaceKind: value.surfaceKind }-}--export async function revalidateMobileSystemNotificationActivation(- activation: MobileSystemNotificationActivation,- fetchImpl: typeof fetch = fetch,- options: { signal?: AbortSignal; assertActive?: () => void } = {},-): Promise<MobileSystemNotificationDestination | null> {- try {- options.assertActive?.()- const messageResponse = await fetchImpl(- `/api/community/channels/${encodeURIComponent(activation.targetId)}/messages?anchor=${encodeURIComponent(activation.messageId)}&limit=1`,- { method: "GET", credentials: "same-origin", cache: "no-store", signal: options.signal },- )- options.assertActive?.()- if (!messageResponse.ok) return null- const messagePayload: unknown = await messageResponse.json()- options.assertActive?.()- if (!isObject(messagePayload) || !Array.isArray(messagePayload.messages)) return null- const receipt = surfaceReceipt(messagePayload.surfaceReceipt)- if (!receipt || receipt.channelId !== activation.targetId) return null- const message = messagePayload.messages.find((candidate) => (- isObject(candidate)- && candidate.id === activation.messageId- && typeof candidate.seq === "number"- && Number.isSafeInteger(candidate.seq)- && candidate.seq > 0- ))- if (!isObject(message) || typeof message.seq !== "number") return null-- if (receipt.surfaceKind === "dm") {- return {- href: systemNotificationHref({ kind: "dm", channelId: activation.targetId }),- }- }-- const channelResponse = await fetchImpl(- `/api/community/channels/${encodeURIComponent(activation.targetId)}`,- { method: "GET", credentials: "same-origin", cache: "no-store", signal: options.signal },- )- options.assertActive?.()- if (!channelResponse.ok) return null- const channel: unknown = await channelResponse.json()- options.assertActive?.()- if (!isObject(channel)- || channel.id !== activation.targetId- || !isSafeId(channel.serverId)- || (channel.type !== "text" && channel.type !== "forum" && channel.type !== "thread")) {- return null- }- const expectedType = receipt.surfaceKind === "channel" ? "text" : receipt.surfaceKind- if (channel.type !== expectedType) return null- return {- href: systemNotificationHref({- kind: "server",- serverId: channel.serverId,- channelId: activation.targetId,- }),- }- } catch {- options.assertActive?.()- return null- }+export function mobileSystemNotificationHref(activation: MobileSystemNotificationActivation): string {+ return `/c/messages/${encodeURIComponent(activation.messageId)}`}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 c6fa906a7..3b7e08c12 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@@ -24,23 +24,23 @@ describe("native notification dismissal handoff", () => {it("completes an exact platform and destination match once", () => {const values = new Map<string, string>()const queue = createNativeSystemNotificationDismissalQueue(deps(values))- expect(queue.queue("mobile", notificationId, "/c/me/channel_1")).toBe(true)- expect(queue.peek("desktop", "/c/me/channel_1")).toBeNull()- expect(queue.peek("mobile", "/c/me/channel_2")).toBeNull()- expect(queue.peek("mobile", "/c/me/channel_1")).toBe(notificationId)- expect(queue.complete("mobile", "/c/me/channel_2", notificationId)).toBe(false)- expect(queue.complete("mobile", "/c/me/channel_1", notificationId)).toBe(true)- expect(queue.peek("mobile", "/c/me/channel_1")).toBeNull()+ expect(queue.queue("mobile", "viewer_1", notificationId, "/c/me/channel_1")).toBe(true)+ expect(queue.peek("desktop", "viewer_1", "/c/me/channel_1")).toBeNull()+ expect(queue.peek("mobile", "viewer_1", "/c/me/channel_2")).toBeNull()+ expect(queue.peek("mobile", "viewer_1", "/c/me/channel_1")).toBe(notificationId)+ expect(queue.complete("mobile", "viewer_1", "/c/me/channel_2", notificationId)).toBe(false)+ expect(queue.complete("mobile", "viewer_1", "/c/me/channel_1", notificationId)).toBe(true)+ expect(queue.peek("mobile", "viewer_1", "/c/me/channel_1")).toBeNull()})it("rejects unsafe values and removes corrupt or expired handoffs", () => {const values = new Map<string, string>()const queue = createNativeSystemNotificationDismissalQueue(deps(values))- expect(queue.queue("desktop", "bad", "/c/me/channel_1")).toBe(false)- expect(queue.queue("desktop", notificationId, "https://evil.test/c/me/channel_1")).toBe(false)+ expect(queue.queue("desktop", "viewer_1", "bad", "/c/me/channel_1")).toBe(false)+ expect(queue.queue("desktop", "viewer_1", notificationId, "https://evil.test/c/me/channel_1")).toBe(false)values.set("alook:native-system-notification:pending-dismissal", "corrupt")- expect(queue.peek("desktop", "/c/me/channel_1")).toBeNull()+ expect(queue.peek("desktop", "viewer_1", "/c/me/channel_1")).toBeNull()expect(values.size).toBe(0)values.set("alook:native-system-notification:pending-dismissal", JSON.stringify({@@ -50,7 +50,7 @@ describe("native notification dismissal handoff", () => {pathname: "/c/me/channel_1",expiresAt: 1_000,}))- expect(queue.peek("desktop", "/c/me/channel_1")).toBeNull()+ expect(queue.peek("desktop", "viewer_1", "/c/me/channel_1")).toBeNull()expect(values.size).toBe(0)})@@ -60,8 +60,8 @@ describe("native notification dismissal handoff", () => {setItem: () => { throw new Error("blocked") },removeItem: vi.fn(),}))- expect(queue.queue("mobile", notificationId, "/c/me/channel_1")).toBe(false)- expect(queue.peek("mobile", "/c/me/channel_1")).toBeNull()+ expect(queue.queue("mobile", "viewer_1", notificationId, "/c/me/channel_1")).toBe(false)+ expect(queue.peek("mobile", "viewer_1", "/c/me/channel_1")).toBeNull()})it("drops an invalid handoff even when storage removal is blocked", () => {@@ -71,85 +71,52 @@ describe("native notification dismissal handoff", () => {const removeItem = vi.fn(() => { throw new Error("blocked") })const queue = createNativeSystemNotificationDismissalQueue(deps(values, { removeItem }))- expect(queue.peek("mobile", "/c/me/channel_1")).toBeNull()+ expect(queue.peek("mobile", "viewer_1", "/c/me/channel_1")).toBeNull()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", () => {+describe("native notification conversation dismissal revisions", () => {+ const target = { kind: "server" as const, serverId: "server_1", channelId: "channel_1" }+ const key = "alook:native-system-notification:conversation-dismissals"+ it("keeps a newer demand when an older dismissal completes, including remove/recreate ABA", () => {const values = new Map<string, string>()+ const queue = createNativeSystemNotificationConversationDismissalQueue(deps(values))+ queue.queue("desktop", "viewer_1", target)+ const first = queue.pending("desktop", "viewer_1")[0]!+ queue.queue("desktop", "viewer_1", target)+ const second = queue.pending("desktop", "viewer_1")[0]!+ expect(second.revision).not.toBe(first.revision)+ expect(queue.complete("desktop", "viewer_1", target, first.revision)).toBe(false)+ expect(queue.complete("desktop", "viewer_2", target, second.revision)).toBe(false)+ expect(queue.complete("mobile", "viewer_1", target, second.revision)).toBe(false)+ expect(queue.complete("desktop", "viewer_1", target, second.revision)).toBe(true)+ queue.queue("desktop", "viewer_1", target)+ expect(queue.complete("desktop", "viewer_1", target, second.revision)).toBe(false)+ expect(queue.pending("desktop", "viewer_1")).toHaveLength(1)+ })+ it("migrates a legacy demand once in the same key and survives recreation", () => {+ const values = new Map([[key, JSON.stringify([{version:1, platform:"mobile", viewerUserId:"viewer_1", target}])]])const first = createNativeSystemNotificationConversationDismissalQueue(deps(values))- expect(first.queue("desktop", "viewer_1", serverTarget)).toBe(true)- expect(first.queue("desktop", "viewer_1", otherTarget)).toBe(true)-+ const demand = first.pending("mobile", "viewer_1")[0]!+ expect(JSON.parse(values.get(key)!)[0].version).toBe(2)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])+ expect(restored.pending("mobile", "viewer_1")).toEqual([demand])+ expect(restored.pending("desktop", "viewer_1")).toEqual([])+ expect(restored.complete("mobile", "viewer_1", target, demand.revision)).toBe(true)+ expect(values.size).toBe(0)})-- it("round-trips an exact DM target", () => {+ it("bounds scopes and rejects corrupt storage, unsafe identities, and failed writes", () => {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)+ for (let i=0; i<65; i++) queue.queue("desktop", "viewer_1", { kind:"dm", channelId:`dm_${i}` })+ expect(queue.pending("desktop", "viewer_1")).toHaveLength(64)+ expect(queue.pending("desktop", "viewer_1")[0]!.target.channelId).toBe("dm_1")+ expect(queue.queue("desktop", "../viewer", target)).toBe(false)+ values.set(key, "broken")+ expect(queue.pending("desktop", "viewer_1")).toEqual([])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)+ const blocked = createNativeSystemNotificationConversationDismissalQueue(deps(values,{setItem:()=>{throw new Error("blocked")}}))+ expect(blocked.queue("mobile", "viewer_1", target)).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 7344163ef..14f76ff75 100644--- a/src/web/src/lib/community/native-system-notification-dismissal.ts+++ b/src/web/src/lib/community/native-system-notification-dismissal.ts@@ -5,8 +5,9 @@ export type NativeSystemNotificationConversation =| { kind: "dm"; channelId: string }type PendingDismissal = {- version: 1+ version: 2platform: NativeSystemNotificationPlatform+ viewerUserId: stringnotificationId: stringpathname: stringexpiresAt: number@@ -20,18 +21,19 @@ export type NativeSystemNotificationDismissalDeps = {}const KEY = "alook:native-system-notification:pending-dismissal"-const VERSION = 1+const VERSION = 2const TTL_MS = 2 * 60 * 1000const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iconst 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 ROUTE = new RegExp(`^/c/(?:me/${SAFE_ID}|channels/${SAFE_ID}/${SAFE_ID}|messages/${SAFE_ID})$`)+const FIELDS = new Set(["version", "platform", "viewerUserId", "notificationId", "pathname", "expiresAt"])const CONVERSATION_KEY = "alook:native-system-notification:conversation-dismissals"-const CONVERSATION_VERSION = 1 as const+const CONVERSATION_VERSION = 2 as constconst MAX_CONVERSATION_DISMISSALS = 64type PendingConversationDismissal = {- version: 1+ version: 2+ revision: stringplatform: NativeSystemNotificationPlatformviewerUserId: stringtarget: NativeSystemNotificationConversation@@ -63,12 +65,14 @@ function sameConversation(}export function createNativeSystemNotificationConversationDismissalQueue(- deps: Pick<NativeSystemNotificationDismissalDeps, "getItem" | "setItem" | "removeItem">,+ deps: Pick<NativeSystemNotificationDismissalDeps, "getItem" | "setItem" | "removeItem"> & { revision?: () => string },) {function remove() {try { deps.removeItem(CONVERSATION_KEY) } catch {}}+ const revision = deps.revision ?? (() => crypto.randomUUID())+function read(): PendingConversationDismissal[] {let raw: string | nulltry { raw = deps.getItem(CONVERSATION_KEY) } catch { return [] }@@ -79,14 +83,18 @@ export function createNativeSystemNotificationConversationDismissalQueue(const valid = values.every((value) => {if (!value || typeof value !== "object" || Array.isArray(value)) return falseconst entry = value as Record<string, unknown>- return Object.keys(entry).length === 4- && entry.version === CONVERSATION_VERSION+ return ((Object.keys(entry).length === 4 && entry.version === 1)+ || (Object.keys(entry).length === 5 && entry.version === CONVERSATION_VERSION+ && typeof entry.revision === "string" && UUID.test(entry.revision)))&& (entry.platform === "desktop" || entry.platform === "mobile")&& validSafeId(entry.viewerUserId)&& validConversation(entry.target)})if (!valid) throw new Error()- return values as PendingConversationDismissal[]+ const migrated = values.map((value) => value.version === 1+ ? { ...value, version: CONVERSATION_VERSION, revision: revision() } : value) as PendingConversationDismissal[]+ if (values.some((value) => value.version === 1) && !write(migrated)) return []+ return migrated} catch {remove()return []@@ -111,27 +119,27 @@ export function createNativeSystemNotificationConversationDismissalQueue() {if (!validSafeId(viewerUserId) || !validConversation(target)) return falseconst 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 }]+ return write([...values.filter((entry) => !(entry.platform === platform+ && entry.viewerUserId === viewerUserId && sameConversation(entry.target, target))),+ { version: CONVERSATION_VERSION, platform, viewerUserId, target, revision: revision() }].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)+ .map((entry) => ({ target: entry.target, revision: entry.revision }))},complete(platform: NativeSystemNotificationPlatform,viewerUserId: string,target: NativeSystemNotificationConversation,+ revision: string,) {const values = read()const next = values.filter((entry) => !(entry.platform === platform&& entry.viewerUserId === viewerUserId- && sameConversation(entry.target, target)))+ && sameConversation(entry.target, target) && entry.revision === revision))return next.length !== values.length && write(next)},}@@ -161,6 +169,7 @@ export function createNativeSystemNotificationDismissalQueue(if (value.version !== VERSION|| (value.platform !== "desktop" && value.platform !== "mobile")+ || !validSafeId(value.viewerUserId)|| typeof value.notificationId !== "string"|| !UUID.test(value.notificationId)|| typeof value.pathname !== "string"@@ -183,13 +192,15 @@ export function createNativeSystemNotificationDismissalQueue(return {queue(platform: NativeSystemNotificationPlatform,+ viewerUserId: string,notificationId: string,pathname: string,) {- if (!UUID.test(notificationId) || !ROUTE.test(pathname)) return false+ if (!validSafeId(viewerUserId) || !UUID.test(notificationId) || !ROUTE.test(pathname)) return falseconst value: PendingDismissal = {version: VERSION,platform,+ viewerUserId,notificationId,pathname,expiresAt: deps.now() + TTL_MS,@@ -201,13 +212,14 @@ export function createNativeSystemNotificationDismissalQueue(return false}},- peek(platform: NativeSystemNotificationPlatform, pathname: string) {+ peek(platform: NativeSystemNotificationPlatform, viewerUserId: string, pathname: string) {const value = read()- if (!value || value.platform !== platform || value.pathname !== pathname) return null+ if (!value || value.platform !== platform || value.viewerUserId !== viewerUserId || value.pathname !== pathname) return nullreturn value.notificationId},complete(platform: NativeSystemNotificationPlatform,+ viewerUserId: string,pathname: string,notificationId: string,) {@@ -215,6 +227,7 @@ export function createNativeSystemNotificationDismissalQueue(if (!value|| value.platform !== platform+ || value.viewerUserId !== viewerUserId|| value.pathname !== pathname|| value.notificationId !== notificationId) return falsediff --git a/src/web/src/lib/community/system-notification-route.test.ts b/src/web/src/lib/community/system-notification-route.test.tsindex b98345a7a..fa885cf50 100644--- a/src/web/src/lib/community/system-notification-route.test.ts+++ b/src/web/src/lib/community/system-notification-route.test.ts@@ -1,7 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest"import {parseDesktopSystemNotificationActivation,- revalidateDesktopSystemNotificationTarget,systemNotificationHref,type DesktopSystemNotificationActivation,} from "./system-notification-route"@@ -68,56 +67,4 @@ describe("desktop system notification routes", () => {})).toBe("/c/me/dm_1")})- it("revalidates the exact message through the authenticated API", async () => {- const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ id: "message_3" }), {- status: 200,- headers: { "content-type": "application/json" },- }))- await expect(revalidateDesktopSystemNotificationTarget(- activation.target,- fetchImpl,- )).resolves.toBe("allowed")- expect(fetchImpl).toHaveBeenCalledWith("/api/community/messages/message_3", {- method: "GET",- credentials: "same-origin",- cache: "no-store",- })- })-- it("uses the global fetch implementation by default", async () => {- const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ id: "message_3" }), {- status: 200,- headers: { "content-type": "application/json" },- }))- vi.stubGlobal("fetch", fetchImpl)-- await expect(revalidateDesktopSystemNotificationTarget(activation.target)).resolves.toBe("allowed")- expect(fetchImpl).toHaveBeenCalledOnce()- })-- it("classifies deleted and revoked targets as permanently invalid", async () => {- for (const response of [- new Response(null, { status: 404 }),- new Response(null, { status: 403 }),- ]) {- await expect(revalidateDesktopSystemNotificationTarget(- activation.target,- vi.fn(async () => response),- )).resolves.toBe("invalid")- }- })-- it("classifies network, server, malformed, and mismatched responses as retryable", async () => {- for (const fetchImpl of [- vi.fn(async () => { throw new Error("offline") }),- vi.fn(async () => new Response(null, { status: 503 })),- vi.fn(async () => new Response("nope", { status: 200 })),- vi.fn(async () => new Response(JSON.stringify({ id: "other" }), { status: 200 })),- ]) {- await expect(revalidateDesktopSystemNotificationTarget(- activation.target,- fetchImpl,- )).resolves.toBe("retryable")- }- })})diff --git a/src/web/src/lib/community/system-notification-route.ts b/src/web/src/lib/community/system-notification-route.tsindex d8d2ae544..71e6d53c3 100644--- a/src/web/src/lib/community/system-notification-route.ts+++ b/src/web/src/lib/community/system-notification-route.ts@@ -18,11 +18,6 @@ export type DesktopSystemNotificationActivation = {target: DesktopSystemNotificationTarget}-export type DesktopSystemNotificationTargetValidation =- | "allowed"- | "invalid"- | "retryable"-export type SystemNotificationRouteTarget =| { kind: "server"; serverId: string; channelId: string }| { kind: "dm"; channelId: string }@@ -94,28 +89,3 @@ export function systemNotificationHref(target: SystemNotificationRouteTarget): s}return `/c/channels/${encodeURIComponent(target.serverId)}/${encodeURIComponent(target.channelId)}`}--export async function revalidateDesktopSystemNotificationTarget(- target: DesktopSystemNotificationTarget,- fetchImpl: typeof fetch = fetch,- options: { signal?: AbortSignal; assertActive?: () => void } = {},-): Promise<DesktopSystemNotificationTargetValidation> {- try {- options.assertActive?.()- const response = await fetchImpl(`/api/community/messages/${encodeURIComponent(target.messageId)}`, {- method: "GET",- credentials: "same-origin",- cache: "no-store",- signal: options.signal,- })- options.assertActive?.()- if (response.status === 403 || response.status === 404) return "invalid"- if (!response.ok) return "retryable"- const payload: unknown = await response.json()- options.assertActive?.()- return isObject(payload) && payload.id === target.messageId ? "allowed" : "retryable"- } catch {- options.assertActive?.()- return "retryable"- }-}diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 5c1f574b8..ea7bf99e6 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -17,6 +17,8 @@ export const tid = {initialRailPending: "community-initial-rail-pending",initialUserBarPending: "community-initial-user-bar-pending",pendingMain: (kind: string) => `community-pending-main-${kind}`,+ conversationResolutionPending: "community-conversation-resolution-pending",+ messageRouteAlert: (messageId: string) => `community-message-route-alert-${messageId}`,serverAdd: "community-server-add",serverRailScroll: "community-server-rail-scroll",serverRailFolder: (id: string) => `community-server-folder-${id}`,diff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.tsindex d08adb988..c727374a3 100644--- a/src/web/src/lib/observability/coverage.test.ts+++ b/src/web/src/lib/observability/coverage.test.ts@@ -2,11 +2,14 @@ import { readFileSync, readdirSync } from "node:fs"import { resolve, relative } from "node:path"import ts from "typescript"import { expect, it } from "vitest"-import { actionNames, pageRoutes } from "./coverage"+import { actionNames, pageRoutes, routeTemplate } from "./coverage"import { actionVariants } from "./actions"const web = resolve(import.meta.dirname, "../../..")const files = (root: string) => readdirSync(root, { recursive: true }).filter((file): file is string => typeof file === "string" && /\.tsx?$/.test(file)).map(file => resolve(root, file))+it("normalizes the ordinary message route without retaining a message ID or query", () => {+ expect(routeTemplate("/c/messages/private_message_188?seq=123")).toBe("/c/messages/[messageId]")+})it("keeps the route whitelist aligned with both builds and parallel route slots", () => {const routes = new Set(["src/app", "blog/src/app"].flatMap(root => files(resolve(web, root)).filter(file => file.endsWith("/page.tsx")).map(file => "/" + relative(resolve(web, root), file).split("/").slice(0, -1).filter(segment => !segment.startsWith("(") && !segment.startsWith("@")).join("/"))))expect([...routes].sort()).toEqual([...pageRoutes].sort())diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.tsindex fa095df6a..239323d30 100644--- a/src/web/src/lib/observability/coverage.ts+++ b/src/web/src/lib/observability/coverage.ts@@ -12,6 +12,7 @@ export const pageRoutes = ["/c/me/bots","/c/me/friends","/c/me/machines",+ "/c/messages/[messageId]","/c/onboarding-preview","/contact","/device",diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.tsindex 00c28c632..96a108c63 100644--- a/src/web/src/lib/query-keys.test.ts+++ b/src/web/src/lib/query-keys.test.ts@@ -221,3 +221,9 @@ describe("communityKeys", () => {expect(head).toBe("community")})})+++it("keeps message URL resolution separate from the canonical message query", () => {+ expect(communityKeys.messageRoute("message_1")).toEqual(["community","message-route","message_1"])+ expect(communityKeys.messageRoute("message_1")).not.toEqual(communityKeys.message("message_1"))+})diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex cfc0e1fa3..e21fb6878 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -113,6 +113,8 @@ export const communityKeys = {[...communityKeys.all, "attention"] as const,// Single hydrated message (opener block, deep-link previews).+ messageRoute: (messageId: string) =>+ [...communityKeys.all, "message-route", messageId] as const,message: (messageId: string) =>[...communityKeys.all, "message", messageId] as const,messageContexts: (_type: "channel" | "dm", channelId: string) =>diff --git a/src/web/src/test/e2e-ui/58-system-notifications.spec.ts b/src/web/src/test/e2e-ui/58-system-notifications.spec.tsindex 3295dfabd..81bcdf3a8 100644--- a/src/web/src/test/e2e-ui/58-system-notifications.spec.ts+++ b/src/web/src/test/e2e-ui/58-system-notifications.spec.ts@@ -28,7 +28,10 @@ async function installDesktopNotificationBridge(let pending = initialActivation && sessionStorage.getItem(usedKey) !== "used"? initialActivation: null+ const documentLoads = Number(sessionStorage.getItem("qa-desktop-document-loads") ?? "0") + 1+ sessionStorage.setItem("qa-desktop-document-loads", String(documentLoads))const state = {+ documentLoads,shows: [] as unknown[],dismissed,retryActivations: [] as unknown[],@@ -114,12 +117,6 @@ async function retriedNotifications(page: Page) {).__desktopNotificationTest.retryActivations)}-async function clickDesktopNotification(page: Page) {- await page.evaluate(() => (- window as typeof window & { __desktopNotificationTest: { click: () => void } }- ).__desktopNotificationTest.click())-}-test.describe.serial("desktop system notifications", () => {test("a delivered message+bump bundle invokes the native command with the exact target", async ({ asUser }) => {const stamp = Date.now()@@ -150,7 +147,7 @@ test.describe.serial("desktop system notifications", () => {])})- test("a cold activation revalidates access and opens the exact message", async ({ asUser }) => {+ test("a cold activation starts ordinary conversation navigation without a document reload", async ({ asUser }) => {test.setTimeout(90_000)const stamp = Date.now()const serverId = await seedServer("alice", `notification-cold-${stamp}`)@@ -169,56 +166,51 @@ test.describe.serial("desktop system notifications", () => {"4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",])await expect(bob.page.getByTestId(tid.message(messageId))).toBeVisible({ timeout: 30_000 })+ expect(await bob.page.evaluate(() => (window as typeof window & { __desktopNotificationTest: {documentLoads:number} }).__desktopNotificationTest.documentLoads)).toBe(1)})- test("a deleted or inaccessible activation falls back to Inbox", async ({ asUser }) => {- const bob = await asUser("bob")- await installDesktopNotificationBridge(bob.page, {- notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71f",- target: {- kind: "server",- serverId: "missing_server",- channelId: "missing_channel",- messageId: "missing_message",- seq: 1,- },- })- await gotoAfterUserWsAuth(bob.page, "/c/me/friends")- await expect(bob.page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "true")- expect(await dismissedNotifications(bob.page)).toEqual([])- })-- test("a transient validation failure re-arms the exact notification for a later click", async ({ asUser }) => {- test.setTimeout(90_000)+ test("activation starts its target checkpoint before a slow permission response", async ({ asUser }) => {const stamp = Date.now()- const serverId = await seedServer("alice", `notification-retry-${stamp}`)- const channelId = await seedChannel("alice", serverId, `notification-retry-${stamp}`)+ const serverId = await seedServer("alice", `notification-delayed-${stamp}`)+ const channelId = await seedChannel("alice", serverId, `notification-delayed-${stamp}`)await seedJoinServer("alice", "bob", serverId)- const messageId = await seedMessage("alice", channelId, `Retry activation ${stamp}`)- const notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f720"+ const messageId = await seedMessage("alice", channelId, `Delayed activation ${stamp}`)const bob = await asUser("bob")- let attempts = 0- await bob.page.route(`**/api/community/messages/${messageId}`, async (route) => {- attempts += 1- if (attempts === 1) {- await route.fulfill({ status: 503, body: "temporarily unavailable" })- return- }+ await installDesktopNotificationBridge(bob.page)+ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")+ let release!: () => void+ const pending = new Promise<void>((resolve) => { release = resolve })+ let permissionHeld = false+ await bob.page.route(`**/api/community/channels/${channelId}`, async route => {+ permissionHeld = true+ await pending+ permissionHeld = falseawait route.continue()})- await installDesktopNotificationBridge(bob.page, {- notificationId,- target: { kind: "server", serverId, channelId, messageId, seq: 1 },- })-- await gotoAfterUserWsAuth(bob.page, "/c/me/friends")- await expect(bob.page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "true")- await expect.poll(() => retriedNotifications(bob.page)).toEqual([notificationId])- expect(await dismissedNotifications(bob.page)).toEqual([])-- await clickDesktopNotification(bob.page)- await expect(bob.page).toHaveURL(new RegExp(`/c/channels/${serverId}/${channelId}`))- await expect.poll(() => dismissedNotifications(bob.page)).toEqual([notificationId])- expect(attempts).toBe(2)+ const targetHref = `/c/channels/${serverId}/${channelId}`+ const targetLoading = bob.page.locator(`[data-community-target-href="${targetHref}"] main[data-testid="${tid.conversationResolutionPending}"]`)+ try {+ await bob.page.evaluate(value => {+ const state = (window as typeof window & {__desktopNotificationTest:{listener?:{onmessage?:(value:unknown)=>void}}}).__desktopNotificationTest+ const core = (window as typeof window & {__TAURI__:{core:{invoke:(command:string,args?:Record<string,unknown>)=>Promise<unknown>}}}).__TAURI__.core+ const original = core.invoke+ let activation: unknown = value+ core.invoke = async (command,args) => command === "desktop_system_notification_take_activation"+ ? (()=>{const next=activation;activation=null;return next})() : original(command,args)+ state.listener?.onmessage?.(undefined)+ }, {notificationId:"4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f720",target:{kind:"server",serverId,channelId,messageId,seq:1}})+ await expect.poll(() => permissionHeld).toBe(true)+ await expect(targetLoading).toHaveCount(1)+ await expect(targetLoading).toBeVisible()+ await expect(targetLoading).toHaveAttribute("aria-busy", "true")+ await expect(bob.page).toHaveURL(new RegExp(`/c/channels/${serverId}/${channelId}`))+ await expect(targetLoading).toHaveCount(1)+ await expect(targetLoading).toBeVisible()+ await expect(targetLoading).toHaveAttribute("aria-busy", "true")+ expect(permissionHeld).toBe(true)+ expect(await retriedNotifications(bob.page)).toEqual([])+ } finally { release() }+ await expect(bob.page.getByTestId(tid.message(messageId))).toBeVisible({timeout:30_000})+ await expect.poll(()=>dismissedNotifications(bob.page)).toEqual(["4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f720"])})})diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.tsindex 3ddfbbec8..6653b4357 100644--- a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts+++ b/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts@@ -6,13 +6,16 @@ import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"type Activation = { notificationId: string; messageId: string; targetId: string }-type Bridge = { pending: Activation | null; listener: unknown; takes: number; dismissed: string[]; visibility: DocumentVisibilityState }+type Bridge = { pending: Activation | null; listener: unknown; takes: number; dismissed: string[]; visibility: DocumentVisibilityState; documentLoads: number }async function installMobileBridge(page: Page, activation: Activation | null) {await page.addInitScript((initial) => {const key = `qa-mobile-consumed:${initial?.notificationId}`const dismissedKey = "qa-mobile-notification-dismissed"+ const documentLoads = Number(sessionStorage.getItem("qa-mobile-document-loads") ?? "0") + 1+ sessionStorage.setItem("qa-mobile-document-loads", String(documentLoads))const state: Bridge = {+ documentLoads,pending: initial && !sessionStorage.getItem(key) ? initial : null,listener: null,takes: 0,@@ -59,7 +62,7 @@ async function resumeActivation(page: Page, activation: Activation) {type MessageDoorEvidence = {status: number- payload: { surfaceReceipt?: unknown; messages?: unknown }+ payload: { id?: string; channelId?: string }}async function captureMessageDoor(page: Page, targetId: string, messageId: string) {@@ -69,12 +72,12 @@ async function captureMessageDoor(page: Page, targetId: string, messageId: strincapture = resolvefail = reject})- await page.route((url) => url.pathname === `/api/community/channels/${targetId}/messages`- && url.searchParams.get("anchor") === messageId && url.searchParams.get("limit") === "1", async (route) => {+ await page.route((url) => url.pathname === `/api/community/messages/${messageId}`, async (route) => {try {const response = await route.fetch()const payload = await response.json()const evidence = { status: response.status(), payload }+ if (response.ok()) expect(payload.channelId).toBe(targetId)await route.fulfill({ response })capture(evidence)} catch (error) {@@ -130,24 +133,25 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =if (mode === "resume") await resumeActivation(page, activation)const { status, payload } = await door.resultexpect(status).toBe(200)- expect(payload.surfaceReceipt).toEqual({ channelId: targetId, surfaceKind: surface })- expect(payload.messages).toEqual(expect.arrayContaining([expect.objectContaining({ id: messageId })]))+ expect(payload.id).toBe(messageId)+ expect(payload.channelId).toBe(targetId)const path = surface === "dm" ? `/c/me/${targetId}` : `/c/channels/${serverId}/${targetId}`await expect(page).toHaveURL(`${WEB_URL}${path}`)await expect.poll(() => page.evaluate(() => (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])+ expect(await page.evaluate(() => (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa.documentLoads)).toBe(1)await expect(composerEditable(page)).toBeVisible({ timeout: 30_000 })await expect(page.getByTestId(tid.message(messageId))).toBeVisible()await expect(page.locator('[data-slot="sheet-content"]')).toHaveCount(0)- await testInfo.attach("message-door-evidence", { body: JSON.stringify({ simulation: "iPhone UA + Tauri command shim + browser visibility events", status, surfaceReceipt: payload.surfaceReceipt, messageId, url: page.url() }), contentType: "application/json" })+ await testInfo.attach("message-door-evidence", { body: JSON.stringify({ simulation: "iPhone UA + Tauri command shim + browser visibility events", status, channelId: payload.channelId, messageId, url: page.url() }), contentType: "application/json" })await testInfo.attach("chat", { body: await page.screenshot(), contentType: "image/png" })})}}for (const kind of ["deleted", "revoked"] as const) {- test(`${kind} target opens Inbox without unauthorized navigation`, async ({ asUser }, testInfo) => {+ test(`${kind} target shows an unavailable message page with the normal Inbox action`, async ({ asUser }, testInfo) => {const categoryId = kind === "revoked" ? await seedCategory("alice", serverId, `private-${Date.now()}`, { private: true }) : undefinedconst targetId = await seedChannel("alice", serverId, `${kind}-${Date.now()}`, "text", categoryId)if (kind === "revoked") await seedChannelMember("alice", targetId, userId("bob"))@@ -159,15 +163,35 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =const route = `/c/channels/${serverId}`await page.goto(route)await expect(page.getByTestId(tid.inboxTrigger)).toBeVisible({ timeout: 30_000 })- await resumeActivation(page, { notificationId: crypto.randomUUID(), targetId, messageId })+ const activation = { notificationId: crypto.randomUUID(), targetId, messageId }+ await resumeActivation(page, activation)const { status } = await door.resultexpect([403, 404]).toContain(status)+ await expect(page).toHaveURL(`${WEB_URL}/c/messages/${messageId}`)+ const unavailableAlert = page.getByTestId(tid.messageRouteAlert(messageId))+ await expect(unavailableAlert).toHaveCount(1)+ await expect(unavailableAlert).toBeVisible()+ await expect(unavailableAlert).toHaveText("This conversation is unavailable.")+ await page.getByRole("button", { name: "Open Inbox", exact: true }).click()+ await expect(page).toHaveURL(`${WEB_URL}/c/me`)+ await expect(page.getByTestId(tid.inboxTrigger)).toBeVisible()await expect(page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "true")- await expect(page).toHaveURL(`${WEB_URL}${route}`)- expect(await page.evaluate(() => (+ const inbox = page.getByTestId(tid.userBarExtension)+ await expect(inbox).toHaveCount(1)+ await expect(inbox).toBeVisible()+ await expect(inbox.locator("xpath=ancestor::*[@inert or @aria-hidden='true']")).toHaveCount(0)+ await expect.poll(() => page.evaluate(() => (window as typeof window & { __mobileNotificationQa: Bridge }- ).__mobileNotificationQa.dismissed)).toEqual([])- await testInfo.attach("fallback-evidence", { body: JSON.stringify({ kind, status, url: page.url() }), contentType: "application/json" })+ ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])+ const inboxHref = page.url()+ await page.getByRole("link", { name: /^Friends(?:, \d+ new requests)?$/ }).click()+ await expect(page).toHaveURL(`${WEB_URL}/c/me/friends`)+ await expect(page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "false")+ await expect(page.getByTestId(tid.userBarExtension)).toHaveCount(0)+ await expect.poll(() => page.evaluate(() => (+ window as typeof window & { __mobileNotificationQa: Bridge }+ ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])+ await testInfo.attach("fallback-evidence", { body: JSON.stringify({ kind, status, inboxHref, url: page.url() }), contentType: "application/json" })})}