Implement tasks 40, 41, 42: web push, notification bus, reminders engine

Task 40 — Web Push (VAPID):
- Add web-push package + @types/web-push
- pnpm vapid:generate script prints VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, NEXT_PUBLIC_VAPID_PUBLIC_KEY
- push_subscriptions schema + migration 0013
- _core/push.ts: sendPush() iterates subscriptions, prunes 404/410 stale entries
- SW push/notificationclick event handlers added to generated sw.js template
- PushOptIn client component on /settings (opt-in, disable, send test)

Task 42 — Notification bus + ntfy adapter:
- notifications table + notif_push/notif_inapp/notif_ntfy user columns (migration 0013)
- _core/notify.ts: notify() fans out to push, in-app DB, and optional ntfy POST
- NotificationBell server component in AppNav: unread badge, dropdown inbox, mark-read
- NotifyChannelToggles client component in /settings

Task 41 — Reminders engine:
- fired_at + created_by added to reminders; default channel changed to 'auto'
- _core/reminders.ts: scheduleReminder (upsert), cancelReminder, listReminders, tickReminders
- tickReminders uses pg_try_advisory_xact_lock for horizontal-scale safety
- src/instrumentation.ts starts reminder worker (30s tick) on Node.js boot
- Notes actions use scheduleReminder/cancelReminder instead of raw SQL
- Calendar createEvent: optional remindMinutesBefore, deleteEvent: cancelReminder
- Calendar-shell: "Remind me 30 min before" checkbox on new event form

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
ginnoir
2026-05-06 16:55:02 -05:00
co-authored by Claude Sonnet 4.6
parent ec20f1bc87
commit b6abe052c9
25 changed files with 986 additions and 85 deletions
+3
View File
@@ -15,3 +15,6 @@ export type { QuickAddItem, SerializedQuickAddItem, SerializedWidgetMeta } from
export { logActivity, logShareActivity } from "./activity";
export { createShareLink, resolveShareToken, revokeShareLink } from "./share";
export type { ShareLinkCapabilities, CreateShareLinkResult } from "./share";
export { sendPush } from "./push";
export { notify } from "./notify";
export { scheduleReminder, cancelReminder, listReminders, startReminderWorker } from "./reminders";
+52
View File
@@ -0,0 +1,52 @@
import { eq } from "drizzle-orm";
import { db } from "@/lib/db";
import { notifications, users } from "./schema";
import { sendPush } from "./push";
type NotifyPayload = {
title: string;
body: string;
url?: string;
channels?: ("push" | "inapp" | "ntfy")[];
};
export async function notify(userId: string, payload: NotifyPayload) {
const channels = payload.channels ?? ["push", "inapp"];
const [user] = await db
.select({ notifPush: users.notifPush, notifInApp: users.notifInApp, notifNtfy: users.notifNtfy })
.from(users)
.where(eq(users.id, userId))
.limit(1);
if (!user) return;
const pushEnabled = process.env["VAPID_PUBLIC_KEY"] && process.env["VAPID_PRIVATE_KEY"];
if (channels.includes("push") && user.notifPush && pushEnabled) {
await sendPush(userId, payload).catch((err) =>
console.error("[famapp] push channel failed:", err),
);
}
if (channels.includes("inapp") && user.notifInApp) {
await db.insert(notifications).values({
userId,
title: payload.title,
body: payload.body,
url: payload.url,
});
}
if (channels.includes("ntfy") && user.notifNtfy) {
const ntfyUrl = process.env["NTFY_URL"];
const ntfyTopic = process.env["NTFY_TOPIC"];
if (ntfyUrl && ntfyTopic) {
await fetch(`${ntfyUrl}/${ntfyTopic}`, {
method: "POST",
headers: { Title: payload.title, "Content-Type": "text/plain" },
body: payload.body,
}).catch((err) => console.error("[famapp] ntfy delivery failed:", err));
}
}
}
+54
View File
@@ -0,0 +1,54 @@
import webPush from "web-push";
import { and, eq, inArray } from "drizzle-orm";
import { db } from "@/lib/db";
import { pushSubscriptions } from "./schema";
function ensureVapidConfigured() {
const subject = process.env["VAPID_SUBJECT"];
const publicKey = process.env["VAPID_PUBLIC_KEY"];
const privateKey = process.env["VAPID_PRIVATE_KEY"];
if (!subject || !publicKey || !privateKey) {
throw new Error("VAPID_SUBJECT, VAPID_PUBLIC_KEY, and VAPID_PRIVATE_KEY must be set");
}
webPush.setVapidDetails(subject, publicKey, privateKey);
}
export async function sendPush(
userId: string,
payload: { title: string; body: string; url?: string },
) {
ensureVapidConfigured();
const subs = await db
.select()
.from(pushSubscriptions)
.where(eq(pushSubscriptions.userId, userId));
if (subs.length === 0) return;
const staleIds: string[] = [];
await Promise.allSettled(
subs.map(async (sub) => {
try {
await webPush.sendNotification(
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
JSON.stringify({ title: payload.title, body: payload.body, url: payload.url ?? "/" }),
);
} catch (err) {
const status = (err as { statusCode?: number }).statusCode;
if (status === 404 || status === 410) {
staleIds.push(sub.id);
} else {
console.error("[famapp] push delivery failed:", err);
}
}
}),
);
if (staleIds.length > 0) {
await db
.delete(pushSubscriptions)
.where(and(eq(pushSubscriptions.userId, userId), inArray(pushSubscriptions.id, staleIds)));
}
}
+99
View File
@@ -0,0 +1,99 @@
import { and, eq, inArray, isNull, lte, sql } from "drizzle-orm";
import { db } from "@/lib/db";
import { reminders } from "./schema";
import { notify } from "./notify";
const REMINDER_LOCK_KEY = 7_777_777;
export async function scheduleReminder(input: {
householdId: string;
entityType: string;
entityId: string;
fireAt: Date;
createdBy: string;
channel?: string;
}) {
await db
.insert(reminders)
.values({
householdId: input.householdId,
entityType: input.entityType,
entityId: input.entityId,
fireAt: input.fireAt,
channel: input.channel ?? "auto",
createdBy: input.createdBy,
firedAt: null,
})
.onConflictDoUpdate({
target: [reminders.entityType, reminders.entityId],
set: { fireAt: input.fireAt, firedAt: null, createdBy: input.createdBy },
});
}
export async function cancelReminder(entityType: string, entityId: string) {
await db
.delete(reminders)
.where(and(eq(reminders.entityType, entityType), eq(reminders.entityId, entityId)));
}
export async function listReminders(entityType: string, entityId: string) {
return db
.select()
.from(reminders)
.where(and(eq(reminders.entityType, entityType), eq(reminders.entityId, entityId)));
}
export async function tickReminders() {
let dueReminders: (typeof reminders.$inferSelect)[] = [];
try {
await db.transaction(async (tx) => {
const lockRows = await tx.execute<{ acquired: boolean }>(
sql`SELECT pg_try_advisory_xact_lock(${REMINDER_LOCK_KEY}) AS acquired`,
);
if (!lockRows[0]?.acquired) return;
const now = new Date();
dueReminders = await tx
.select()
.from(reminders)
.where(and(lte(reminders.fireAt, now), isNull(reminders.firedAt)));
if (dueReminders.length > 0) {
await tx
.update(reminders)
.set({ firedAt: now })
.where(inArray(reminders.id, dueReminders.map((r) => r.id)));
}
});
} catch (err) {
console.error("[famapp] reminder tick error:", err);
return;
}
await Promise.allSettled(
dueReminders.map(async (reminder) => {
if (!reminder.createdBy) return;
try {
await notify(reminder.createdBy, {
title: "Reminder",
body: `You have a reminder`,
url: reminder.entityType === "notes.note" ? `/notes/${reminder.entityId}` : "/",
channels: ["push", "inapp"],
});
} catch (err) {
console.error("[famapp] reminder delivery failed:", reminder.id, err);
}
}),
);
}
let workerTimer: ReturnType<typeof setInterval> | null = null;
export function startReminderWorker() {
if (workerTimer) return;
workerTimer = setInterval(() => {
tickReminders().catch((err) => console.error("[famapp] reminder worker uncaught:", err));
}, 30_000);
console.log("[famapp] reminder worker started (30s tick)");
}
+38 -1
View File
@@ -26,6 +26,9 @@ export const users = pgTable("users", {
theme: text("theme").notNull().default("default"),
themeMode: text("theme_mode").notNull().default("system"),
completionVisibilityHours: integer("completion_visibility_hours").notNull().default(24),
notifPush: boolean("notif_push").notNull().default(true),
notifInApp: boolean("notif_inapp").notNull().default(true),
notifNtfy: boolean("notif_ntfy").notNull().default(false),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
@@ -158,7 +161,9 @@ export const reminders = pgTable(
entityType: text("entity_type").notNull(),
entityId: uuid("entity_id").notNull(),
fireAt: timestamp("fire_at", { withTimezone: true }).notNull(),
channel: text("channel").notNull().default("in_app"),
channel: text("channel").notNull().default("auto"),
firedAt: timestamp("fired_at", { withTimezone: true }),
createdBy: uuid("created_by").references(() => users.id, { onDelete: "set null" }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [
@@ -166,3 +171,35 @@ export const reminders = pgTable(
index("reminders_household_fire_at_idx").on(t.householdId, t.fireAt),
],
);
export const pushSubscriptions = pgTable(
"push_subscriptions",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
endpoint: text("endpoint").notNull().unique(),
p256dh: text("p256dh").notNull(),
auth: text("auth").notNull(),
userAgent: text("user_agent"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("push_subscriptions_user_idx").on(t.userId)],
);
export const notifications = pgTable(
"notifications",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
title: text("title").notNull(),
body: text("body").notNull(),
url: text("url"),
readAt: timestamp("read_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("notifications_user_read_idx").on(t.userId, t.readAt)],
);