You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add the notification persistence service and authenticated Inbox API #1717
The mobile Inbox needs a stable API for listing, counting, reading, and dismissing notification events. These operations must be authenticated and must never trust a user identifier supplied by the browser.
Requirements
Add a core notification service for idempotent event creation and paginated listing.
Join per-user receipts into list results.
Exclude dismissed items by default while allowing an explicit historical query.
Add authenticated routes for list, unread count, mark-read, and dismiss.
Use cursor pagination based on occurred_at plus event ID.
Clamp request limits to avoid unbounded database reads.
Marking or dismissing an event must be idempotent.
Do not expose notification data through demo-mode write exceptions; list/count remain readable while mutations follow existing demo-mode middleware policy.
Acceptance Criteria
GET /api/notifications returns newest-first items and an unread count.
GET /api/notifications/unread-count returns the same count used by icon badging.
POST /api/notifications/:id/read and /dismiss affect only the authenticated user's receipt.
A different authenticated user does not inherit another user's read/dismiss state.
Invalid cursors and limits return 400 rather than causing SQL errors.
Duplicate event creation returns the original event ID.
Keep SQL and row parsing in packages/core, while Express is responsible only for authentication, input validation, and HTTP status mapping. This keeps notification semantics reusable by the push dispatcher and CLI in the future. Offset pagination was considered but rejected because new events arriving during scrolling would move rows and cause duplicates; a stable timestamp/ID cursor avoids that behavior.
File: packages/core/src/services/notificationService.ts (new file)
Why this file: This is the single persistence boundary for event creation and per-user Inbox state. Push delivery and API routes will reuse it instead of duplicating SQL.
import{randomUUID}from'node:crypto';import{db}from'../db/connection.js';importtype{NotificationAction,NotificationCategory,NotificationEvent,NotificationKind,NotificationTargetType,}from'@propr/shared';exportinterfaceCreateNotificationEventInput{kind: NotificationKind;category: NotificationCategory;title: string;body: string;targetType: NotificationTargetType;targetId: string;projectSlug?: string|null;deepLink: string;prUrl?: string|null;actions?: NotificationAction[];metadata?: Record<string,unknown>;dedupeKey: string;occurredAt?: string;}interfaceNotificationRow{id: string;kind: NotificationKind;category: NotificationCategory;title: string;body: string;target_type: NotificationTargetType;target_id: string;project_slug: string|null;deep_link: string;pr_url: string|null;actions_json: string;metadata_json: string;occurred_at: string;read_at: string|null;dismissed_at: string|null;}constsafeJson=<T>(value: string,fallback: T): T=>{try{returnJSON.parse(value)asT;}catch{// Old or manually edited rows must not make the entire Inbox unavailable.returnfallback;}};consttoEvent=(row: NotificationRow): NotificationEvent=>({id: row.id,kind: row.kind,category: row.category,title: row.title,body: row.body,targetType: row.target_type,targetId: row.target_id,projectSlug: row.project_slug,deepLink: row.deep_link,prUrl: row.pr_url,actions: safeJson<NotificationAction[]>(row.actions_json,[]),metadata: safeJson<Record<string,unknown>>(row.metadata_json,{}),occurredAt: row.occurred_at,readAt: row.read_at,dismissedAt: row.dismissed_at,});exportasyncfunctioncreateNotificationEvent(input: CreateNotificationEventInput): Promise<string>{constexisting=awaitdb('notification_events').select('id').where({dedupe_key: input.dedupeKey}).first<{id: string}>();if(existing)returnexisting.id;constid=randomUUID();constnow=newDate().toISOString();try{awaitdb('notification_events').insert({
id,kind: input.kind,category: input.category,title: input.title,body: input.body,target_type: input.targetType,target_id: input.targetId,project_slug: input.projectSlug??null,deep_link: input.deepLink,pr_url: input.prUrl??null,actions_json: JSON.stringify(input.actions??[]),metadata_json: JSON.stringify(input.metadata??{}),dedupe_key: input.dedupeKey,occurred_at: input.occurredAt??now,created_at: now,});returnid;}catch(error){// Two workers can observe the same transition concurrently. The unique key// decides the winner; return it instead of surfacing a false failure.constraced=awaitdb('notification_events').select('id').where({dedupe_key: input.dedupeKey}).first<{id: string}>();if(raced)returnraced.id;throwerror;}}exportinterfaceListNotificationOptions{limit: number;cursor?: {occurredAt: string;id: string};includeDismissed?: boolean;}exportasyncfunctionlistNotifications(userId: string,options: ListNotificationOptions){constquery=db('notification_events as event').leftJoin('notification_receipts as receipt',functionjoinReceipt(){this.on('receipt.event_id','=','event.id').andOnVal('receipt.user_id','=',userId);}).select('event.*','receipt.read_at','receipt.dismissed_at',).orderBy('event.occurred_at','desc').orderBy('event.id','desc').limit(options.limit+1);if(!options.includeDismissed)query.whereNull('receipt.dismissed_at');if(options.cursor){query.where(builder=>{builder.where('event.occurred_at','<',options.cursor!.occurredAt).orWhere(inner=>inner.where('event.occurred_at','=',options.cursor!.occurredAt).andWhere('event.id','<',options.cursor!.id));});}constrows=awaitqueryasNotificationRow[];consthasMore=rows.length>options.limit;constvisible=rows.slice(0,options.limit).map(toEvent);constlast=visible[visible.length-1];return{notifications: visible,unreadCount: awaitgetUnreadNotificationCount(userId),nextCursor: hasMore&&last
? Buffer.from(JSON.stringify({occurredAt: last.occurredAt,id: last.id})).toString('base64url')
: null,};}exportasyncfunctiongetUnreadNotificationCount(userId: string): Promise<number>{constrow=awaitdb('notification_events as event').leftJoin('notification_receipts as receipt',functionjoinReceipt(){this.on('receipt.event_id','=','event.id').andOnVal('receipt.user_id','=',userId);}).whereNull('receipt.read_at').whereNull('receipt.dismissed_at').count<{count: number|string}[]>({count: 'event.id'}).first();returnNumber(row?.count??0);}asyncfunctionupdateReceipt(userId: string,eventId: string,values: Record<string,string>): Promise<boolean>{constexists=awaitdb('notification_events').where({id: eventId}).first('id');if(!exists)returnfalse;awaitdb('notification_receipts').insert({event_id: eventId,user_id: userId, ...values}).onConflict(['event_id','user_id']).merge(values);returntrue;}exportconstmarkNotificationRead=(userId: string,eventId: string)=>updateReceipt(userId,eventId,{read_at: newDate().toISOString()});exportconstdismissNotification=(userId: string,eventId: string)=>{constnow=newDate().toISOString();// Dismissal also marks the item read so the badge cannot remain inflated.returnupdateReceipt(userId,eventId,{read_at: now,dismissed_at: now});};
File: packages/core/src/index.ts
Why this file: API and delivery packages consume core services through the public barrel.
--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1,3 +1,11 @@+export {+ createNotificationEvent,+ listNotifications,+ getUnreadNotificationCount,+ markNotificationRead,+ dismissNotification,+} from './services/notificationService.js';+export type { CreateNotificationEventInput, ListNotificationOptions } from './services/notificationService.js';
File: packages/api/routes/notifications.ts (new file)
Why this file: This route translates authenticated HTTP requests into the core service calls. The user ID is derived from the session, never from query or body data.
import{Router,typeRequest,typeResponse}from'express';import{dismissNotification,listNotifications,getUnreadNotificationCount,markNotificationRead,}from'@propr/core';constrouter=Router();typeAuthenticatedRequest=Request&{user?: {id?: string|number;login?: string};};constuserIdFor=(request: Request): string|null=>{constuser=(requestasAuthenticatedRequest).user;// Prefer the immutable provider ID; login is retained for compatibility with// existing session shapes until every deployment has refreshed its session.returnuser?.id!==undefined ? String(user.id) : user?.login??null;};constrequireUser=(request: Request,response: Response): string|null=>{constuserId=userIdFor(request);if(!userId)response.status(401).json({error: 'Authentication required'});returnuserId;};constparseCursor=(value: unknown): {occurredAt: string;id: string}|undefined=>{if(!value)returnundefined;constparsed=JSON.parse(Buffer.from(String(value),'base64url').toString('utf8'))asRecord<string,unknown>;if(typeofparsed.occurredAt!=='string'||typeofparsed.id!=='string'){thrownewError('Invalid cursor');}return{occurredAt: parsed.occurredAt,id: parsed.id};};router.get('/',async(request,response,next)=>{try{constuserId=requireUser(request,response);if(!userId)return;constrequestedLimit=Number(request.query.limit??30);if(!Number.isInteger(requestedLimit)||requestedLimit<1){response.status(400).json({error: 'limit must be a positive integer'});return;}response.json(awaitlistNotifications(userId,{limit: Math.min(requestedLimit,100),cursor: parseCursor(request.query.cursor),includeDismissed: request.query.includeDismissed==='true',}));}catch(error){if((errorasError).message==='Invalid cursor'){response.status(400).json({error: 'Invalid notification cursor'});return;}next(error);}});router.get('/unread-count',async(request,response,next)=>{try{constuserId=requireUser(request,response);if(!userId)return;response.json({unreadCount: awaitgetUnreadNotificationCount(userId)});}catch(error){next(error);}});for(const[path,operation]of[['read',markNotificationRead],['dismiss',dismissNotification],]asconst){router.post(`/:id/${path}`,async(request,response,next)=>{try{constuserId=requireUser(request,response);if(!userId)return;constupdated=awaitoperation(userId,request.params.id);if(!updated){response.status(404).json({error: 'Notification not found'});return;}response.json({success: true,unreadCount: awaitgetUnreadNotificationCount(userId)});}catch(error){next(error);}});}exportdefaultrouter;
File: packages/api/server.ts
Why this file: The new router must be mounted behind the same session and demo-mode middleware used by existing authenticated API routes.
--- a/packages/api/server.ts+++ b/packages/api/server.ts@@ -1,5 +1,6 @@+import notificationRoutes from './routes/notifications.js';@@ -120,6 +121,9 @@+// Mount after authentication so notification receipt mutations can only use+// the server-verified session identity.+app.use('/api/notifications', notificationRoutes);
Activity
propr-dev commentedon Aug 2, 2026
Suggested Implementation:
Implementation Approach
Keep SQL and row parsing in
packages/core, while Express is responsible only for authentication, input validation, and HTTP status mapping. This keeps notification semantics reusable by the push dispatcher and CLI in the future. Offset pagination was considered but rejected because new events arriving during scrolling would move rows and cause duplicates; a stable timestamp/ID cursor avoids that behavior.File:
packages/core/src/services/notificationService.ts(new file)Why this file: This is the single persistence boundary for event creation and per-user Inbox state. Push delivery and API routes will reuse it instead of duplicating SQL.
File:
packages/core/src/index.tsWhy this file: API and delivery packages consume core services through the public barrel.
File:
packages/api/routes/notifications.ts(new file)Why this file: This route translates authenticated HTTP requests into the core service calls. The user ID is derived from the session, never from query or body data.
File:
packages/api/server.tsWhy this file: The new router must be mounted behind the same session and demo-mode middleware used by existing authenticated API routes.
propr-dev commentedon Aug 2, 2026
🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.
I'll analyze the problem and work on a solution. This may take a few minutes.
Processing Details:
codexgpt-5.6-sol1717/gpt-5.6-sol-add-the-notification-pers-20260802-1128-zjd1716-epic-failed-to-3m8issue-1717-20260802-1128-gpt-5.6-sol-zjd🔍 Track Task Execution
fix(ai): Resolve issue #1717 - Add the notification persistence servi…
fix(ai): Resolve issue #1717 - Add the notification persistence servi…
[Epic] PWA & Web push (#1731)