Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): simplify mobile notifications and use cached navigation (#1043)

Gener8e941e9f1ee5
diff --git a/scripts/ci/mobile-system-notification.test.ts b/scripts/ci/mobile-system-notification.test.ts
index ec32f7eee..2167029fb 100644
--- a/scripts/ci/mobile-system-notification.test.ts
+++ b/scripts/ci/mobile-system-notification.test.ts
@@ -160,11 +160,12 @@ describe("mobile system notification contract", () => {
expect(androidRoute).toContain("mobilePushNotificationTagMatchesConversation")
expect(androidPlugin).toContain("manager.activeNotifications")
expect(androidPlugin).toContain(
- "mobilePushNotificationTagMatchesNotification(notification.tag, args.notificationId)",
+ "mobilePushNotificationTagMatchesNotification(tag, args.notificationId)",
)
expect(androidPlugin).toContain("fun dismissConversation")
expect(androidPlugin).toContain("mobilePushNotificationTagMatchesConversation(")
expect(androidPlugin).toContain("manager.cancel(it.tag, it.id)")
+ expect(androidPlugin).toContain("manager.activeNotifications.any { matches(it.tag) }")
})
it("locks iOS APNs callbacks, foreground/tap handling, and production entitlement", () => {
diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt
index 1abc903da..eade6543b 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt
+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt
@@ -174,22 +174,8 @@ class MobilePushPlugin(private val activity: Activity) : Plugin(activity) {
invoke.reject("Notification dismissal is invalid", "invalid_request")
return
}
- val manager = activity.getSystemService(NotificationManager::class.java)
- if (manager == null) {
- invoke.reject("Notification manager is unavailable", "notification_unavailable")
- return
- }
- val matches = manager.activeNotifications.filter { notification ->
- mobilePushNotificationTagMatchesNotification(notification.tag, args.notificationId)
- }
- matches.forEach { manager.cancel(it.tag, it.id) }
- val remains = manager.activeNotifications.any { notification ->
- mobilePushNotificationTagMatchesNotification(notification.tag, args.notificationId)
- }
- if (remains) {
- invoke.reject("Notification remains delivered", "notification_unavailable")
- } else {
- invoke.resolve()
+ dismissMatchingNotifications(invoke, "Notification remains delivered") { tag ->
+ mobilePushNotificationTagMatchesNotification(tag, args.notificationId)
}
}
@@ -207,28 +193,25 @@ class MobilePushPlugin(private val activity: Activity) : Plugin(activity) {
invoke.reject("Conversation dismissal is invalid", "invalid_request")
return
}
+ dismissMatchingNotifications(invoke, "Conversation notifications remain delivered") { tag ->
+ mobilePushNotificationTagMatchesConversation(tag, args.viewerUserId, args.targetId)
+ }
+ }
+
+ private fun dismissMatchingNotifications(
+ invoke: Invoke,
+ remainsMessage: String,
+ matches: (String?) -> Boolean,
+ ) {
val manager = activity.getSystemService(NotificationManager::class.java)
if (manager == null) {
invoke.reject("Notification manager is unavailable", "notification_unavailable")
return
}
- manager.activeNotifications
- .filter {
- mobilePushNotificationTagMatchesConversation(
- it.tag,
- args.viewerUserId,
- args.targetId,
- )
- }
+ manager.activeNotifications.filter { matches(it.tag) }
.forEach { manager.cancel(it.tag, it.id) }
- if (manager.activeNotifications.any {
- mobilePushNotificationTagMatchesConversation(
- it.tag,
- args.viewerUserId,
- args.targetId,
- )
- }) {
- invoke.reject("Conversation notifications remain delivered", "notification_unavailable")
+ if (manager.activeNotifications.any { matches(it.tag) }) {
+ invoke.reject(remainsMessage, "notification_unavailable")
} else {
invoke.resolve()
}
diff --git a/src/desktop/src-tauri/plugins/mobile-push/ios/Sources/MobilePushPlugin.swift b/src/desktop/src-tauri/plugins/mobile-push/ios/Sources/MobilePushPlugin.swift
index 70e1f86f2..a22b7190b 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
@@ -119,9 +119,11 @@ struct MobilePushRegistrationState: Equatable {
final class MobilePushStore {
private let defaults: UserDefaults
private let lock = NSLock()
+ private var currentToken: String?
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
+ defaults.removeObject(forKey: Keys.currentToken)
}
func installationId() -> String {
@@ -147,7 +149,7 @@ final class MobilePushStore {
let current = unlockedRegistration()
let next = current.withCurrentToken(token)
guard next != current else { return false }
- defaults.set(next.currentToken, forKey: Keys.currentToken)
+ currentToken = next.currentToken
return true
}
@@ -212,7 +214,7 @@ final class MobilePushStore {
private func unlockedRegistration() -> MobilePushRegistrationState {
MobilePushRegistrationState(
- currentToken: defaults.string(forKey: Keys.currentToken),
+ currentToken: currentToken,
acknowledgedToken: defaults.string(forKey: Keys.acknowledgedToken)
)
}
diff --git a/src/desktop/src-tauri/plugins/mobile-push/ios/Tests/MobilePushPluginTests/MobilePushPluginTests.swift b/src/desktop/src-tauri/plugins/mobile-push/ios/Tests/MobilePushPluginTests/MobilePushPluginTests.swift
index fc8c01925..cb6ed98af 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
@@ -196,4 +196,37 @@ final class MobilePushPluginTests: XCTestCase {
store.completeDeliveredNotificationIdentifier(for: route.notificationId)
XCTAssertNil(store.deliveredNotificationIdentifier(for: route.notificationId))
}
+
+ func testRelaunchRequiresASystemTokenAndRetainsInstallationAndOwnershipProof() {
+ let suite = "mobile-push-tests-\(UUID().uuidString)"
+ let defaults = UserDefaults(suiteName: suite)!
+ defer { defaults.removePersistentDomain(forName: suite) }
+ let old = "token-00000000000"
+ let current = "token-11111111111"
+ let newer = "token-22222222222"
+ defaults.set(old, forKey: "alook.mobilePush.currentToken")
+ defaults.set(old, forKey: "alook.mobilePush.acknowledgedToken")
+ let store = MobilePushStore(defaults: defaults)
+ let installation = store.installationId()
+ XCTAssertNil(store.registration().currentToken)
+ XCTAssertNil(defaults.string(forKey: "alook.mobilePush.currentToken"))
+ XCTAssertEqual(store.registration().acknowledgedToken, old)
+
+ XCTAssertTrue(store.updateCurrentToken(current))
+ XCTAssertFalse(store.updateCurrentToken(current))
+ XCTAssertEqual(store.registration().currentToken, current)
+ XCTAssertEqual(store.registration().previousToken, old)
+ XCTAssertTrue(store.updateCurrentToken(newer))
+ XCTAssertTrue(store.acknowledge(current))
+ XCTAssertEqual(store.registration().currentToken, newer)
+ XCTAssertEqual(store.registration().previousToken, current)
+
+ let relaunched = MobilePushStore(defaults: defaults)
+ XCTAssertEqual(relaunched.installationId(), installation)
+ XCTAssertNil(relaunched.registration().currentToken)
+ XCTAssertEqual(relaunched.registration().acknowledgedToken, current)
+ XCTAssertTrue(relaunched.updateCurrentToken(newer))
+ XCTAssertEqual(relaunched.registration().currentToken, newer)
+ XCTAssertEqual(relaunched.registration().previousToken, current)
+ }
}
diff --git a/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts b/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts
index 81b700202..eaab98679 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
@@ -11,6 +11,8 @@ import {
} from "./use-native-system-notifications"
import type { DesktopSystemNotificationActivation } from "@/lib/community/system-notification-route"
import { createNativeSystemNotificationDismissalQueue } from "@/lib/community/native-system-notification-dismissal"
+import { conversationEntryFixture, dmConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"
+import { writeCommunityCollectionRows } from "@/lib/community-db/write"
const hookMocks = vi.hoisted(() => ({
@@ -206,6 +208,50 @@ describe("notification activation",()=>{
expect(window.sessionStorage.length).toBe(0)
expect(hookMocks.mobileDismiss).not.toHaveBeenCalled()
})
+ it.each(["dm", "channel"] as const)("navigates a cached mobile %s directly and clears only after route commit", async kind => {
+ hookMocks.desktop = false
+ hookMocks.mobile = true
+ setRoute("/c/me/friends")
+ const owner = await createCommunityQueryOwner()
+ await seedConversationEntry(owner.client, kind === "dm" ? dmConversationEntryFixture() : conversationEntryFixture())
+ const clicked = { notificationId: activation.notificationId, messageId: "m1", targetId: "c1" }
+ hookMocks.mobileTake.mockResolvedValueOnce(clicked)
+ const wrapped = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider,
+ { client: owner.client, registry: owner.registry, retainOwner: true }, createElement(wrapper, null, children))
+ const rendered = renderOwnedHook(useNotifications, { wrapper: wrapped })
+ const href = kind === "dm" ? "/c/me/c1" : "/c/channels/s1/c1"
+ await waitFor(() => expect(route.navigation.pushImmediate).toHaveBeenCalledExactlyOnceWith(href))
+ expect(hookMocks.mobileRevalidate).not.toHaveBeenCalled()
+ expect(hookMocks.mobileDismiss).not.toHaveBeenCalled()
+ setRoute(href)
+ rendered.rerender()
+ await waitFor(() => expect(hookMocks.mobileDismiss).toHaveBeenCalledExactlyOnceWith(clicked.notificationId))
+ rendered.unmount()
+ })
+ it.each(["dm with server", "server without server"] as const)("resolves a cached %s through the ordinary message page", async combination => {
+ hookMocks.desktop = false
+ hookMocks.mobile = true
+ setRoute("/c/me/friends")
+ const owner = await createCommunityQueryOwner()
+ await seedConversationEntry(owner.client, combination === "dm with server" ? dmConversationEntryFixture() : conversationEntryFixture())
+ const channel = owner.registry.collections.channels.get("c1")!
+ await writeCommunityCollectionRows(owner.registry, "channels", [{ ...channel, serverId: combination === "dm with server" ? "s1" : null }], row => row.id)
+ const clicked = { notificationId: activation.notificationId, messageId: "m1", targetId: "c1" }
+ hookMocks.mobileTake.mockResolvedValueOnce(clicked)
+ const fetch = vi.fn(() => new Promise<Response>(() => undefined))
+ vi.stubGlobal("fetch", fetch)
+ const wrapped = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider,
+ { client: owner.client, registry: owner.registry, retainOwner: true }, createElement(wrapper, null, children))
+ const rendered = renderOwnedHook(useNotifications, { wrapper: wrapped })
+ await waitFor(() => expect(route.navigation.pushImmediate).toHaveBeenCalledExactlyOnceWith("/c/messages/m1"))
+ expect(fetch).not.toHaveBeenCalled()
+ expect(hookMocks.mobileRevalidate).not.toHaveBeenCalled()
+ expect(hookMocks.mobileDismiss).not.toHaveBeenCalled()
+ setRoute("/c/messages/m1")
+ rendered.rerender()
+ await waitFor(() => expect(hookMocks.mobileDismiss).toHaveBeenCalledExactlyOnceWith(clicked.notificationId))
+ rendered.unmount()
+ })
})
describe("current native conversation",()=>{
function useCurrent(ready=true) {useNotifications();useNativeSystemNotificationConversationDismissal("viewer",target,ready)}
diff --git a/src/web/src/hooks/community/use-native-system-notifications.ts b/src/web/src/hooks/community/use-native-system-notifications.ts
index f2336f237..b0ea7268f 100644
--- a/src/web/src/hooks/community/use-native-system-notifications.ts
+++ b/src/web/src/hooks/community/use-native-system-notifications.ts
@@ -7,6 +7,7 @@ import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurr
import { useCommunityViewSource } from "./use-community-view-source"
import { isAbortError } from "@/lib/errors"
import { normalizeCommunityHref, type CommunityCommittedFrame } from "@/lib/community/community-route"
+import { cachedConversationNavigationHref } from "@/lib/community/navigation-metadata"
import { useCommunityRouteFrame, type NativeNotificationConversationConsumer, type CommunityNavigationController } from "@/contexts/community/route-frame"
import { isDesktop, isMobile } from "@alook/shared"
import {
@@ -369,12 +370,13 @@ export function useNativeSystemNotifications(
register: (snapshot) => nativeCommand(client, key("mobile", "register"), original, () => postMobileSystemNotificationRegistration(snapshot, fetch, { signal: original.signal, assertActive: original }), true),
acknowledge: (token) => nativeCommand(client, key("mobile", "acknowledge"), original, () => acknowledgeMobileSystemNotificationRegistration(token), true),
unregister: (id) => nativeCommand(client, key("mobile", "unregister", id), original, () => deleteMobileSystemNotificationRegistration(id, fetch, { signal: original.signal, assertActive: original }), true),
- retryDelaysMs: [],
- schedule: (callback, delayMs) => window.setTimeout(callback, delayMs),
- cancel: (handle) => window.clearTimeout(handle as number),
})
const activation = createMobileSystemNotificationActivationController({
take: () => nativeCommand(client, key("mobile", "take"), original, takeMobileSystemNotificationActivation),
+ resolveHref: (activation) => {
+ original()
+ return cachedConversationNavigationHref(client, viewerUserId, activation.targetId)
+ },
queueDismiss: (notificationId, href) => {
original(); dismissal.queue("mobile", viewerUserId, notificationId, href)
},
diff --git a/src/web/src/lib/community/mobile-system-notification.test.ts b/src/web/src/lib/community/mobile-system-notification.test.ts
index f245ea191..ea14a4a48 100644
--- a/src/web/src/lib/community/mobile-system-notification.test.ts
+++ b/src/web/src/lib/community/mobile-system-notification.test.ts
@@ -77,8 +77,6 @@ function registrationDeps(
register: vi.fn(async () => undefined),
acknowledge: vi.fn(async () => undefined),
unregister: vi.fn(async () => undefined),
- schedule: vi.fn(() => 1),
- cancel: vi.fn(),
...overrides,
}
}
@@ -381,7 +379,6 @@ describe("mobile notification registration controller", () => {
})
await createMobileSystemNotificationRegistrationController(tokenless).sync()
expect(tokenless.register).not.toHaveBeenCalled()
- expect(tokenless.schedule).not.toHaveBeenCalled()
})
it("serializes concurrent signals and coalesces them into one rerun", async () => {
@@ -414,7 +411,6 @@ describe("mobile notification registration controller", () => {
let currentToken = token0
let acknowledgedToken: string | undefined
const posted: MobileSystemNotificationRegistration[] = []
- let retry: (() => void) | undefined
const deps = registrationDeps({
snapshot: vi.fn(async () => snapshot({
providerToken: currentToken,
@@ -428,13 +424,12 @@ describe("mobile notification registration controller", () => {
if (token !== currentToken) throw new Error("stale")
acknowledgedToken = token
}),
- schedule: vi.fn((callback) => { retry = callback; return 7 }),
})
const controller = createMobileSystemNotificationRegistrationController(deps)
await controller.sync()
currentToken = token1
await controller.sync()
- expect(retry).toBeTypeOf("function")
+ expect(acknowledgedToken).toBe(token0)
currentToken = token2
await controller.sync()
expect(posted.map(({ providerToken, previousProviderToken }) => ({
@@ -446,27 +441,22 @@ describe("mobile notification registration controller", () => {
{ providerToken: token2, previousProviderToken: token0 },
])
expect(acknowledgedToken).toBe(token2)
- expect(deps.cancel).toHaveBeenCalledWith(7)
})
- it("uses bounded retry delays and cancels a pending retry on disposal", async () => {
- const scheduled: Array<{ callback: () => void; delay: number }> = []
+ it("leaves failed work unacknowledged until the next signal and stays retired after disposal", async () => {
const deps = registrationDeps({
- checkPermission: vi.fn(async () => { throw new Error("offline") }),
- schedule: vi.fn((callback, delay) => {
- scheduled.push({ callback, delay })
- return scheduled.length
- }),
- retryDelaysMs: [10, 20],
+ register: vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValue(undefined),
})
const controller = createMobileSystemNotificationRegistrationController(deps)
await controller.sync(true)
- expect(scheduled.map(({ delay }) => delay)).toEqual([10])
- scheduled.shift()?.callback()
- await vi.waitFor(() => expect(scheduled.map(({ delay }) => delay)).toEqual([20]))
- scheduled.shift()?.callback()
- await vi.waitFor(() => expect(deps.checkPermission).toHaveBeenCalledTimes(3))
- expect(scheduled).toHaveLength(0)
+ expect(deps.register).toHaveBeenCalledOnce()
+ expect(deps.acknowledge).not.toHaveBeenCalled()
+ await controller.sync()
+ expect(deps.register).toHaveBeenCalledTimes(2)
+ expect(deps.acknowledge).toHaveBeenCalledExactlyOnceWith(token0)
+ controller.dispose()
+ await controller.sync()
+ expect(deps.register).toHaveBeenCalledTimes(2)
const disposableDeps = registrationDeps({
checkPermission: vi.fn(async () => { throw new Error("offline") }),
diff --git a/src/web/src/lib/community/mobile-system-notification.ts b/src/web/src/lib/community/mobile-system-notification.ts
index 6807b3d1b..baa081e1e 100644
--- a/src/web/src/lib/community/mobile-system-notification.ts
+++ b/src/web/src/lib/community/mobile-system-notification.ts
@@ -21,7 +21,6 @@ export type MobileSystemNotificationActivation = {
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}$/i
-const RETRY_DELAYS_MS = [1_000, 5_000, 30_000, 60_000] as const
const registrationClient = new QueryClient()
const registrationPolicy = createStore({ suppressed: false })
@@ -269,35 +268,12 @@ export type MobileSystemNotificationRegistrationDeps = {
register: (snapshot: MobileSystemNotificationRegistration) => Promise<void>
acknowledge: (providerToken: string) => Promise<void>
unregister: (installationId: string) => Promise<void>
- schedule: (callback: () => void, delayMs: number) => unknown
- cancel: (handle: unknown) => void
- retryDelaysMs?: readonly number[]
}
export function createMobileSystemNotificationRegistrationController(
deps: MobileSystemNotificationRegistrationDeps,
) {
- const protocol = createStore({ disposed: false, active: null as Promise<void> | null, rerun: false, pendingPrompt: false, retryAttempt: 0, retryTimer: undefined as unknown | undefined });
- function clearRetry() {
- if (protocol.get().retryTimer === undefined)
- return;
- deps.cancel(protocol.get().retryTimer);
- protocol.setState(state => ({ ...state, retryTimer: undefined }));
- }
- function scheduleRetry(allowPrompt: boolean) {
- if (protocol.get().disposed || protocol.get().retryTimer !== undefined)
- return;
- const delays = deps.retryDelaysMs ?? RETRY_DELAYS_MS;
- const delay = delays[protocol.get().retryAttempt];
- if (delay === undefined)
- return;
- protocol.setState(state => ({ ...state, retryAttempt: protocol.get().retryAttempt + 1 }));
- const retryTimer = deps.schedule(() => {
- protocol.setState(state => ({ ...state, retryTimer: undefined }));
- void sync(allowPrompt);
- }, delay);
- protocol.setState(state => ({ ...state, retryTimer }));
- }
+ const protocol = createStore({ disposed: false, active: null as Promise<void> | null, rerun: false, pendingPrompt: false });
async function runOnce(allowPrompt: boolean) {
const assert = () => { if (protocol.get().disposed) throw new DOMException("Retired notification registration", "AbortError") }
assert()
@@ -327,7 +303,6 @@ export function createMobileSystemNotificationRegistrationController(
return Promise.resolve();
protocol.setState(state => ({ ...state, pendingPrompt: protocol.get().pendingPrompt || allowPrompt }));
protocol.setState(state => ({ ...state, rerun: true }));
- clearRetry();
const inFlight = protocol.get().active
if (inFlight) return inFlight
const active = Promise.resolve().then(async () => {
@@ -337,14 +312,12 @@ export function createMobileSystemNotificationRegistrationController(
protocol.setState(state => ({ ...state, pendingPrompt: false }));
try {
await runOnce(promptThisRun);
- protocol.setState(state => ({ ...state, retryAttempt: 0 }));
}
catch {
if (protocol.get().rerun) {
protocol.setState(state => ({ ...state, pendingPrompt: protocol.get().pendingPrompt || promptThisRun }));
continue;
}
- scheduleRetry(promptThisRun);
}
}
}).finally(() => {
@@ -359,13 +332,13 @@ export function createMobileSystemNotificationRegistrationController(
if (protocol.get().disposed)
return;
protocol.setState(state => ({ ...state, disposed: true }));
- clearRetry();
},
};
}
export type MobileSystemNotificationActivationDeps = {
take: () => Promise<MobileSystemNotificationActivation | null>
+ resolveHref?: (activation: MobileSystemNotificationActivation) => string | undefined
queueDismiss: (notificationId: string, href: string) => void
navigate: (href: string) => void
}
@@ -394,7 +367,7 @@ export function createMobileSystemNotificationActivationController(
}
if (!activation || protocol.get().disposed)
continue;
- const href = mobileSystemNotificationHref(activation);
+ const href = deps.resolveHref?.(activation) ?? mobileSystemNotificationHref(activation);
try {
deps.queueDismiss(activation.notificationId, href);
}
diff --git a/src/web/src/lib/community/navigation-metadata.dom.test.tsx b/src/web/src/lib/community/navigation-metadata.dom.test.tsx
index 3120658d0..d5c5772ca 100644
--- a/src/web/src/lib/community/navigation-metadata.dom.test.tsx
+++ b/src/web/src/lib/community/navigation-metadata.dom.test.tsx
@@ -4,14 +4,15 @@ import { QueryClientProvider } from "@tanstack/react-query"
import type { ApiRequestOptions } from "@/lib/api/client"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { dmConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"
+import { conversationEntryFixture, dmConversationEntryFixture, forumConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
import { communityKeys } from "@/lib/query-keys"
import { retireCommunityChannelReading, publishCommunityLiveSnapshot, captureCommunityLiveSnapshotToken, ingestReadStateSnapshot } from "@/lib/community-db/sync"
import { useChannelMetadata } from "@/hooks/community/use-channel-metadata"
import { useDmMessages } from "@/hooks/community/use-messages"
-import { prepareNavigationMetadata } from "@/lib/community/navigation-metadata"
+import { cachedConversationNavigationHref, prepareNavigationMetadata } from "@/lib/community/navigation-metadata"
+import { writeCommunityCollectionRows } from "@/lib/community-db/write"
import { CommunityRouteContext } from "@/contexts/community/route-frame"
const load = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: async (path: string, options?: ApiRequestOptions) => { options?.assertActive?.(); const result = await load(path, options); options?.assertActive?.(); return result } }))
@@ -22,6 +23,48 @@ function deferred<T>() {
return { promise, resolve }
}
describe("native navigation warming and DM consumer mounting", () => {
+ it.each(["dm", "text", "forum", "thread"] as const)("resolves an eligible cached %s with no target lookup", async kind => {
+ const owner = await createCommunityQueryOwner()
+ const entry = kind === "dm" ? dmConversationEntryFixture()
+ : kind === "forum" ? forumConversationEntryFixture() : conversationEntryFixture()
+ if (kind === "thread") {
+ entry.channel = { ...entry.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }
+ entry.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }
+ }
+ await seedConversationEntry(owner.client, entry)
+ expect(cachedConversationNavigationHref(owner.client, "viewer", "c1"))
+ .toBe(kind === "dm" ? "/c/me/c1" : "/c/channels/s1/c1")
+ expect(load).not.toHaveBeenCalled()
+ })
+
+ it.each(["missing", "account", "session", "pending", "archived", "access", "revoked", "retired"] as const)(
+ "declines the cached fast path when %s and leaves ordinary resolution available", async reason => {
+ const owner = await createCommunityQueryOwner()
+ await seedConversationEntry(owner.client, conversationEntryFixture())
+ expect(cachedConversationNavigationHref(owner.client, "viewer", "c1")).toBe("/c/channels/s1/c1")
+ if (reason === "session") owner.registry.bindAuthentication(() => "other", async () => {})
+ if (reason === "pending" || reason === "archived") {
+ const channel = owner.registry.collections.channels.get("c1")!
+ await writeCommunityCollectionRows(owner.registry, "channels", [{ ...channel, [reason]: true }], row => row.id)
+ }
+ if (reason === "access") await writeCommunityCollectionRows(owner.registry, "channelMemberships", [], row => String(row))
+ if (reason === "revoked") owner.runtime.ws.actions.revokeChannelAccess("s1", "c1")
+ if (reason === "retired") retireCommunityAccount(owner.registry)
+ expect(cachedConversationNavigationHref(owner.client, reason === "account" ? "other" : "viewer", reason === "missing" ? "unknown" : "c1"))
+ .toBeUndefined()
+ expect(load).not.toHaveBeenCalled()
+ },
+ )
+
+ it.each(["dm with server", "server without server"] as const)("rejects a cached %s without looking up a target", async combination => {
+ const owner = await createCommunityQueryOwner()
+ await seedConversationEntry(owner.client, combination === "dm with server" ? dmConversationEntryFixture() : conversationEntryFixture())
+ const channel = owner.registry.collections.channels.get("c1")!
+ await writeCommunityCollectionRows(owner.registry, "channels", [{ ...channel, serverId: combination === "dm with server" ? "s1" : null }], row => row.id)
+ expect(cachedConversationNavigationHref(owner.client, "viewer", "c1")).toBeUndefined()
+ expect(load).not.toHaveBeenCalled()
+ })
+
it.each([
[false, "held"], [true, "held"],
[false, "resolved"], [true, "resolved"],
diff --git a/src/web/src/lib/community/navigation-metadata.ts b/src/web/src/lib/community/navigation-metadata.ts
index 342bae2ed..b874cc736 100644
--- a/src/web/src/lib/community/navigation-metadata.ts
+++ b/src/web/src/lib/community/navigation-metadata.ts
@@ -4,8 +4,9 @@ import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { channelMembershipKey } from "@/lib/community-db/schema"
import { resolveCommunityModulePlan } from "./community-route"
import { prefetchForHref, navigationForHref } from "@/lib/observability/context"
+import { systemNotificationHref } from "./system-notification-route"
-export function prepareNavigationMetadata(queryClient: QueryClient, href: string, intent: "prefetch" | "foreground") {
+function cachedNavigationTarget(queryClient: QueryClient, href: string) {
const registry = getCommunityDbRegistry(queryClient)
if (!registry?.accountId || !registry.runtime.lifecycle.get().active) return
const main = resolveCommunityModulePlan(href).main
@@ -17,6 +18,26 @@ export function prepareNavigationMetadata(queryClient: QueryClient, href: string
|| (main.kind === "dm") !== (channel.type === "dm")
|| !registry.collections.channelMemberships.has(channelMembershipKey(channelId, registry.accountId, "access"))
|| registry.runtime.ws.actions.isChannelAccessRevoked(channelId, serverId)) return
+ return { channelId, serverId }
+}
+
+export function cachedConversationNavigationHref(queryClient: QueryClient, viewerUserId: string, channelId: string) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry?.accountId !== viewerUserId || registry.sessionViewer() !== viewerUserId) return
+ const channel = registry.collections.channels.get(channelId)
+ if (!channel) return
+ const href = channel.type === "dm" && channel.serverId === null
+ ? systemNotificationHref({ kind: "dm", channelId })
+ : channel.type !== "dm" && channel.serverId
+ ? systemNotificationHref({ kind: "server", channelId, serverId: channel.serverId })
+ : undefined
+ return href && cachedNavigationTarget(queryClient, href) ? href : undefined
+}
+
+export function prepareNavigationMetadata(queryClient: QueryClient, href: string, intent: "prefetch" | "foreground") {
+ const target = cachedNavigationTarget(queryClient, href)
+ if (!target) return
+ const { channelId, serverId } = target
const action = intent === "prefetch" ? prefetchForHref(href) : navigationForHref(href)
const anchorMessageId = new URL(href, "https://alook.test").searchParams.get("msg")
const options = conversationEntryOptions(queryClient, { serverId, channelId, anchorMessageId }, { action, reason: intent })
diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts
index 3be52358b..66f2f810a 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
@@ -63,6 +63,17 @@ async function resumeActivation(page: Page, activation: Activation) {
}, activation)
}
+async function foregroundActivation(page: Page, activation: Activation) {
+ await expect.poll(() => page.evaluate(() => Boolean((
+ window as typeof window & { __mobileNotificationQa: Bridge }
+ ).__mobileNotificationQa.listener))).toBe(true)
+ await page.evaluate((value) => {
+ const state = (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa
+ state.pending = value
+ ;(state.listener as { onmessage: (value: unknown) => void }).onmessage({})
+ }, activation)
+}
+
type MessageDoorEvidence = {
status: number
payload: { id?: string; channelId?: string }
@@ -75,19 +86,24 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =
expect(response.ok, `${path}: ${response.status}`).toBeTruthy()
}
async function captureMessageDoor(page: Page, targetId: string, messageId: string) {
+ let observed: MessageDoorEvidence | undefined
+ let requests = 0
let capture!: (evidence: MessageDoorEvidence) => void
let fail!: (error: unknown) => void
const result = new Promise<MessageDoorEvidence>((resolve, reject) => {
capture = resolve
fail = reject
})
+ void result.catch(() => undefined)
await page.route((url) => url.pathname === `/api/community/messages/${messageId}`, async (route) => {
+ requests += 1
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)
+ observed = evidence
await route.fulfill({ response })
capture(evidence)
}
@@ -96,7 +112,7 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =
await route.abort()
}
})
- return { result }
+ return { result, evidence: () => observed, requestCount: () => requests }
}
const { sessionCookie, userId } = actors
const { seedChannel, seedDm, seedDmMessage, seedFriendship, seedJoinServer, seedMessage, seedServer } = actors.seed
@@ -137,10 +153,6 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =
const door = await captureMessageDoor(page, targetId, messageId)
await page.goto("/c/me/friends")
if (mode === "resume") await resumeActivation(page, activation)
- const { status, payload } = await door.result
- expect(status).toBe(200)
- 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(() => (
@@ -150,7 +162,51 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =
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, channelId: payload.channelId, messageId, url: page.url() }), contentType: "application/json" })
+ const evidence = door.evidence()
+ if (evidence) {
+ expect(evidence.status).toBe(200)
+ expect(evidence.payload.id).toBe(messageId)
+ expect(evidence.payload.channelId).toBe(targetId)
+ }
+ else expect(door.requestCount()).toBe(0)
+ await testInfo.attach("message-door-evidence", { body: JSON.stringify({ simulation: "iPhone UA + Tauri command shim + browser visibility events", navigation: evidence ? "message resolution" : "cached conversation", evidence, messageDoorRequests: door.requestCount(), targetId, messageId, url: page.url() }), contentType: "application/json" })
+ await testInfo.attach("chat", { body: await page.screenshot(), contentType: "image/png" })
+ })
+ }
+ }
+
+ for (const mode of ["foreground", "resume"] as const) {
+ for (const surface of ["dm", "channel"] as const) {
+ test(`cached ${mode} ${surface} opens directly in the same document`, async ({ caseActors }, testInfo) => {
+ const actors = await caseActors(["alice", "bob"])
+ const { serverId, channelId, channelMessageId, dmId, dmMessageId, captureMessageDoor } = await prepareCase1(actors)
+ const { page } = await actors.asUser("bob", devices["iPhone 13"])
+ const targetId = surface === "dm" ? dmId : channelId
+ const messageId = surface === "dm" ? dmMessageId : channelMessageId
+ const path = surface === "dm" ? `/c/me/${targetId}` : `/c/channels/${serverId}/${targetId}`
+ const parent = surface === "dm" ? "/c/me" : `/c/channels/${serverId}`
+ const activation = { notificationId: crypto.randomUUID(), targetId, messageId }
+ await installMobileBridge(page, null)
+ const door = await captureMessageDoor(page, targetId, messageId)
+ await page.goto(path)
+ await expect(composerEditable(page)).toBeVisible({ timeout: 30_000 })
+ await expect(page.getByTestId(tid.message(messageId))).toBeVisible()
+ const timeOrigin = await page.evaluate(() => performance.timeOrigin)
+ await page.getByRole("button", { name: "Back", exact: true }).click()
+ await expect(page).toHaveURL(`${WEB_URL}${parent}`)
+ if (mode === "foreground") await foregroundActivation(page, activation)
+ else await resumeActivation(page, activation)
+ await expect(page).toHaveURL(`${WEB_URL}${path}`)
+ await expect(composerEditable(page)).toBeVisible()
+ await expect(page.getByTestId(tid.message(messageId))).toBeVisible()
+ await expect.poll(() => page.evaluate(() => (
+ window as typeof window & { __mobileNotificationQa: Bridge }
+ ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])
+ expect(door.requestCount()).toBe(0)
+ expect(await page.evaluate(() => performance.timeOrigin)).toBe(timeOrigin)
+ expect(await page.evaluate(() => (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa.documentLoads)).toBe(1)
+ await expect(page.locator('[data-slot="sheet-content"]')).toHaveCount(0)
+ await testInfo.attach("cached-navigation-evidence", { body: JSON.stringify({ simulation: "iPhone UA + Tauri command shim", mode, surface, targetId, messageId, messageDoorRequests: door.requestCount(), timeOrigin, documentLoads: 1, url: page.url() }), contentType: "application/json" })
await testInfo.attach("chat", { body: await page.screenshot(), contentType: "image/png" })
})
}