Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 修复 iOS 推送点击任务跳转 (#1721)

Dash6e8487a19766
diff --git a/apps/mobile/src/__tests__/pushRegistrationModel.test.ts b/apps/mobile/src/__tests__/pushRegistrationModel.test.ts
index 4e2faf1a0b..765d6784bc 100644
--- a/apps/mobile/src/__tests__/pushRegistrationModel.test.ts
+++ b/apps/mobile/src/__tests__/pushRegistrationModel.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
buildPushTokenRegistrationBody,
parseNotificationDeepLink,
+ parseNotificationResponseDeepLink,
resolvePushAppVariant,
} from '@/notifications/pushRegistrationModel';
@@ -56,3 +57,67 @@ describe('parseNotificationDeepLink', () => {
expect(parseNotificationDeepLink(input)).toBeNull();
});
});
+
+describe('parseNotificationResponseDeepLink', () => {
+ it('读取 Expo content.data 中的深链', () => {
+ expect(
+ parseNotificationResponseDeepLink({
+ notification: {
+ request: {
+ content: { data: { deepLink: '/sessions/s-1?deviceId=d-1' } },
+ trigger: { type: 'push', payload: {} },
+ },
+ },
+ }),
+ ).toBe('/sessions/s-1?deviceId=d-1');
+ });
+
+ it('兼容 iOS APNs trigger.payload 顶层深链', () => {
+ expect(
+ parseNotificationResponseDeepLink({
+ notification: {
+ request: {
+ content: { data: {} },
+ trigger: {
+ type: 'push',
+ payload: { deepLink: '/sessions/s-2?deviceId=d-2' },
+ },
+ },
+ },
+ }),
+ ).toBe('/sessions/s-2?deviceId=d-2');
+ });
+
+ it('兼容 relay 将自定义字段包在 payload.body / payload.data 中', () => {
+ expect(
+ parseNotificationResponseDeepLink({
+ notification: {
+ request: {
+ content: { data: {} },
+ trigger: {
+ type: 'push',
+ payload: { body: { deepLink: '/sessions/s-3?deviceId=d-3' } },
+ },
+ },
+ },
+ }),
+ ).toBe('/sessions/s-3?deviceId=d-3');
+ expect(
+ parseNotificationResponseDeepLink({
+ notification: {
+ request: {
+ content: { data: {} },
+ trigger: {
+ type: 'push',
+ payload: { data: { deepLink: '/sessions/s-4?deviceId=d-4' } },
+ },
+ },
+ },
+ }),
+ ).toBe('/sessions/s-4?deviceId=d-4');
+ });
+
+ it('非对象响应返回 null', () => {
+ expect(parseNotificationResponseDeepLink(null)).toBeNull();
+ });
+});
diff --git a/apps/mobile/src/notifications/PushNotificationsBridge.tsx b/apps/mobile/src/notifications/PushNotificationsBridge.tsx
index c6ab69c22a..3d61f6f95a 100644
--- a/apps/mobile/src/notifications/PushNotificationsBridge.tsx
+++ b/apps/mobile/src/notifications/PushNotificationsBridge.tsx
@@ -1,8 +1,9 @@
import { useRouter } from 'expo-router';
-import { useEffect, useRef } from 'react';
+import { useCallback, useEffect, useRef } from 'react';
+import { AppState } from 'react-native';
import { useAuth } from '@/auth/AuthContext';
import Notifications from './nativeNotifications';
-import { parseNotificationDeepLink } from './pushRegistrationModel';
+import { parseNotificationResponseDeepLink } from './pushRegistrationModel';
import {
configureForegroundNotificationBehavior,
isPushSupported,
@@ -11,22 +12,35 @@ import {
syncPushRegistration,
} from './pushNotifications';
-/** 冷启动 last-response 的已消费标记(模块级:组件重挂/Provider 重建也不重复路由)。 */
-const consumedLastResponseIds = new Set<string>();
+/** 已消费点击的去重键(模块级:组件重挂/Provider 重建也不重复路由)。 */
+const consumedNotificationResponseKeys = new Set<string>();
+type NotificationResponse = Parameters<
+ Parameters<typeof Notifications.addNotificationResponseReceivedListener>[0]
+>[0];
/**
* 移动推送的运行时桥(挂在 AuthProvider 内、导航树旁,不渲染任何 UI):
*
* 1. 登录后按本机开关同步 token 注册(启动补偿:上次注册失败/换账号后自愈);
* 2. APNs token 轮换时重新上报;
- * 3. 通知点击(前台/后台/冷启动)→ 校验 data.deepLink → 路由到对应会话;
+ * 3. 通知点击(前台/后台/冷启动)→ 解析 APNs / Expo 深链 → 路由到对应会话;
* 4. 前台压掉系统横幅。
*/
export function PushNotificationsBridge() {
const auth = useAuth();
const router = useRouter();
+ const routerRef = useRef(router);
+ routerRef.current = router;
/** 冷启动点通知时 auth 可能未就绪,先存下待路由的深链。 */
const pendingDeepLinkRef = useRef<string | null>(null);
+ const authStateRef = useRef({
+ initialized: auth.initialized,
+ isAuthenticated: auth.isAuthenticated,
+ });
+ authStateRef.current = {
+ initialized: auth.initialized,
+ isAuthenticated: auth.isAuthenticated,
+ };
const apiFetchRef = useRef(auth.apiFetch);
apiFetchRef.current = auth.apiFetch;
@@ -69,41 +83,56 @@ export function PushNotificationsBridge() {
return () => sub.remove();
}, [auth.initialized, auth.isAuthenticated]);
- // 通知点击路由:后台点击经 response listener,冷启动经 last response 补偿
+ const flushPendingDeepLink = useCallback((): void => {
+ const target = pendingDeepLinkRef.current;
+ if (!target) return;
+ const { initialized, isAuthenticated } = authStateRef.current;
+ if (!initialized || !isAuthenticated) return; // 待 auth 就绪后由下方 effect 重放
+ pendingDeepLinkRef.current = null;
+ routerRef.current.push(target as never);
+ }, []);
+
+ // 通知点击路由:后台点击经 response listener,冷启动 / 回前台经 last response 补偿
useEffect(() => {
if (!isPushSupported()) return;
- const routeTo = (deepLink: string | null): void => {
+ const consumeResponse = (response: NotificationResponse): void => {
+ const deepLink = parseNotificationResponseDeepLink(response);
if (!deepLink) return;
+ const identifier = response.notification.request.identifier;
+ const dedupeKey = identifier ? `id:${identifier}` : `deepLink:${deepLink}`;
+ if (consumedNotificationResponseKeys.has(dedupeKey)) return;
+ consumedNotificationResponseKeys.add(dedupeKey);
+ void Notifications.clearLastNotificationResponseAsync?.()?.catch(() => undefined);
pendingDeepLinkRef.current = deepLink;
flushPendingDeepLink();
};
- const flushPendingDeepLink = (): void => {
- const target = pendingDeepLinkRef.current;
- if (!target) return;
- if (!auth.initialized || !auth.isAuthenticated) return; // 待 auth 就绪后由下方 effect 重放
- pendingDeepLinkRef.current = null;
- router.push(target as never);
+
+ const readLastResponse = (): void => {
+ void Notifications.getLastNotificationResponseAsync()
+ .then((response) => {
+ if (response) consumeResponse(response);
+ })
+ .catch(() => undefined);
};
- // effect 因 auth 就绪重跑时,冷启动阶段暂存的深链在此重放——last response
- // 已被上一轮消费/清除,不能依赖再次读取它来触发
- flushPendingDeepLink();
+
const sub = Notifications.addNotificationResponseReceivedListener((response) => {
- routeTo(parseNotificationDeepLink(response.notification.request.content.data));
+ consumeResponse(response);
});
- void Notifications.getLastNotificationResponseAsync().then((response) => {
- if (!response) return;
- // last response 会一直返回同一次点击(effect 因 auth 变化重跑、组件重挂时会
- // 再次读到):按 request.identifier 去重,消费后清掉系统侧记录,避免用户处理
- // 完通知后又被重复推回旧会话。
- const identifier = response.notification.request.identifier;
- if (identifier && consumedLastResponseIds.has(identifier)) return;
- if (identifier) consumedLastResponseIds.add(identifier);
- void Notifications.clearLastNotificationResponseAsync?.().catch(() => undefined);
- routeTo(parseNotificationDeepLink(response.notification.request.content.data));
+ readLastResponse();
+ const appStateSub = AppState.addEventListener('change', (state) => {
+ if (state === 'active') readLastResponse();
});
- return () => sub.remove();
- // auth 状态变化时重跑以重放 pending 深链(冷启动点通知 → 登录恢复完成 → 进会话)
- }, [auth.initialized, auth.isAuthenticated, router]);
+ return () => {
+ sub.remove();
+ appStateSub.remove();
+ };
+ }, [flushPendingDeepLink]);
+
+ // auth 就绪后重放冷启动 / 点击期间暂存的深链。监听本身保持挂载,避免 auth
+ // 状态变化重建 effect 时与 last-response 读取发生竞态。
+ useEffect(() => {
+ flushPendingDeepLink();
+ }, [auth.initialized, auth.isAuthenticated, flushPendingDeepLink]);
return null;
}
diff --git a/apps/mobile/src/notifications/pushRegistrationModel.ts b/apps/mobile/src/notifications/pushRegistrationModel.ts
index 9f72975d03..6e9c279c29 100644
--- a/apps/mobile/src/notifications/pushRegistrationModel.ts
+++ b/apps/mobile/src/notifications/pushRegistrationModel.ts
@@ -59,3 +59,39 @@ export function parseNotificationDeepLink(data: unknown): string | null {
if (deepLink.includes('://') || deepLink.startsWith('//')) return null;
return deepLink;
}
+
+function parseNotificationPayloadDeepLink(data: unknown): string | null {
+ const direct = parseNotificationDeepLink(data);
+ if (direct) return direct;
+ if (!data || typeof data !== 'object') return null;
+ const record = data as Record<string, unknown>;
+ // APNs relay implementations may wrap custom fields under `body` or `data`.
+ // Keep the fallback explicit rather than recursively walking untrusted payloads.
+ return parseNotificationDeepLink(record.body) ?? parseNotificationDeepLink(record.data);
+}
+
+/**
+ * 从 expo-notifications 的点击响应中解析任务深链。
+ *
+ * iOS 远程通知在 Expo 56 有两条数据出口:`content.data` 通常来自 APNs
+ * userInfo 的 `body` 字段,而完整的 APNs userInfo 保存在
+ * `request.trigger.payload`。两者都支持,避免 relay 的 payload 包装方式
+ * 让点击事件静默失效。
+ */
+export function parseNotificationResponseDeepLink(response: unknown): string | null {
+ if (!response || typeof response !== 'object') return null;
+ const notification = (response as Record<string, unknown>).notification;
+ if (!notification || typeof notification !== 'object') return null;
+ const request = (notification as Record<string, unknown>).request;
+ if (!request || typeof request !== 'object') return null;
+ const requestRecord = request as Record<string, unknown>;
+ const content = requestRecord.content;
+ if (content && typeof content === 'object') {
+ const contentData = (content as Record<string, unknown>).data;
+ const fromContent = parseNotificationPayloadDeepLink(contentData);
+ if (fromContent) return fromContent;
+ }
+ const trigger = requestRecord.trigger;
+ if (!trigger || typeof trigger !== 'object') return null;
+ return parseNotificationPayloadDeepLink((trigger as Record<string, unknown>).payload);
+}