🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(push): add PushChannel, receipt cron, and pushToken tRPC API (#15233)
Tsuki4d840e90715f
diff --git a/locales/ar/setting.json b/locales/ar/setting.jsonindex e845a8d5ec8..fabdbc52ef4 100644--- a/locales/ar/setting.json+++ b/locales/ar/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "فشل المهمة المجدولة","notification.item.image_generation_completed": "اكتمل إنشاء الصورة","notification.item.video_generation_completed": "اكتمل إنشاء الفيديو",+ "notification.push.desc": "إرسال إشعارات دفع إلى أجهزتك المحمولة (يتطلب تطبيق LobeHub المحمول)",+ "notification.push.title": "إشعارات الدفع للجوال","notification.title": "قنوات الإشعارات","platformAgentConfig.availability.available": "متاح","platformAgentConfig.availability.checking": "جارٍ التحقق...",diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.jsonindex 9056b8919b9..984157da472 100644--- a/locales/bg-BG/setting.json+++ b/locales/bg-BG/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "Планираната задача не успя","notification.item.image_generation_completed": "Генерирането на изображение завърши","notification.item.video_generation_completed": "Генерирането на видео завърши",+ "notification.push.desc": "Изпращайте push известия до вашите мобилни устройства (изисква се мобилното приложение LobeHub)",+ "notification.push.title": "Мобилни push известия","notification.title": "Канали за известия","platformAgentConfig.availability.available": "Наличен","platformAgentConfig.availability.checking": "Проверка...",diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.jsonindex e3059346bc4..9e08cd195b3 100644--- a/locales/de-DE/setting.json+++ b/locales/de-DE/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "Geplanter Task fehlgeschlagen","notification.item.image_generation_completed": "Bilderstellung abgeschlossen","notification.item.video_generation_completed": "Videoerstellung abgeschlossen",+ "notification.push.desc": "Senden Sie Push-Benachrichtigungen an Ihre mobilen Geräte (LobeHub Mobile App erforderlich)",+ "notification.push.title": "Mobile Push-Benachrichtigungen","notification.title": "Benachrichtigungskanäle","platformAgentConfig.availability.available": "Verfügbar","platformAgentConfig.availability.checking": "Überprüfen...",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 40b0400e3b0..d761ed60321 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -504,6 +504,8 @@"notification.item.agent_cron_job_failed": "Scheduled task failed","notification.item.image_generation_completed": "Image generation completed","notification.item.video_generation_completed": "Video generation completed",+ "notification.push.desc": "Send push notifications to your mobile devices (LobeHub mobile app required)",+ "notification.push.title": "Mobile Push Notifications","notification.title": "Notification Channels","platformAgentConfig.availability.available": "Available","platformAgentConfig.availability.checking": "Checking...",diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.jsonindex 1a025189aaf..8bf7e25ee56 100644--- a/locales/es-ES/setting.json+++ b/locales/es-ES/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "La tarea programada falló","notification.item.image_generation_completed": "Generación de imagen completada","notification.item.video_generation_completed": "Generación de vídeo completada",+ "notification.push.desc": "Envía notificaciones push a tus dispositivos móviles (se requiere la aplicación móvil LobeHub)",+ "notification.push.title": "Notificaciones Push Móviles","notification.title": "Canales de Notificación","platformAgentConfig.availability.available": "Disponible","platformAgentConfig.availability.checking": "Comprobando...",diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.jsonindex 010368e13f0..fb50b7a86e5 100644--- a/locales/fa-IR/setting.json+++ b/locales/fa-IR/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "وظیفه زمانبندیشده شکست خورد","notification.item.image_generation_completed": "تولید تصویر با موفقیت انجام شد","notification.item.video_generation_completed": "تولید ویدئو با موفقیت انجام شد",+ "notification.push.desc": "ارسال اعلانهای فشاری به دستگاههای موبایل شما (اپلیکیشن موبایل LobeHub مورد نیاز است)",+ "notification.push.title": "اعلانهای فشاری موبایل","notification.title": "کانالهای اعلان","platformAgentConfig.availability.available": "در دسترس","platformAgentConfig.availability.checking": "در حال بررسی...",diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.jsonindex db1a04273a4..b817d3e761f 100644--- a/locales/fr-FR/setting.json+++ b/locales/fr-FR/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "La tâche planifiée a échoué","notification.item.image_generation_completed": "Génération d’image terminée","notification.item.video_generation_completed": "Génération de vidéo terminée",+ "notification.push.desc": "Envoyez des notifications push à vos appareils mobiles (application mobile LobeHub requise)",+ "notification.push.title": "Notifications Push Mobiles","notification.title": "Canaux de notification","platformAgentConfig.availability.available": "Disponible","platformAgentConfig.availability.checking": "Vérification...",diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.jsonindex c7158597f21..9b8a7f5e0a3 100644--- a/locales/it-IT/setting.json+++ b/locales/it-IT/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "Attività pianificata non riuscita","notification.item.image_generation_completed": "Generazione immagine completata","notification.item.video_generation_completed": "Generazione video completata",+ "notification.push.desc": "Invia notifiche push ai tuoi dispositivi mobili (è richiesta l'app mobile LobeHub)",+ "notification.push.title": "Notifiche Push Mobile","notification.title": "Canali di Notifica","platformAgentConfig.availability.available": "Disponibile","platformAgentConfig.availability.checking": "Verifica in corso...",diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.jsonindex bdf755ebf79..e4a919ed7a2 100644--- a/locales/ja-JP/setting.json+++ b/locales/ja-JP/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "スケジュールされたタスクが失敗しました","notification.item.image_generation_completed": "画像生成が完了しました","notification.item.video_generation_completed": "動画生成が完了しました",+ "notification.push.desc": "モバイルデバイスにプッシュ通知を送信します(LobeHubモバイルアプリが必要です)",+ "notification.push.title": "モバイルプッシュ通知","notification.title": "通知チャンネル","platformAgentConfig.availability.available": "利用可能","platformAgentConfig.availability.checking": "確認中...",diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.jsonindex 110768b0518..1c1752e4bf0 100644--- a/locales/ko-KR/setting.json+++ b/locales/ko-KR/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "예약된 작업이 실패했습니다","notification.item.image_generation_completed": "이미지 생성 완료","notification.item.video_generation_completed": "동영상 생성 완료",+ "notification.push.desc": "모바일 장치로 푸시 알림을 보냅니다 (LobeHub 모바일 앱 필요)",+ "notification.push.title": "모바일 푸시 알림","notification.title": "알림 채널","platformAgentConfig.availability.available": "사용 가능","platformAgentConfig.availability.checking": "확인 중...",diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.jsonindex 88af0dfbcb0..6a0fec08b1e 100644--- a/locales/nl-NL/setting.json+++ b/locales/nl-NL/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "Geplande taak mislukt","notification.item.image_generation_completed": "Afbeeldingsgeneratie voltooid","notification.item.video_generation_completed": "Videogeneratie voltooid",+ "notification.push.desc": "Stuur pushmeldingen naar je mobiele apparaten (LobeHub mobiele app vereist)",+ "notification.push.title": "Mobiele pushmeldingen","notification.title": "Meldingskanalen","platformAgentConfig.availability.available": "Beschikbaar","platformAgentConfig.availability.checking": "Controleren...",diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.jsonindex 0f93d63c16c..39505e2832c 100644--- a/locales/pl-PL/setting.json+++ b/locales/pl-PL/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "Zadanie zaplanowane nie powiodło się","notification.item.image_generation_completed": "Generowanie obrazu zakończone","notification.item.video_generation_completed": "Generowanie wideo zakończone",+ "notification.push.desc": "Wysyłaj powiadomienia push na swoje urządzenia mobilne (wymagana aplikacja mobilna LobeHub)",+ "notification.push.title": "Mobilne powiadomienia push","notification.title": "Kanały powiadomień","platformAgentConfig.availability.available": "Dostępny","platformAgentConfig.availability.checking": "Sprawdzanie...",diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.jsonindex 2f931b78da8..e15f860c6f1 100644--- a/locales/pt-BR/setting.json+++ b/locales/pt-BR/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "Tarefa agendada falhou","notification.item.image_generation_completed": "Geração de imagem concluída","notification.item.video_generation_completed": "Geração de vídeo concluída",+ "notification.push.desc": "Envie notificações push para seus dispositivos móveis (aplicativo móvel LobeHub necessário)",+ "notification.push.title": "Notificações Push Móveis","notification.title": "Canais de Notificação","platformAgentConfig.availability.available": "Disponível","platformAgentConfig.availability.checking": "Verificando...",diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.jsonindex 7221156631d..0229d59e025 100644--- a/locales/ru-RU/setting.json+++ b/locales/ru-RU/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "Запланированная задача не выполнена","notification.item.image_generation_completed": "Генерация изображения завершена","notification.item.video_generation_completed": "Генерация видео завершена",+ "notification.push.desc": "Отправляйте push-уведомления на свои мобильные устройства (требуется мобильное приложение LobeHub)",+ "notification.push.title": "Мобильные push-уведомления","notification.title": "Каналы уведомлений","platformAgentConfig.availability.available": "Доступно","platformAgentConfig.availability.checking": "Проверка...",diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.jsonindex f1bc60aae2d..95a9bb8167a 100644--- a/locales/tr-TR/setting.json+++ b/locales/tr-TR/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "Zamanlanmış görev başarısız oldu","notification.item.image_generation_completed": "Görüntü oluşturma tamamlandı","notification.item.video_generation_completed": "Video oluşturma tamamlandı",+ "notification.push.desc": "Mobil cihazlarınıza anlık bildirimler gönderin (LobeHub mobil uygulaması gereklidir)",+ "notification.push.title": "Mobil Anlık Bildirimler","notification.title": "Bildirim Kanalları","platformAgentConfig.availability.available": "Mevcut","platformAgentConfig.availability.checking": "Kontrol ediliyor...",diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.jsonindex 530ef5fc449..5b851ad8ae5 100644--- a/locales/vi-VN/setting.json+++ b/locales/vi-VN/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "Tác vụ theo lịch đã thất bại","notification.item.image_generation_completed": "Tạo ảnh hoàn tất","notification.item.video_generation_completed": "Tạo video hoàn tất",+ "notification.push.desc": "Gửi thông báo đẩy đến các thiết bị di động của bạn (cần ứng dụng di động LobeHub)",+ "notification.push.title": "Thông báo đẩy trên di động","notification.title": "Kênh Thông Báo","platformAgentConfig.availability.available": "Có sẵn","platformAgentConfig.availability.checking": "Đang kiểm tra...",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 9c3dfd1c253..eb21b27c1c9 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -504,6 +504,8 @@"notification.item.agent_cron_job_failed": "计划任务失败","notification.item.image_generation_completed": "图片生成完成","notification.item.video_generation_completed": "视频生成完成",+ "notification.push.desc": "向您的移动设备发送推送通知(需要安装 LobeHub 移动应用)",+ "notification.push.title": "移动推送通知","notification.title": "通知渠道","platformAgentConfig.availability.available": "可用","platformAgentConfig.availability.checking": "检测中...",diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.jsonindex 5a4c0177198..080cbe4bd28 100644--- a/locales/zh-TW/setting.json+++ b/locales/zh-TW/setting.json@@ -478,6 +478,8 @@"notification.item.agent_cron_job_failed": "排程任務失敗","notification.item.image_generation_completed": "圖片生成完成","notification.item.video_generation_completed": "影片生成完成",+ "notification.push.desc": "向您的行動裝置發送推播通知(需要 LobeHub 行動應用程式)",+ "notification.push.title": "行動推播通知","notification.title": "通知頻道","platformAgentConfig.availability.available": "可用","platformAgentConfig.availability.checking": "檢查中...",diff --git a/package.json b/package.jsonindex 3fa9b66b3c9..04013cfb3de 100644--- a/package.json+++ b/package.json@@ -342,6 +342,7 @@"drizzle-zod": "^0.5.1","epub2": "^3.0.2","es-toolkit": "^1.44.0",+ "expo-server-sdk": "^6.1.0","fast-deep-equal": "^3.1.3","fflate": "^0.8.2","ffmpeg-static": "^5.3.0",diff --git a/packages/database/src/models/__tests__/pushToken.test.ts b/packages/database/src/models/__tests__/pushToken.test.tsnew file mode 100644index 00000000000..d809abcdf44--- /dev/null+++ b/packages/database/src/models/__tests__/pushToken.test.ts@@ -0,0 +1,171 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { pushTokens, users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { deletePushTokensByExpoTokens, PushTokenModel } from '../pushToken';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'push-token-model-test-user-id';+const otherUserId = 'push-token-model-test-other-user';+const model = new PushTokenModel(serverDB, userId);++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.delete(users).where(eq(users.id, otherUserId));+});++describe('PushTokenModel', () => {+ describe('upsert', () => {+ it('should insert a new token row', async () => {+ const result = await model.upsert({+ deviceId: 'device-1',+ expoToken: 'ExponentPushToken[abc]',+ platform: 'ios',+ });++ expect(result.id).toBeDefined();+ expect(result).toMatchObject({+ deviceId: 'device-1',+ expoToken: 'ExponentPushToken[abc]',+ platform: 'ios',+ userId,+ });+ });++ it('should update lastSeenAt and expoToken when re-registering same device', async () => {+ const first = await model.upsert({+ deviceId: 'device-1',+ expoToken: 'ExponentPushToken[old]',+ platform: 'ios',+ });+ const firstSeen = first.lastSeenAt;++ // wait so timestamps clearly differ+ await new Promise((r) => setTimeout(r, 50));++ const updated = await model.upsert({+ appVersion: '1.2.3',+ deviceId: 'device-1',+ expoToken: 'ExponentPushToken[new]',+ platform: 'ios',+ });++ expect(updated.id).toBe(first.id); // same row, not a new one+ expect(updated.expoToken).toBe('ExponentPushToken[new]');+ expect(updated.appVersion).toBe('1.2.3');+ expect(updated.lastSeenAt.getTime()).toBeGreaterThan(firstSeen.getTime());++ const rows = await serverDB.select().from(pushTokens).where(eq(pushTokens.userId, userId));+ expect(rows).toHaveLength(1);+ });++ it('should support same user with multiple devices', async () => {+ await model.upsert({+ deviceId: 'iphone',+ expoToken: 'ExponentPushToken[ios]',+ platform: 'ios',+ });+ await model.upsert({+ deviceId: 'pixel',+ expoToken: 'ExponentPushToken[android]',+ platform: 'android',+ });++ const tokens = await model.listByUserId();+ expect(tokens).toHaveLength(2);+ });+ });++ describe('unregister', () => {+ it('should delete only the specified device', async () => {+ await model.upsert({ deviceId: 'a', expoToken: 't1', platform: 'ios' });+ await model.upsert({ deviceId: 'b', expoToken: 't2', platform: 'android' });++ await model.unregister('a');++ const tokens = await model.listByUserId();+ expect(tokens).toHaveLength(1);+ expect(tokens[0].deviceId).toBe('b');+ });++ it('should not delete another user tokens', async () => {+ await model.upsert({ deviceId: 'shared-device', expoToken: 'mine', platform: 'ios' });++ const otherModel = new PushTokenModel(serverDB, otherUserId);+ await otherModel.upsert({+ deviceId: 'shared-device',+ expoToken: 'theirs',+ platform: 'ios',+ });++ await model.unregister('shared-device');++ const theirs = await otherModel.listByUserId();+ expect(theirs).toHaveLength(1);+ expect(theirs[0].expoToken).toBe('theirs');+ });+ });++ describe('listByUserId', () => {+ it('should return empty array when no tokens', async () => {+ const tokens = await model.listByUserId();+ expect(tokens).toEqual([]);+ });++ it('should only return current user tokens', async () => {+ await model.upsert({ deviceId: 'mine', expoToken: 'a', platform: 'ios' });+ const otherModel = new PushTokenModel(serverDB, otherUserId);+ await otherModel.upsert({ deviceId: 'theirs', expoToken: 'b', platform: 'ios' });++ const tokens = await model.listByUserId();+ expect(tokens).toHaveLength(1);+ expect(tokens[0].userId).toBe(userId);+ });+ });++ describe('deletePushTokensByExpoTokens helper', () => {+ it('should noop on empty array', async () => {+ await model.upsert({ deviceId: 'a', expoToken: 'keep', platform: 'ios' });+ await deletePushTokensByExpoTokens(serverDB, []);+ const tokens = await model.listByUserId();+ expect(tokens).toHaveLength(1);+ });++ it('should delete cross-user by expoToken', async () => {+ await model.upsert({ deviceId: 'mine', expoToken: 'bad-token', platform: 'ios' });+ const otherModel = new PushTokenModel(serverDB, otherUserId);+ await otherModel.upsert({ deviceId: 'theirs', expoToken: 'bad-token', platform: 'ios' });+ await otherModel.upsert({ deviceId: 'good', expoToken: 'good-token', platform: 'ios' });++ await deletePushTokensByExpoTokens(serverDB, ['bad-token']);++ const mine = await model.listByUserId();+ const theirs = await otherModel.listByUserId();+ expect(mine).toHaveLength(0);+ expect(theirs).toHaveLength(1);+ expect(theirs[0].expoToken).toBe('good-token');+ });+ });++ describe('cascade delete on user removal', () => {+ it('should delete tokens when user is deleted', async () => {+ await model.upsert({ deviceId: 'a', expoToken: 't', platform: 'ios' });+ await serverDB.delete(users).where(eq(users.id, userId));++ const remaining = await serverDB+ .select()+ .from(pushTokens)+ .where(eq(pushTokens.userId, userId));+ expect(remaining).toHaveLength(0);+ });+ });+});diff --git a/packages/database/src/models/pushToken.ts b/packages/database/src/models/pushToken.tsnew file mode 100644index 00000000000..33b36e96163--- /dev/null+++ b/packages/database/src/models/pushToken.ts@@ -0,0 +1,62 @@+import { and, eq, inArray } from 'drizzle-orm';++import type { NewPushToken, PushTokenItem } from '../schemas/pushToken';+import { pushTokens } from '../schemas/pushToken';+import type { LobeChatDatabase } from '../type';++export class PushTokenModel {+ private readonly userId: string;+ private readonly db: LobeChatDatabase;++ constructor(db: LobeChatDatabase, userId: string) {+ this.db = db;+ this.userId = userId;+ }++ /**+ * Upsert by (userId, deviceId). Re-registering the same device replaces+ * the previous token and refreshes lastSeenAt.+ */+ async upsert(data: Omit<NewPushToken, 'userId'>): Promise<PushTokenItem> {+ const [result] = await this.db+ .insert(pushTokens)+ .values({ ...data, userId: this.userId })+ .onConflictDoUpdate({+ set: {+ appVersion: data.appVersion,+ expoToken: data.expoToken,+ lastSeenAt: new Date(),+ locale: data.locale,+ platform: data.platform,+ },+ target: [pushTokens.userId, pushTokens.deviceId],+ })+ .returning();++ return result;+ }++ /** Delete this user's token for a specific device (e.g. on logout). */+ async unregister(deviceId: string) {+ return this.db+ .delete(pushTokens)+ .where(and(eq(pushTokens.userId, this.userId), eq(pushTokens.deviceId, deviceId)));+ }++ /** All tokens for this user — used by PushChannel to fan out a notification. */+ async listByUserId(): Promise<PushTokenItem[]> {+ return this.db.select().from(pushTokens).where(eq(pushTokens.userId, this.userId));+ }+}++/**+ * Static helper for the cloud-side receipt cleanup worker.+ * Not bound to a userId — operates across all users at once.+ */+export async function deletePushTokensByExpoTokens(+ db: LobeChatDatabase,+ tokens: string[],+): Promise<void> {+ if (tokens.length === 0) return;+ await db.delete(pushTokens).where(inArray(pushTokens.expoToken, tokens));+}diff --git a/packages/types/src/user/settings/notification.ts b/packages/types/src/user/settings/notification.tsindex 63335776f06..605cc91ef12 100644--- a/packages/types/src/user/settings/notification.ts+++ b/packages/types/src/user/settings/notification.ts@@ -7,4 +7,10 @@ export interface NotificationChannelSettings {export interface NotificationSettings {email?: NotificationChannelSettings;inbox?: NotificationChannelSettings;+ /**+ * Mobile push notifications (delivered via Expo Push Service → APNs/FCM).+ * Only takes effect for users with a registered Expo push token —+ * see `push_tokens` table.+ */+ push?: NotificationChannelSettings;}diff --git a/src/app/(backend)/api/dev/test-push/route.ts b/src/app/(backend)/api/dev/test-push/route.tsnew file mode 100644index 00000000000..07d5a339ccd--- /dev/null+++ b/src/app/(backend)/api/dev/test-push/route.ts@@ -0,0 +1,57 @@+import { NextResponse } from 'next/server';++import { PushChannel } from '@/server/services/push/PushChannel';++/**+ * Dev-only end-to-end push tester.+ *+ * POST http://localhost:3010/api/dev/test-push+ * body: { userId, title?, content?, actionUrl? }+ *+ * Looks up the user's registered Expo tokens via PushTokenModel and triggers+ * a real Expo Push Service send. Use this once EAS credentials are uploaded+ * to verify that the full stack (PushTokenModel → PushChannel → Expo → APNs/FCM+ * → device) works against a real device.+ *+ * Disabled in production builds.+ */+export async function POST(req: Request) {+ if (process.env.NODE_ENV !== 'development') {+ return NextResponse.json({ error: 'dev only' }, { status: 404 });+ }++ let body: {+ actionUrl?: string;+ content?: string;+ sessionId?: string;+ title?: string;+ userId?: string;+ };++ try {+ body = await req.json();+ } catch {+ return NextResponse.json({ error: 'invalid JSON body' }, { status: 400 });+ }++ if (!body.userId) {+ return NextResponse.json({ error: 'userId is required' }, { status: 400 });+ }++ const channel = new PushChannel();+ try {+ const result = await channel.deliver({+ actionUrl: body.actionUrl,+ content: body.content ?? 'Hello from /api/dev/test-push',+ notificationId: `dev-test-${Date.now()}`,+ title: body.title ?? 'Dev test push',+ userId: body.userId,+ });+ return NextResponse.json(result);+ } catch (error) {+ return NextResponse.json(+ { error: (error as Error).message, stack: (error as Error).stack },+ { status: 500 },+ );+ }+}diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.tsindex 97e12605fb1..f3213f98393 100644--- a/src/locales/default/setting.ts+++ b/src/locales/default/setting.ts@@ -535,6 +535,9 @@ export default {'notification.email.title': 'Email Notifications','notification.inbox.desc': 'Show notifications in the in-app inbox','notification.inbox.title': 'Inbox Notifications',+ 'notification.push.desc':+ 'Send push notifications to your mobile devices (LobeHub mobile app required)',+ 'notification.push.title': 'Mobile Push Notifications','notification.category.generation.title': 'Generation','notification.category.schedule.title': 'Scheduled tasks','notification.item.agent_cron_job_failed': 'Scheduled task failed',diff --git a/src/server/routers/lambda/__tests__/pushToken.test.ts b/src/server/routers/lambda/__tests__/pushToken.test.tsnew file mode 100644index 00000000000..3191faa7d67--- /dev/null+++ b/src/server/routers/lambda/__tests__/pushToken.test.ts@@ -0,0 +1,108 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { pushTokenRouter } from '@/server/routers/lambda/pushToken';++const mockUpsert = vi.fn();+const mockUnregister = vi.fn();++vi.mock('@/database/models/pushToken', () => ({+ PushTokenModel: vi.fn(() => ({+ unregister: mockUnregister,+ upsert: mockUpsert,+ })),+}));++const createCaller = (ctxOverrides: Partial<any> = {}) => {+ const ctx = {+ serverDB: {} as any,+ userId: 'user-1',+ ...ctxOverrides,+ };++ return pushTokenRouter.createCaller(ctx);+};++describe('pushTokenRouter', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('register', () => {+ it('should upsert with the input fields', async () => {+ mockUpsert.mockResolvedValueOnce({ id: 'row-1' });++ const caller = createCaller();+ const result = await caller.register({+ appVersion: '1.0.0',+ deviceId: 'device-1',+ expoToken: 'ExponentPushToken[abc]',+ locale: 'zh-CN',+ platform: 'ios',+ });++ expect(mockUpsert).toHaveBeenCalledWith({+ appVersion: '1.0.0',+ deviceId: 'device-1',+ expoToken: 'ExponentPushToken[abc]',+ locale: 'zh-CN',+ platform: 'ios',+ });+ expect(result).toEqual({ id: 'row-1' });+ });++ it('should accept omitted optional fields', async () => {+ mockUpsert.mockResolvedValueOnce({ id: 'row-1' });+ const caller = createCaller();++ await caller.register({+ deviceId: 'd',+ expoToken: 't',+ platform: 'android',+ });++ expect(mockUpsert).toHaveBeenCalledWith({+ deviceId: 'd',+ expoToken: 't',+ platform: 'android',+ });+ });++ it('should reject empty deviceId', async () => {+ const caller = createCaller();+ await expect(+ caller.register({ deviceId: '', expoToken: 't', platform: 'ios' }),+ ).rejects.toThrow();+ });++ it('should reject empty expoToken', async () => {+ const caller = createCaller();+ await expect(+ caller.register({ deviceId: 'd', expoToken: '', platform: 'ios' }),+ ).rejects.toThrow();+ });++ it('should reject invalid platform', async () => {+ const caller = createCaller();+ await expect(+ // @ts-expect-error testing runtime validation+ caller.register({ deviceId: 'd', expoToken: 't', platform: 'windows' }),+ ).rejects.toThrow();+ });+ });++ describe('unregister', () => {+ it('should call model.unregister with deviceId', async () => {+ mockUnregister.mockResolvedValueOnce(undefined);+ const caller = createCaller();++ await caller.unregister({ deviceId: 'device-1' });++ expect(mockUnregister).toHaveBeenCalledWith('device-1');+ });++ it('should reject empty deviceId', async () => {+ const caller = createCaller();+ await expect(caller.unregister({ deviceId: '' })).rejects.toThrow();+ });+ });+});diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.tsindex 230b6fbd1d9..7ea5eaf037f 100644--- a/src/server/routers/lambda/index.ts+++ b/src/server/routers/lambda/index.ts@@ -52,6 +52,7 @@ import { notebookRouter } from './notebook';import { notificationRouter } from './notification';import { oauthDeviceFlowRouter } from './oauthDeviceFlow';import { pluginRouter } from './plugin';+import { pushTokenRouter } from './pushToken';import { ragEvalRouter } from './ragEval';import { recentRouter } from './recent';import { searchRouter } from './search';@@ -114,6 +115,7 @@ export const lambdaRouter = router({notification: notificationRouter,oauthDeviceFlow: oauthDeviceFlowRouter,plugin: pluginRouter,+ pushToken: pushTokenRouter,ragEval: ragEvalRouter,recent: recentRouter,search: searchRouter,diff --git a/src/server/routers/lambda/pushToken.ts b/src/server/routers/lambda/pushToken.tsnew file mode 100644index 00000000000..42379a2eed6--- /dev/null+++ b/src/server/routers/lambda/pushToken.ts@@ -0,0 +1,37 @@+import { z } from 'zod';++import { PushTokenModel } from '@/database/models/pushToken';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';++const pushTokenProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: { pushTokenModel: new PushTokenModel(ctx.serverDB, ctx.userId) },+ });+});++export const pushTokenRouter = router({+ register: pushTokenProcedure+ .input(+ z.object({+ appVersion: z.string().optional(),+ deviceId: z.string().min(1),+ expoToken: z.string().min(1),+ locale: z.string().optional(),+ platform: z.enum(['ios', 'android']),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return ctx.pushTokenModel.upsert(input);+ }),++ unregister: pushTokenProcedure+ .input(z.object({ deviceId: z.string().min(1) }))+ .mutation(async ({ ctx, input }) => {+ return ctx.pushTokenModel.unregister(input.deviceId);+ }),+});++export type PushTokenRouter = typeof pushTokenRouter;diff --git a/src/server/routers/mobile/index.ts b/src/server/routers/mobile/index.tsindex b0a50e13a86..bdff35461bb 100644--- a/src/server/routers/mobile/index.ts+++ b/src/server/routers/mobile/index.ts@@ -19,6 +19,7 @@ import { homeRouter } from '../lambda/home';import { knowledgeBaseRouter } from '../lambda/knowledgeBase';import { marketRouter } from '../lambda/market';import { messageRouter } from '../lambda/message';+import { pushTokenRouter } from '../lambda/pushToken';import { sessionRouter } from '../lambda/session';import { sessionGroupRouter } from '../lambda/sessionGroup';import { taskRouter } from '../lambda/task';@@ -42,6 +43,7 @@ export const mobileRouter = router({knowledgeBase: knowledgeBaseRouter,market: marketRouter,message: messageRouter,+ pushToken: pushTokenRouter,session: sessionRouter,sessionGroup: sessionGroupRouter,subscription: mobileSubscriptionRouter,diff --git a/src/server/services/push/PushChannel.ts b/src/server/services/push/PushChannel.tsnew file mode 100644index 00000000000..ee1fa085558--- /dev/null+++ b/src/server/services/push/PushChannel.ts@@ -0,0 +1,124 @@+import { sleep } from '@lobechat/utils';+import debug from 'debug';+import { Expo, type ExpoPushMessage } from 'expo-server-sdk';++import { PushTokenModel } from '@/database/models/pushToken';+import { serverDB } from '@/database/server';++import { DEFAULT_PUSH_CHANNEL_ID } from './constants';+import type { PushDeliveryContext, PushDeliveryResult, PushTicketRecord } from './types';++const log = debug('lobe-notification:push');++/** Expo Push Service hard rate limit (messages per second per project) */+const SEND_CHUNK_THROTTLE_MS = 100;++/**+ * Push channel implementation backed by the Expo Push Service.+ *+ * Structurally compatible with cloud's `NotificationChannel`; can be registered+ * directly into cloud's `channelInstances` map. Also usable standalone by+ * self-hosters who supply their own EAS credentials.+ *+ * Behaviour:+ * 1. Resolves all of `userId`'s registered Expo tokens via `PushTokenModel`+ * 2. Filters out malformed tokens via `Expo.isExpoPushToken`+ * 3. Chunks + sends with `expo.sendPushNotificationsAsync`, with throttling+ * 4. Encodes (ticketId, expoToken) pairs into `providerMessageId` so the+ * receipt cron can identify invalid tokens later+ */+export class PushChannel {+ readonly id = 'push';++ private expo: Expo;++ constructor(expoClient?: Expo) {+ // FCM v1 is the only supported FCM API for new projects — Legacy server+ // keys were retired by Google. APNs uses the .p8 auth key uploaded to EAS.+ // (`useFcmV1` is implicit in the current SDK; no constructor flag needed.)+ this.expo = expoClient ?? new Expo();+ }++ async deliver(ctx: PushDeliveryContext): Promise<PushDeliveryResult> {+ const tokens = await new PushTokenModel(serverDB, ctx.userId).listByUserId();++ if (tokens.length === 0) {+ log('No push tokens for userId=%s', ctx.userId);+ return { failedReason: 'no_tokens', status: 'failed' };+ }++ // Build messages, keeping the order so we can map tickets back to tokens by index+ const validTokens = tokens.filter((t) => Expo.isExpoPushToken(t.expoToken));+ if (validTokens.length === 0) {+ log('All tokens malformed for userId=%s', ctx.userId);+ return { failedReason: 'invalid_tokens', status: 'failed' };+ }++ const messages: ExpoPushMessage[] = validTokens.map((t) => ({+ body: ctx.content,+ channelId: DEFAULT_PUSH_CHANNEL_ID,+ data: {+ notificationId: ctx.notificationId,+ url: ctx.actionUrl,+ },+ priority: 'high',+ sound: 'default',+ title: ctx.title,+ to: t.expoToken,+ }));++ const ticketRecords: PushTicketRecord[] = [];+ const chunks = this.expo.chunkPushNotifications(messages);+ let cursor = 0;++ for (const chunk of chunks) {+ try {+ const tickets = await this.expo.sendPushNotificationsAsync(chunk);++ tickets.forEach((ticket, i) => {+ const expoToken = chunk[i].to as string;++ if (ticket.status === 'ok') {+ ticketRecords.push({ expoToken, ticketId: ticket.id });+ } else {+ // Per-message error at send time — receipt phase won't see this one.+ // Common cases: bad token format that slipped past isExpoPushToken,+ // payload too big. Logged but not enough to fail the whole delivery.+ log(+ 'Send-time error for token=%s: %s (%s)',+ expoToken,+ ticket.message,+ ticket.details?.error,+ );+ }+ });+ } catch (error) {+ const err = error as { statusCode?: number; message?: string };+ if (err.statusCode === 429) {+ log('Rate limited by Expo Push Service for userId=%s', ctx.userId);+ return { failedReason: 'rate_limited', status: 'failed' };+ }+ // Unrecoverable — let the caller log via Promise.allSettled in NotificationService+ throw error;+ }++ // Throttle between chunks to stay under Expo's 600/sec project limit+ cursor += chunk.length;+ if (cursor < messages.length) {+ await sleep(SEND_CHUNK_THROTTLE_MS);+ }+ }++ if (ticketRecords.length === 0) {+ return { failedReason: 'all_send_failed', status: 'failed' };+ }++ return {+ // TODO: tracking each (ticketId, expoToken) inline keeps deliveries+ // self-contained but couples PushChannel to processPushReceipts. Migrate+ // to a dedicated push_tickets table if we ever need cross-delivery joins.+ providerMessageId: JSON.stringify(ticketRecords),+ status: 'sent',+ };+ }+}diff --git a/src/server/services/push/__tests__/PushChannel.test.ts b/src/server/services/push/__tests__/PushChannel.test.tsnew file mode 100644index 00000000000..d493b5b5dbd--- /dev/null+++ b/src/server/services/push/__tests__/PushChannel.test.ts@@ -0,0 +1,166 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { PushChannel } from '../PushChannel';+import type { PushDeliveryContext, PushTicketRecord } from '../types';++const mockListByUserId = vi.fn();++vi.mock('@/database/models/pushToken', () => ({+ PushTokenModel: vi.fn(() => ({+ listByUserId: mockListByUserId,+ })),+}));++vi.mock('@/database/server', () => ({ serverDB: {} }));++const ctx: PushDeliveryContext = {+ actionUrl: '/image?topic=t1',+ content: 'Your image is ready.',+ notificationId: 'notif-1',+ title: 'Image Generated',+ userId: 'user-1',+};++const makeExpoMock = (overrides: Partial<any> = {}) => ({+ chunkPushNotifications: (msgs: any[]) => [msgs],+ chunkPushNotificationReceiptIds: (ids: string[]) => [ids],+ isExpoPushToken: (t: string) => t.startsWith('ExponentPushToken['),+ sendPushNotificationsAsync: vi.fn(),+ ...overrides,+});++describe('PushChannel', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('returns no_tokens when the user has no push_tokens row', async () => {+ mockListByUserId.mockResolvedValueOnce([]);++ const expo = makeExpoMock();+ const channel = new PushChannel(expo as any);++ const result = await channel.deliver(ctx);++ expect(result).toEqual({ failedReason: 'no_tokens', status: 'failed' });+ expect(expo.sendPushNotificationsAsync).not.toHaveBeenCalled();+ });++ it('returns invalid_tokens when all stored tokens are malformed', async () => {+ mockListByUserId.mockResolvedValueOnce([+ { deviceId: 'a', expoToken: 'not-a-real-token' },+ { deviceId: 'b', expoToken: 'also-bad' },+ ]);++ const expo = makeExpoMock({+ isExpoPushToken: () => false,+ });+ const channel = new PushChannel(expo as any);++ const result = await channel.deliver(ctx);+ expect(result.status).toBe('failed');+ expect(result.failedReason).toBe('invalid_tokens');+ });++ it('sends one Expo message per token and embeds ticket→token mapping', async () => {+ mockListByUserId.mockResolvedValueOnce([+ { deviceId: 'iphone', expoToken: 'ExponentPushToken[A]' },+ { deviceId: 'pixel', expoToken: 'ExponentPushToken[B]' },+ ]);++ const expo = makeExpoMock();+ expo.sendPushNotificationsAsync.mockResolvedValueOnce([+ { id: 'ticket-1', status: 'ok' },+ { id: 'ticket-2', status: 'ok' },+ ]);++ const channel = new PushChannel(expo as any);+ const result = await channel.deliver(ctx);++ expect(result.status).toBe('sent');+ const records = JSON.parse(result.providerMessageId!) as PushTicketRecord[];+ expect(records).toEqual([+ { expoToken: 'ExponentPushToken[A]', ticketId: 'ticket-1' },+ { expoToken: 'ExponentPushToken[B]', ticketId: 'ticket-2' },+ ]);++ const sentMessages = expo.sendPushNotificationsAsync.mock.calls[0][0];+ expect(sentMessages).toHaveLength(2);+ expect(sentMessages[0]).toMatchObject({+ body: ctx.content,+ channelId: 'default',+ data: { notificationId: 'notif-1', url: '/image?topic=t1' },+ priority: 'high',+ sound: 'default',+ title: ctx.title,+ to: 'ExponentPushToken[A]',+ });+ });++ it('drops send-time errors but still returns sent if at least one ticket succeeded', async () => {+ mockListByUserId.mockResolvedValueOnce([+ { deviceId: 'a', expoToken: 'ExponentPushToken[A]' },+ { deviceId: 'b', expoToken: 'ExponentPushToken[B]' },+ ]);++ const expo = makeExpoMock();+ expo.sendPushNotificationsAsync.mockResolvedValueOnce([+ { id: 'ticket-1', status: 'ok' },+ {+ details: { error: 'DeviceNotRegistered' },+ message: 'token-b dead',+ status: 'error',+ },+ ]);++ const channel = new PushChannel(expo as any);+ const result = await channel.deliver(ctx);++ expect(result.status).toBe('sent');+ const records = JSON.parse(result.providerMessageId!) as PushTicketRecord[];+ expect(records).toEqual([{ expoToken: 'ExponentPushToken[A]', ticketId: 'ticket-1' }]);+ });++ it('returns all_send_failed when every ticket fails at send time', async () => {+ mockListByUserId.mockResolvedValueOnce([{ deviceId: 'a', expoToken: 'ExponentPushToken[A]' }]);++ const expo = makeExpoMock();+ expo.sendPushNotificationsAsync.mockResolvedValueOnce([+ {+ details: { error: 'DeviceNotRegistered' },+ message: 'dead',+ status: 'error',+ },+ ]);++ const channel = new PushChannel(expo as any);+ const result = await channel.deliver(ctx);++ expect(result.status).toBe('failed');+ expect(result.failedReason).toBe('all_send_failed');+ });++ it('returns rate_limited on 429 without throwing', async () => {+ mockListByUserId.mockResolvedValueOnce([{ deviceId: 'a', expoToken: 'ExponentPushToken[A]' }]);++ const expo = makeExpoMock();+ expo.sendPushNotificationsAsync.mockRejectedValueOnce(+ Object.assign(new Error('rate'), { statusCode: 429 }),+ );++ const channel = new PushChannel(expo as any);+ const result = await channel.deliver(ctx);++ expect(result).toEqual({ failedReason: 'rate_limited', status: 'failed' });+ });++ it('rethrows non-429 send errors so NotificationService can log', async () => {+ mockListByUserId.mockResolvedValueOnce([{ deviceId: 'a', expoToken: 'ExponentPushToken[A]' }]);++ const expo = makeExpoMock();+ expo.sendPushNotificationsAsync.mockRejectedValueOnce(new Error('network down'));++ const channel = new PushChannel(expo as any);+ await expect(channel.deliver(ctx)).rejects.toThrow('network down');+ });+});diff --git a/src/server/services/push/__tests__/processPushReceipts.test.ts b/src/server/services/push/__tests__/processPushReceipts.test.tsnew file mode 100644index 00000000000..0718f8eaf0f--- /dev/null+++ b/src/server/services/push/__tests__/processPushReceipts.test.ts@@ -0,0 +1,209 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { processPushReceipts } from '../processPushReceipts';++const mockDeleteByExpoTokens = vi.fn();++vi.mock('@/database/models/pushToken', () => ({+ deletePushTokensByExpoTokens: (...args: unknown[]) => mockDeleteByExpoTokens(...args),+}));++vi.mock('@/database/schemas/notification', () => ({+ notificationDeliveries: {+ channel: { name: 'channel' },+ id: { name: 'id' },+ sentAt: { name: 'sent_at' },+ status: { name: 'status' },+ },+}));++/**+ * Minimal fake db that records `.update().set().where()` chains and lets+ * us inspect what processPushReceipts attempted to write.+ */+function fakeDb(pendingRows: any[]) {+ const updates: Array<{ set: any }> = [];++ const db = {+ delete: vi.fn(() => ({ where: vi.fn().mockResolvedValue(undefined) })),+ select: vi.fn(() => ({+ from: () => ({+ where: () => Promise.resolve(pendingRows),+ }),+ })),+ update: vi.fn(() => ({+ set: (s: any) => {+ updates.push({ set: s });+ return { where: vi.fn().mockResolvedValue(undefined) };+ },+ })),+ };++ return { db, updates };+}++function fakeExpo(receipts: Record<string, any>) {+ return {+ chunkPushNotificationReceiptIds: (ids: string[]) => [ids],+ getPushNotificationReceiptsAsync: vi.fn().mockResolvedValue(receipts),+ };+}++describe('processPushReceipts', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('returns zeros when there are no pending deliveries', async () => {+ const { db } = fakeDb([]);+ const expo = fakeExpo({});++ const result = await processPushReceipts(db as any, { expoClient: expo as any });++ expect(result.processed).toBe(0);+ expect(expo.getPushNotificationReceiptsAsync).not.toHaveBeenCalled();+ });++ it('marks delivery as delivered when all tickets are ok', async () => {+ const { db, updates } = fakeDb([+ {+ id: 'd1',+ providerMessageId: JSON.stringify([+ { expoToken: 'ExponentPushToken[A]', ticketId: 't1' },+ { expoToken: 'ExponentPushToken[B]', ticketId: 't2' },+ ]),+ },+ ]);+ const expo = fakeExpo({+ t1: { status: 'ok' },+ t2: { status: 'ok' },+ });++ const result = await processPushReceipts(db as any, { expoClient: expo as any });++ expect(result.deliveriesUpdated).toBe(1);+ expect(updates[0].set).toEqual({ status: 'delivered' });+ expect(mockDeleteByExpoTokens).toHaveBeenCalledWith(db, []);+ });++ it('marks delivery as failed and queues tokens for deletion on DeviceNotRegistered', async () => {+ const { db, updates } = fakeDb([+ {+ id: 'd1',+ providerMessageId: JSON.stringify([+ { expoToken: 'ExponentPushToken[A]', ticketId: 't1' },+ { expoToken: 'ExponentPushToken[B]', ticketId: 't2' },+ ]),+ },+ ]);+ const expo = fakeExpo({+ t1: { details: { error: 'DeviceNotRegistered' }, message: 'gone', status: 'error' },+ t2: { status: 'ok' },+ });++ const result = await processPushReceipts(db as any, { expoClient: expo as any });++ expect(result.deliveriesUpdated).toBe(1);+ expect(result.invalidTokensDeleted).toBe(1);+ expect(updates[0].set.status).toBe('failed');+ expect(updates[0].set.failedReason).toContain('DeviceNotRegistered');+ expect(mockDeleteByExpoTokens).toHaveBeenCalledWith(db, ['ExponentPushToken[A]']);+ });++ it('aggregates distinct error reasons per delivery', async () => {+ const { db, updates } = fakeDb([+ {+ id: 'd1',+ providerMessageId: JSON.stringify([+ { expoToken: 'ExponentPushToken[A]', ticketId: 't1' },+ { expoToken: 'ExponentPushToken[B]', ticketId: 't2' },+ ]),+ },+ ]);+ const expo = fakeExpo({+ t1: { details: { error: 'DeviceNotRegistered' }, status: 'error' },+ t2: { details: { error: 'MessageRateExceeded' }, status: 'error' },+ });++ await processPushReceipts(db as any, { expoClient: expo as any });++ expect(updates[0].set.failedReason).toBe('DeviceNotRegistered,MessageRateExceeded');+ });++ it('leaves delivery in sent state when Expo has not returned any receipts yet', async () => {+ const { db, updates } = fakeDb([+ {+ id: 'd1',+ providerMessageId: JSON.stringify([{ expoToken: 'ExponentPushToken[A]', ticketId: 't1' }]),+ },+ ]);+ // No receipts available yet+ const expo = fakeExpo({});++ const result = await processPushReceipts(db as any, { expoClient: expo as any });++ expect(result.deliveriesUpdated).toBe(0);+ expect(updates).toHaveLength(0);+ });++ it('leaves delivery in sent state when only some tickets have receipts', async () => {+ // Two tickets, only t1 has a receipt. We must NOT finalize the delivery+ // as 'delivered' — t2 might come back as DeviceNotRegistered later, and+ // skipping reconciliation would leak the invalid token.+ const { db, updates } = fakeDb([+ {+ id: 'd1',+ providerMessageId: JSON.stringify([+ { expoToken: 'ExponentPushToken[A]', ticketId: 't1' },+ { expoToken: 'ExponentPushToken[B]', ticketId: 't2' },+ ]),+ },+ ]);+ const expo = fakeExpo({ t1: { status: 'ok' } });++ const result = await processPushReceipts(db as any, { expoClient: expo as any });++ expect(result.deliveriesUpdated).toBe(0);+ expect(updates).toHaveLength(0);+ });++ it('skips malformed providerMessageId without failing the whole run', async () => {+ const { db, updates } = fakeDb([+ { id: 'd-bad', providerMessageId: 'not-json' },+ {+ id: 'd-good',+ providerMessageId: JSON.stringify([{ expoToken: 'ExponentPushToken[A]', ticketId: 't1' }]),+ },+ ]);+ const expo = fakeExpo({ t1: { status: 'ok' } });++ const result = await processPushReceipts(db as any, { expoClient: expo as any });++ expect(result.skippedMalformed).toBe(1);+ expect(result.deliveriesUpdated).toBe(1);+ expect(updates).toHaveLength(1);+ });++ it('dedupes invalid tokens across multiple deliveries', async () => {+ const sharedToken = 'ExponentPushToken[X]';+ const { db } = fakeDb([+ {+ id: 'd1',+ providerMessageId: JSON.stringify([{ expoToken: sharedToken, ticketId: 't1' }]),+ },+ {+ id: 'd2',+ providerMessageId: JSON.stringify([{ expoToken: sharedToken, ticketId: 't2' }]),+ },+ ]);+ const expo = fakeExpo({+ t1: { details: { error: 'DeviceNotRegistered' }, status: 'error' },+ t2: { details: { error: 'DeviceNotRegistered' }, status: 'error' },+ });++ const result = await processPushReceipts(db as any, { expoClient: expo as any });++ expect(result.invalidTokensDeleted).toBe(1);+ expect(mockDeleteByExpoTokens).toHaveBeenCalledWith(db, [sharedToken]);+ });+});diff --git a/src/server/services/push/constants.ts b/src/server/services/push/constants.tsnew file mode 100644index 00000000000..a02b9259f16--- /dev/null+++ b/src/server/services/push/constants.ts@@ -0,0 +1,6 @@+/**+ * Default Android notification channel id. Must match the channel the mobile+ * client creates via `Notifications.setNotificationChannelAsync`; otherwise+ * Android silently drops the notification.+ */+export const DEFAULT_PUSH_CHANNEL_ID = 'default';diff --git a/src/server/services/push/processPushReceipts.ts b/src/server/services/push/processPushReceipts.tsnew file mode 100644index 00000000000..fea892df688--- /dev/null+++ b/src/server/services/push/processPushReceipts.ts@@ -0,0 +1,207 @@+import debug from 'debug';+import { and, eq, gt, lt } from 'drizzle-orm';+import { Expo } from 'expo-server-sdk';++import { deletePushTokensByExpoTokens } from '@/database/models/pushToken';+import { notificationDeliveries } from '@/database/schemas/notification';+import type { LobeChatDatabase } from '@/database/type';++import type { PushTicketRecord } from './types';++const log = debug('lobe-notification:push-receipts');++/** Expo retains receipts for at most 24h after send */+const RECEIPT_LOOKBACK_HOURS = 24;+/** Wait at least this long after send for a meaningful receipt status */+const RECEIPT_MIN_AGE_MINUTES = 15;++interface ProcessReceiptsOptions {+ /** Override the Expo client (used by tests) */+ expoClient?: Expo;+ /**+ * Wait window: only process deliveries sent between [now - lookbackHours, now - minAgeMinutes].+ * Defaults align with Expo's receipt retention + recommended polling cadence.+ */+ lookbackHours?: number;+ minAgeMinutes?: number;+}++export interface ProcessReceiptsResult {+ deliveriesUpdated: number;+ invalidTokensDeleted: number;+ processed: number;+ skippedMalformed: number;+}++/**+ * Receipt reconciliation worker. Designed to be called from a Vercel cron+ * route (in cloud), but is pure with respect to its inputs — pass any+ * `LobeChatDatabase` instance and it works (including in tests).+ *+ * Steps:+ * 1. Find recent `push` deliveries still in `sent` state+ * 2. Decode their `providerMessageId` (JSON `[{ ticketId, expoToken }, ...]`)+ * 3. Ask Expo for the receipts in bulk (chunked)+ * 4. Update each delivery:+ * - all tickets ok → `delivered`+ * - any ticket error → `failed` (failedReason aggregated)+ * 5. Tokens whose receipt says `DeviceNotRegistered` are removed from `push_tokens`+ */+export async function processPushReceipts(+ db: LobeChatDatabase,+ options: ProcessReceiptsOptions = {},+): Promise<ProcessReceiptsResult> {+ const {+ expoClient,+ lookbackHours = RECEIPT_LOOKBACK_HOURS,+ minAgeMinutes = RECEIPT_MIN_AGE_MINUTES,+ } = options;+ const expo = expoClient ?? new Expo();++ const now = Date.now();+ const lookbackFloor = new Date(now - lookbackHours * 60 * 60 * 1000);+ const minAgeCeiling = new Date(now - minAgeMinutes * 60 * 1000);++ const pending = await db+ .select({+ id: notificationDeliveries.id,+ providerMessageId: notificationDeliveries.providerMessageId,+ })+ .from(notificationDeliveries)+ .where(+ and(+ eq(notificationDeliveries.channel, 'push'),+ eq(notificationDeliveries.status, 'sent'),+ gt(notificationDeliveries.sentAt, lookbackFloor),+ lt(notificationDeliveries.sentAt, minAgeCeiling),+ ),+ );++ log('Found %d pending push deliveries to reconcile', pending.length);++ if (pending.length === 0) {+ return {+ deliveriesUpdated: 0,+ invalidTokensDeleted: 0,+ processed: 0,+ skippedMalformed: 0,+ };+ }++ // ticketId → { deliveryId, expoToken }+ const ticketLookup = new Map<string, { deliveryId: string; expoToken: string }>();+ // deliveryId → list of (ticketId) for aggregation+ const deliveryTickets = new Map<string, string[]>();+ let skippedMalformed = 0;++ for (const d of pending) {+ if (!d.providerMessageId) continue;++ let records: PushTicketRecord[];+ try {+ records = JSON.parse(d.providerMessageId) as PushTicketRecord[];+ if (!Array.isArray(records)) throw new Error('not an array');+ } catch (error) {+ log('Malformed providerMessageId on delivery %s: %O', d.id, error);+ skippedMalformed += 1;+ continue;+ }++ deliveryTickets.set(d.id, []);+ for (const r of records) {+ if (!r || typeof r.ticketId !== 'string' || typeof r.expoToken !== 'string') continue;+ ticketLookup.set(r.ticketId, { deliveryId: d.id, expoToken: r.expoToken });+ deliveryTickets.get(d.id)!.push(r.ticketId);+ }+ }++ if (ticketLookup.size === 0) {+ return {+ deliveriesUpdated: 0,+ invalidTokensDeleted: 0,+ processed: pending.length,+ skippedMalformed,+ };+ }++ // ticketId → 'ok' | { error: string; message?: string }+ const ticketOutcome = new Map<+ string,+ { error?: string; message?: string; status: 'error' | 'ok' }+ >();+ const ticketIds = [...ticketLookup.keys()];+ const chunks = expo.chunkPushNotificationReceiptIds(ticketIds);++ const receiptChunks = await Promise.all(+ chunks.map((chunk) => expo.getPushNotificationReceiptsAsync(chunk)),+ );+ for (const receipts of receiptChunks) {+ for (const [ticketId, receipt] of Object.entries(receipts)) {+ if (receipt.status === 'ok') {+ ticketOutcome.set(ticketId, { status: 'ok' });+ } else {+ ticketOutcome.set(ticketId, {+ error: receipt.details?.error,+ message: receipt.message,+ status: 'error',+ });+ }+ }+ }++ const invalidTokens = new Set<string>();+ const updateTasks: Promise<unknown>[] = [];++ for (const [deliveryId, tickets] of deliveryTickets) {+ const outcomes = tickets.map((id) => ticketOutcome.get(id));+ const pendingCount = outcomes.filter((o) => o === undefined).length;+ const errors = outcomes.filter((o) => o?.status === 'error');++ // Leave the delivery in 'sent' if any ticket still has no receipt — finalizing+ // now would lose visibility into later error receipts (e.g. DeviceNotRegistered)+ // and skip cleanup of invalid tokens.+ if (pendingCount > 0) continue;++ if (errors.length === 0) {+ updateTasks.push(+ db+ .update(notificationDeliveries)+ .set({ status: 'delivered' })+ .where(eq(notificationDeliveries.id, deliveryId)),+ );+ } else {+ for (const ticketId of tickets) {+ const o = ticketOutcome.get(ticketId);+ if (o?.status === 'error' && o.error === 'DeviceNotRegistered') {+ invalidTokens.add(ticketLookup.get(ticketId)!.expoToken);+ }+ }+ const reason = [...new Set(errors.map((e) => e!.error ?? e!.message ?? 'unknown'))].join(',');+ updateTasks.push(+ db+ .update(notificationDeliveries)+ .set({ failedReason: reason, status: 'failed' })+ .where(eq(notificationDeliveries.id, deliveryId)),+ );+ }+ }++ await Promise.all(updateTasks);+ const deliveriesUpdated = updateTasks.length;++ await deletePushTokensByExpoTokens(db, [...invalidTokens]);++ log(+ 'Reconciliation done: processed=%d updated=%d invalidTokens=%d',+ pending.length,+ deliveriesUpdated,+ invalidTokens.size,+ );++ return {+ deliveriesUpdated,+ invalidTokensDeleted: invalidTokens.size,+ processed: pending.length,+ skippedMalformed,+ };+}diff --git a/src/server/services/push/types.ts b/src/server/services/push/types.tsnew file mode 100644index 00000000000..d405b4b1d99--- /dev/null+++ b/src/server/services/push/types.ts@@ -0,0 +1,42 @@+/**+ * Push notification channel contract.+ *+ * Structurally compatible with cloud's `NotificationChannel` interface so+ * cloud can register `PushChannel` directly into its `channelInstances` map+ * without any cast (TypeScript structural typing).+ *+ * Self-host (OSS-only) callers can also instantiate `PushChannel` directly+ * and call `.deliver(ctx)` with a minimal context — `userEmail` is accepted+ * but ignored by the push implementation.+ */+export interface PushDeliveryContext {+ /** URL to navigate to when user taps the notification (sent as `data.url`) */+ actionUrl?: string;+ /** Notification body text */+ content: string;+ /** Underlying notifications.id — sent as `data.notificationId` for tracing */+ notificationId: string;+ /** Notification title */+ title: string;+ /** Ignored by push (kept for cloud `NotificationChannel` compatibility) */+ userEmail?: string;+ /** Target user — push channel fans out to all of this user's `push_tokens` */+ userId: string;+}++export interface PushDeliveryResult {+ failedReason?: string;+ /**+ * JSON-encoded `[{ ticketId, expoToken }, ...]` so the receipt cron can+ * map ticket IDs back to the originating token (for invalid-token cleanup).+ * `undefined` when nothing was sent (e.g. `no_tokens`).+ */+ providerMessageId?: string;+ status: 'delivered' | 'failed' | 'sent';+}++/** Persisted (ticketId → expoToken) mapping shape, embedded in providerMessageId */+export interface PushTicketRecord {+ expoToken: string;+ ticketId: string;+}