Repository navigation
feat(notifications): in-app inbox, realtime, webhooks, web push + shared SMTP core - #136
Conversation
…v1.5 specs Imports the notification system design folder (architecture overview, release-events/inbox foundation, APNs/FCM relay specs, outbound webhooks) and adds the Web Push spec (05, implemented in this branch), the shared outbound-email architecture note, and the v1.5 roadmap (06) covering the remaining work after APNs/FCM were deferred to v2. Co-Authored-By: Claude Fable 5 <[email protected]>
…red SMTP core Implements the notification system foundation and all v1 delivery channels that need no external infrastructure (specs 00/01/04/05 in docs/superpowers/plans/notifications/): Foundation (spec 01): - episode_availability seeding + per-library seed markers: "newly available" means newly released to this server, so back-catalog imports and first scans never flood (verified on dev: 1.13M episodes seeded silently) - release_events -> profile_series_interest fanout worker with settling delay, per-series burst caps, FOR UPDATE SKIP LOCKED multi-node claims, and a guarded last-notified cursor - interest index maintained via a userstore provider decorator so every favorites/watchlist/progress mutation path (REST, jellycompat, imports, playback) feeds it; progress writes only recompute on state transitions - durable per-profile inbox + read state, forward-sync cursor API, websocket channel with short-lived single-use handshake tickets - web UI: sidebar badge, inbox page, toasts, per-profile preferences - startup/daily tasks: availability seeding, interest rebuild, retention Outbound webhooks (spec 04): - Discord embeds (text-only per the v1 privacy contract) and generic JSON signed Stripe-style with per-webhook secrets - HTTPS-only + private-destination guard enforced at registration and at connect time (DNS-rebinding mitigation); URLs/secrets encrypted at rest - durable per-target outbox enqueued in the fanout transaction, lease-based claims, 24h exponential retry, 3x-consecutive-4xx auto-disable with an in-app notice (loop-guarded) Web push (spec 05): - VAPID keypair self-provisioned at startup (single atomic JSON setting, private half encrypted at rest) — no third-party accounts needed - payloads E2E-encrypted (RFC 8291); 404/410 treated as unsubscribe - service worker + subscribe flow in Settings -> Notifications Shared SMTP core (internal/mail): - feature-agnostic mail.Sender over live email.* settings, STARTTLS or implicit TLS, encrypted password, admin Email settings page with synchronous test send; no consumer yet by design (digest is v1.5) APNs/FCM (specs 02/03) are deferred to v2; the capability endpoint reports them unavailable so clients render truthfully. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds profile-scoped release notifications, webhooks and web-push transports, account email sender and admin test, API handlers (inbox, prefs, webhooks, web-push), WS ticketing, DB migrations, frontend inbox/settings/UI, startup wiring, background tasks, and tests. ChangesNotifications and email delivery
Estimated code review effort: 🎯 5 (Critical) | ⏱️ ~120 minutes
✨ Finishing Touches🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 60cd5a74dc
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if err := s.writer.Set(ctx, SettingWebPushVAPIDKeypair, string(data)); err != nil { | ||
| return "", "", fmt.Errorf("persist VAPID keypair: %w", err) |
There was a problem hiding this comment.
Make VAPID key provisioning single-writer
When two nodes start with no notifications.web_push.vapid_keypair, both can pass loadKeypair, generate different pairs, and this unconditional Set lets the later writer overwrite the database after the earlier node has already re-read and cached its own pair. In that split-brain state clients that subscribed through one node can receive sends from another node signed with a different VAPID private key, so web push deliveries fail until nodes restart/converge and users resubscribe. Use a conditional insert/update or transactional lock so only one generated pair can win before any node caches it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8214c9b. Provisioning now uses a conditional SetIfAbsent settings write (INSERT … ON CONFLICT DO UPDATE … WHERE value = '' on the raw repo, encryption-aware in the decorator), so exactly one generated pair can ever land; a losing node re-reads and adopts the winner before caching. Read/decode failures now surface as errors instead of being treated as "missing" (see also the auto-rotation fix).
| if (profileRequired && activeProfileIDRef.current) { | ||
| profileRebindAttemptsRef.current += 1; | ||
| nextReconnectDelayRef.current = Math.min( | ||
| 30_000, | ||
| 1_000 * 2 ** Math.min(profileRebindAttemptsRef.current, 5), | ||
| ); | ||
| socket.close(); |
There was a problem hiding this comment.
Keep other realtime channels alive when ticket minting fails
When /events/ws-ticket fails or a Redis-backed ticket cannot be consumed, the server intentionally accepts the websocket unbound and only rejects the notifications channel, but this branch closes that otherwise healthy socket. Because RealtimeEventChannels always subscribes catalog and user_state alongside notifications, a notifications-only outage puts all realtime updates into a reconnect/backoff loop for logged-in profiles; keep the socket and retry only the profile-bound subscription instead of closing the shared connection.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Addressed in 8214c9b, within protocol limits: tickets are single-use and consumed at the websocket handshake, so a profile binding genuinely cannot be retried on the live socket — a rebind requires a reconnect. To keep the shared channels stable through a notifications-only outage, the rebind backoff now grows to a 5-minute cap (was 30s): catalog/user_state see one brief flap per cycle instead of a fast reconnect loop, and they work normally between cycles. A subscribe-time rebind would need a protocol extension; noted as a v1.5 candidate.
| if libraryIngestExecutor != nil { | ||
| libraryIngestExecutor.SetAvailabilityDetector(notificationSystem.Detector) | ||
| } |
There was a problem hiding this comment.
Wire availability detection before scan workers start
This detector is attached only after libraryScanQueue.Start() has already launched workers earlier in main, so any accepted scan resumed during startup can complete while Executor.availability is still nil and skip HandleIngestCompleted. In that startup window newly matched episodes are never recorded in episode_availability and no release events are created, so interested profiles miss notifications for those arrivals; install the detector before starting the scan queue (or delay workers until after this block).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8214c9b. libraryScanQueue.Start() (and its Stop defer) moved below the notification-system block, so scan workers cannot resume an accepted scan before SetAvailabilityDetector has run.
| ON CONFLICT (endpoint) DO UPDATE SET | ||
| user_id = EXCLUDED.user_id, | ||
| profile_id = EXCLUDED.profile_id, |
There was a problem hiding this comment.
Purge old web-push attempts when reassigning endpoints
When an existing browser endpoint is reassigned to a different profile or account, this ON CONFLICT update keeps the same subscription row id, so any pending/retrying web_push_delivery_attempts that were enqueued for the previous owner still target that id. If those attempts are later recovered by the retry worker, processAttempt sends the old delivery to the endpoint now associated with the new owner because it does not verify the subscription profile against the delivery; delete/recreate the row or purge stale attempts during reassignment.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8214c9b. Upsert now runs in a transaction that deletes the endpoint's pending/retrying attempts when it is owned by a different profile before reassigning, and processAttempt re-checks row.ProfileID == sub.ProfileID at send time as defense in depth.
| for offset := 0; ; offset += pageSize { | ||
| progress, err := store.ListProgress(ctx, profileID, "", pageSize, offset) | ||
| if err != nil { | ||
| return fmt.Errorf("list progress: %w", err) | ||
| } | ||
| for _, entry := range progress { | ||
| itemIDs[entry.MediaItemID] = struct{}{} |
There was a problem hiding this comment.
Include history-only imports in interest rebuilds
When watch providers or history imports only have a watched-at record, they call RecordImportedHistoryWithSource, which writes watch history via AddHistoryIfMissing without a progress row. This rebuild seeds profile_series_interest from favorites, watchlist, and ListProgress only, and the live decorator does not hook history writes, so those completed episodes never advance last_completed/next_expected and profiles watched only through imported history miss next-up notifications. Include completed history in the interest source and queue history mutations.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8214c9b. The userstore decorator now hooks AddHistoryIfMissing / RemoveHistoryItems / DeleteHistoryBySource (live AddHistory is deliberately unhooked — playback always writes progress alongside it); RecomputeSeries folds ListCompletedHistory into the progression cursor and next-up candidacy; the rebuild task pages completed history as an interest source.
Expose every live notifications.* server setting on a new admin Notifications tab (next to Email): kill switches, fanout tuning, webhook guards, and retention. Unset kill switches render as enabled to match the backend defaults, numeric fields surface their effective defaults, and enabling private webhook destinations shows an SSRF warning. v1.5 roadmap item 1; no backend changes — all keys are live-read. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 17
🧹 Nitpick comments (1)
web/src/hooks/queries/notificationWebhooks.ts (1)
1-1: ⚡ Quick winRename this hook module to follow the hook filename convention.
Line 1 is in
web/src/hooks/**/*.ts, but the file is namednotificationWebhooks.tsinstead ofuseThing.tsstyle (for example,useNotificationWebhooks.ts).As per coding guidelines,
web/src/hooks/**/*.ts: "UseuseThing.tsnaming convention for React hooks".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/hooks/queries/notificationWebhooks.ts` at line 1, Rename the module file to follow the React hook filename convention (e.g., rename notificationWebhooks.ts to useNotificationWebhooks.ts), and ensure the exported hook function name matches (export default or named export should be useNotificationWebhooks); update all imports across the codebase that reference notificationWebhooks to the new filename and symbol, and adjust any barrel/index exports or tests that re-export or import this hook so they reference the new file and hook name; keep existing logic intact and run the TypeScript build to catch missing import updates.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/api/handlers/notifications_webhooks.go`:
- Around line 177-179: The delete handler currently maps all service.Delete
errors to a generic HTTP 500 via writeError, losing domain-level mapping; update
the error handling after calling service.Delete(r.Context(), profileID,
chi.URLParam(r, "id")) to invoke the existing writeWebhookError (or the handler
that preserves domain-to-HTTP mapping) and pass the original err and response
writer so not-found/validation errors are translated correctly instead of always
returning an internal_error.
In `@internal/mail/mail.go`:
- Around line 109-112: The small helper get currently ignores errors from
s.settings.Get which turns failures into empty values and hides real backend
errors; change get (the closure around s.settings.Get) to return (string, error)
and propagate any non-nil error upward instead of returning an empty string,
update all call sites (e.g., where get is used during mail sender
initialization/newMailSender or similar) to handle the error and return or wrap
it (rather than converting to ErrNotConfigured), and preserve the existing
ErrNotConfigured only for the case where Get returns a nil error and an actually
empty/unspecified value.
In `@internal/notifications/availability_detector.go`:
- Around line 24-29: NewAvailabilityDetector allows settings to be nil but
AvailabilityDetector methods call d.settings.ReleaseEventsEnabled() unguarded;
update the code path that checks ReleaseEventsEnabled (the call site referencing
d.settings.ReleaseEventsEnabled()) to first guard for d.settings != nil (e.g.,
treat nil as disabled) and only call ReleaseEventsEnabled when d.settings is
non-nil so the ingest-complete handling cannot panic; ensure the guard is used
wherever d.settings is dereferenced.
In `@internal/notifications/delivery_repo.go`:
- Around line 326-330: The DELETE uses created_at for read rows so read
retention is based on delivery age; change the SQL in the r.pool.Exec call that
targets notification_deliveries to compare read rows against read_at instead of
created_at (i.e. use "WHERE (read_at IS NOT NULL AND read_at < $1) OR (read_at
IS NULL AND created_at < $2)"), and ensure the bound parameters (readCutoff,
unreadCutoff) match that order so readCutoff is applied to read_at and
unreadCutoff to created_at.
In `@internal/notifications/interest_updater.go`:
- Around line 99-144: flush currently clears u.pending immediately and drops
mutations when resolveSeriesID or RecomputeSeries fail; change flush (and use of
interestMutation, pending, recomputeKey) to requeue failed mutations instead of
discarding them: after taking batch := u.pending and setting u.pending =
make(map[interestMutation]struct{}), keep a local failed map and on any error
from resolveSeriesID or RecomputeSeries add the original mutation back to failed
(preserving dedupe logic), and before returning acquire u.mu and merge failed
entries back into u.pending (or append them safely) so transient errors are
retried; ensure all modifications to u.pending are done under u.mu and that
ctx.Err() early-return does not lose the remaining unprocessed mutations (merge
unprocessed into u.pending before returning).
In `@internal/notifications/system.go`:
- Around line 457-474: The rebuild currently only upserts interests for series
returned by s.batchResolveSeries and never handles existing
profile_series_interest rows that are no longer present; update the routine (the
block that calls s.batchResolveSeries and then loops calling
s.Interest.RecomputeSeries(ctx, userID, profileID, seriesID)) to also fetch the
current persisted series interests for (userID, profileID) from Postgres,
compute the set difference between persisted series and the resolved seriesIDs,
and for each removedSeries either delete the row or call a removal/recompute
method so stale interests are cleared; preserve the existing ctx cancellation
checks and log failures similarly to the existing RecomputeSeries error
handling.
- Around line 221-228: Start() spawns a fire-and-forget goroutine that calls
s.WebPush.PublicKey(ctx) but never increments s.wg, so Wait() may return before
the goroutine finishes; fix by incrementing the wait group before launching the
goroutine (call s.wg.Add(1) in Start()), and ensure the goroutine defers
s.wg.Done() as its first action, keeping the existing ctx.Err() check and error
logging around s.WebPush.PublicKey(ctx) to preserve behavior.
In `@internal/notifications/webhook_http.go`:
- Around line 97-109: Reject non-HTTPS webhook URLs early by validating the
request URL scheme before creating or sending the HTTP request: parse the
provided url string (the same one passed to http.NewRequestWithContext) and
ensure its Scheme is "https"; if not, return the same error/result path used
elsewhere (e.g., result(false, 0, "invalid webhook URL") or a clear HTTPS-only
error). Add this check near the start of the function handling webhook dispatch
(before http.NewRequestWithContext and client.Do) so that webhookRequestTimeout,
webhookUserAgent, headers and the client.Do call never operate on non-HTTPS
URLs.
- Around line 125-129: When handling http.StatusTooManyRequests in
webhook_http.go, extend the Retry-After parsing (currently using strconv.Atoi on
resp.Header.Get("Retry-After")) to also accept HTTP-date values: if Atoi fails,
call http.ParseTime on the header value, compute duration as
parsedTime.Sub(time.Now()), and set out.RetryAfter to that duration only if it's
> 0; keep existing numeric handling and ensure negative or unparseable values
fall back to default behavior; reference resp.Header.Get("Retry-After"),
out.RetryAfter, and the http.StatusTooManyRequests handling block.
In `@internal/notifications/webhook_repo.go`:
- Around line 146-149: Replace the string-contains check on err.Error() with a
typed pg error check: use errors.As to see if err is a *pgconn.PgError, verify
pgErr.Code == "23505" (unique_violation) and pgErr.ConstraintName ==
"notification_webhooks_profile_name_key", and only then return
ErrWebhookNameTaken; otherwise fall through to the existing error handling.
Update the error handling in the function that contains the current snippet (the
block where err is checked after the DB insert/update) to perform this typed
check (importing github.com/jackc/pgconn and using errors.As) so the mapping is
robust to message-format changes.
In `@internal/notifications/webhook_sender.go`:
- Around line 166-170: The current logic calls s.webhooks.FinalizeAttempt for
any err != nil or row == nil from s.deliveries.GetRowByID, which incorrectly
finalizes attempts on transient DB errors; change it so only the case row == nil
triggers s.webhooks.FinalizeAttempt(..., WebhookOutcomeFailed, ... , "delivery
row missing", ...), while when err != nil you should log the error (including
attempt.NotificationDeliveryID and attempt.ID) and return without finalizing so
the lease can expire and the retry path can reclaim the attempt; adjust the
branch around s.deliveries.GetRowByID accordingly in webhook_sender.go.
In `@internal/notifications/webhook_service.go`:
- Around line 92-98: The current pre-check using s.repo.CountByProfile +
s.settings.WebhooksMaxPerProfile is racy; move the quota enforcement into an
atomic repository operation (or DB constraint) so the count-and-insert happens
inside a single transaction. Update the service call (e.g., where CreateWebhook
or the block using CountByProfile) to call a new repo method such as
CreateWebhookIfBelowLimit / InsertWithProfileLimit or implement the
check-and-insert in the existing repo.Create method using a transaction (SELECT
... FOR UPDATE or a conditional INSERT) and return ErrWebhookLimit on violation;
keep ErrWebhookLimit as the error sentinel and ensure
s.settings.WebhooksMaxPerProfile(ctx) is consulted inside that atomic repo
operation.
- Around line 100-119: Create-time type/URL mismatches are allowed because after
parsing hookType the code never verifies an explicit Type matches the
destination URL; update the logic in the webhook creation flow (the block that
calls ValidateWebhookURL and computes hookType) to enforce consistency: after
computing hookType (using WebhookTypeDiscord, WebhookTypeGeneric and
discordWebhookURL(rawURL)), if input.Type was provided and hookType ==
WebhookTypeDiscord then require discordWebhookURL(rawURL) true (otherwise return
ErrWebhookInvalid with a descriptive message), and if input.Type was provided
and hookType == WebhookTypeGeneric then require discordWebhookURL(rawURL) false
(otherwise return ErrWebhookInvalid); keep the existing auto-detection when
input.Type is empty.
In `@internal/notifications/webpush_service.go`:
- Around line 73-96: loadKeypair currently masks read/unmarshal failures by
returning an empty vapidKeypair which causes automatic rotation in the code path
around s.loadKeypair(ctx) and writer.Set; change the logic so that read or
decode errors are surfaced instead of treated as "missing": have loadKeypair
return an explicit error (or a distinct sentinel result) so the caller in the
code handling vapidKeypair (the block that calls s.loadKeypair, generates keys,
json.Marshal and s.writer.Set) only generates and persists a new VAPID keypair
when the store explicitly indicates “not found/missing”, and returns an error
whenever loadKeypair reported a read/unmarshal failure; ensure the
re-read-after-write concurrency branch still reconciles correctly but never
auto-rotate on transient read/decode errors.
In `@migrations/sql/20260611100000_profile_release_notifications.sql`:
- Around line 10-20: The migration must enforce invariants at the DB level: add
CHECK constraints to the episode_availability table to ensure season_number >= 0
(or >=1 per domain), episode_number >= 0 (or >=1), and episode_key >= 0 (and any
upper bounds if applicable), so invalid values cannot be inserted via
SQL/backfills; update the CREATE TABLE for public.episode_availability to
include CHECK(...) clauses on season_number, episode_number, and episode_key
(and add the same constraints to the other affected CREATE TABLE block noted in
the comment) so the collision-free ordering contract used by fanout/suppression
is preserved.
In `@web/public/sw.js`:
- Around line 35-47: The code currently takes event.notification.data.url and
navigates clients to it (url variable) which can enable open-redirects; update
the click handler to validate the URL before using it: compute a safeUrl by
treating the payload as relative (e.g., allow strings starting with "/") or by
constructing new URL(url, self.location) and comparing its origin to
self.location.origin, and only call client.navigate(safeUrl) or
self.clients.openWindow(safeUrl) when the origin matches; otherwise fall back to
the safe default "/notifications". Make this change around the url variable and
before calls to client.navigate and self.clients.openWindow to ensure only
same-origin navigation is permitted.
In `@web/src/pages/Notifications.tsx`:
- Around line 244-266: The current render treats !prefs as loading, causing the
skeleton to show forever on fetch failures; update the Notifications component
to handle the query error state explicitly by using the query's isError (and
error/refetch) instead of only !prefs/isLoading: when isError render a concise
error UI with the error message and a retry control that calls refetch, and only
render the skeleton while isLoading is true; keep the existing toggles/Switch
rendering and updatePrefs.mutate logic unchanged and reference the existing
variables isLoading, isError, error, refetch, prefs, toggles, and
updatePrefs.mutate to implement this behavior.
---
Nitpick comments:
In `@web/src/hooks/queries/notificationWebhooks.ts`:
- Line 1: Rename the module file to follow the React hook filename convention
(e.g., rename notificationWebhooks.ts to useNotificationWebhooks.ts), and ensure
the exported hook function name matches (export default or named export should
be useNotificationWebhooks); update all imports across the codebase that
reference notificationWebhooks to the new filename and symbol, and adjust any
barrel/index exports or tests that re-export or import this hook so they
reference the new file and hook name; keep existing logic intact and run the
TypeScript build to catch missing import updates.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3fcbf3cc-399c-4dce-8100-0216a91831bd
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (65)
cmd/silo/main.godocs/architecture/email.mddocs/superpowers/plans/notifications/05-web-push.mddocs/superpowers/plans/notifications/06-v1.5-roadmap.mdgo.modinternal/api/handlers/email.gointernal/api/handlers/events_ws.gointernal/api/handlers/notifications.gointernal/api/handlers/notifications_webhooks.gointernal/api/handlers/notifications_webpush.gointernal/api/router.gointernal/catalog/encrypted_settings_repo.gointernal/events/types.gointernal/libraryingest/executor.gointernal/mail/mail.gointernal/mail/mail_test.gointernal/notifications/availability_detector.gointernal/notifications/delivery_repo.gointernal/notifications/dispatcher.gointernal/notifications/episode_key.gointernal/notifications/fanout_logic.gointernal/notifications/fanout_logic_test.gointernal/notifications/fanout_worker.gointernal/notifications/interest_hooks.gointernal/notifications/interest_repo.gointernal/notifications/interest_updater.gointernal/notifications/preferences_repo.gointernal/notifications/release_repo.gointernal/notifications/release_types.gointernal/notifications/settings.gointernal/notifications/system.gointernal/notifications/webhook_dispatcher.gointernal/notifications/webhook_guard.gointernal/notifications/webhook_http.gointernal/notifications/webhook_logic_test.gointernal/notifications/webhook_payload_discord.gointernal/notifications/webhook_payload_generic.gointernal/notifications/webhook_repo.gointernal/notifications/webhook_sender.gointernal/notifications/webhook_service.gointernal/notifications/webhook_types.gointernal/notifications/webpush_logic_test.gointernal/notifications/webpush_repo.gointernal/notifications/webpush_sender.gointernal/notifications/webpush_service.gointernal/notifications/ws_ticket.gointernal/taskmanager/tasks/notifications_tasks.gomigrations/sql/20260611100000_profile_release_notifications.sqlmigrations/sql/20260611120000_notification_webhooks.sqlmigrations/sql/20260611150000_web_push_subscriptions.sqlweb/public/sw.jsweb/src/App.tsxweb/src/api/types.tsweb/src/components/AppSidebar.test.tsxweb/src/components/AppSidebar.tsxweb/src/components/RealtimeEventsProvider.tsxweb/src/hooks/queries/keys.tsweb/src/hooks/queries/notificationWebhooks.tsweb/src/hooks/queries/notifications.tsweb/src/lib/webPush.tsweb/src/pages/Notifications.tsxweb/src/pages/SettingsLayout.tsxweb/src/pages/admin-settings/AdminSettingsLayout.tsxweb/src/pages/admin-settings/EmailSettings.tsxweb/src/pages/settings/NotificationsSettings.tsx
Notify the requesting profile once its media request is actually present in the catalog (roadmap 06, item 2). Completion transitions stay notification-agnostic; a presence-gated pass at the end of each reconcile run fires the notice, so it means "watchable in Silo", not "download finished". - New System.DispatchOperational: delivery insert + webhook/web-push outbox enqueue in one transaction, post-commit multi-dispatch. The webhook auto-disable notice now rides the same path (replacing its hand-rolled hub publish and the now-removed InsertOperational), which also delivers auto-disable notices over web push. - At-most-once delivery: partial unique index on (profile_id, reason_flags->>'request_id') plus a fulfilled_notified_at marker on media_requests, backfilled for pre-existing completed requests so deploys never flood. - Per-webhook notify_requests toggle (default on) through repo, service, API, and settings UI; gated independently of the episode reason flags. - request.fulfilled rendering in web inbox, realtime toast, web push payload, and Discord/generic webhook payloads, deep-linking to the matched catalog item. Co-Authored-By: Claude Fable 5 <[email protected]>
Surface per-subscription delivery health on the Notifications settings page: this browser and each other device now show last-delivered / last-failed status (failures newer than the last success render in amber, mirroring webhook health), plus a device count and an explicit disabled-after-failures state. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
♻️ Duplicate comments (1)
web/src/pages/Notifications.tsx (1)
255-277:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winHandle preferences fetch failures explicitly (preferences error state needs retry path).
Line 206 destructures only
dataandisLoading. When the query fails,!prefsremains true and the skeleton is shown indefinitely with no recovery path for the user.♻️ Recommended fix to add error handling
function NotificationPreferencesPopover() { - const { data: prefs, isLoading } = useNotificationPreferences(); + const { data: prefs, isLoading, isError, refetch } = useNotificationPreferences(); const updatePrefs = useUpdateNotificationPreferences(); @@ <PopoverContent align="end" className="w-80"> - {isLoading || !prefs ? ( + {isLoading ? ( <div className="space-y-3"> <Skeleton className="h-6 w-full" /> <Skeleton className="h-6 w-full" /> <Skeleton className="h-6 w-full" /> </div> + ) : isError || !prefs ? ( + <div className="space-y-3 text-sm"> + <p className="text-muted-foreground">Couldn't load preferences.</p> + <Button size="sm" variant="outline" onClick={() => refetch()}> + Retry + </Button> + </div> ) : ( <div className="space-y-4">🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/Notifications.tsx` around lines 255 - 277, The component currently only checks isLoading and !prefs, causing the skeleton to display forever on query failure; update the query destructuring for the prefs fetch to include isError, error, and refetch (alongside data/isLoading), then change the render logic so isLoading shows the Skeletons, isError renders a clear error UI (message using error?.message and a retry button that calls refetch), and the success branch uses prefs to render toggles; keep updatePrefs and toggles handling the same and ensure Switch uses a safe guard if prefs is undefined.
🧹 Nitpick comments (2)
web/src/pages/admin-settings/NotificationsAdminSettings.tsx (2)
26-26: 💤 Low valueRemove redundant
useMemowrapper.
KEYSis defined as a module-level constant (lines 8–23) and never changes, so wrapping it inuseMemoprovides no benefit:- const form = useSettingsForm({ keys: useMemo(() => KEYS, []) }); + const form = useSettingsForm({ keys: KEYS });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/admin-settings/NotificationsAdminSettings.tsx` at line 26, The call in NotificationsAdminSettings to useSettingsForm currently wraps KEYS in useMemo unnecessarily; update the useSettingsForm invocation to pass the module-level constant KEYS directly (remove the useMemo(() => KEYS, []) wrapper) so the form initialization uses KEYS without the redundant memoization in the NotificationsAdminSettings component.
134-134: ⚡ Quick winConsider explicit default for security toggle.
The
allow_private_destinationstoggle correctly avoids usingtoggleValue()(which defaults to"true"), but when the value is unset,form.getValue()may return an empty string or undefined, which could leave the toggle in an unclear state. For a security-sensitive setting, explicitly defaulting to"false"improves clarity:- value={form.getValue("notifications.webhooks.allow_private_destinations")} + value={form.getValue("notifications.webhooks.allow_private_destinations") || "false"}This ensures the toggle always shows "off" when unset, matching the secure default.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/admin-settings/NotificationsAdminSettings.tsx` at line 134, The security toggle in NotificationsAdminSettings.tsx currently reads value={form.getValue("notifications.webhooks.allow_private_destinations")} which can be empty/undefined; change it to explicitly default to "false" when unset (e.g., use a nullish-coalescing or conditional fallback such as form.getValue("notifications.webhooks.allow_private_destinations") ?? "false" or otherwise coerce to a boolean) so the toggle is always shown off by default; update the same symbol and any related toggleValue usage to preserve consistent string/boolean handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@web/src/pages/Notifications.tsx`:
- Around line 255-277: The component currently only checks isLoading and !prefs,
causing the skeleton to display forever on query failure; update the query
destructuring for the prefs fetch to include isError, error, and refetch
(alongside data/isLoading), then change the render logic so isLoading shows the
Skeletons, isError renders a clear error UI (message using error?.message and a
retry button that calls refetch), and the success branch uses prefs to render
toggles; keep updatePrefs and toggles handling the same and ensure Switch uses a
safe guard if prefs is undefined.
---
Nitpick comments:
In `@web/src/pages/admin-settings/NotificationsAdminSettings.tsx`:
- Line 26: The call in NotificationsAdminSettings to useSettingsForm currently
wraps KEYS in useMemo unnecessarily; update the useSettingsForm invocation to
pass the module-level constant KEYS directly (remove the useMemo(() => KEYS, [])
wrapper) so the form initialization uses KEYS without the redundant memoization
in the NotificationsAdminSettings component.
- Line 134: The security toggle in NotificationsAdminSettings.tsx currently
reads value={form.getValue("notifications.webhooks.allow_private_destinations")}
which can be empty/undefined; change it to explicitly default to "false" when
unset (e.g., use a nullish-coalescing or conditional fallback such as
form.getValue("notifications.webhooks.allow_private_destinations") ?? "false" or
otherwise coerce to a boolean) so the toggle is always shown off by default;
update the same symbol and any related toggleValue usage to preserve consistent
string/boolean handling.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 2c9420fb-f024-46f2-86fe-30eb4416fd71
📒 Files selected for processing (29)
cmd/silo/main.gointernal/api/handlers/notifications_webhooks.gointernal/notifications/delivery_repo.gointernal/notifications/operational_dispatch.gointernal/notifications/request_notifier.gointernal/notifications/system.gointernal/notifications/webhook_logic_test.gointernal/notifications/webhook_payload_discord.gointernal/notifications/webhook_payload_generic.gointernal/notifications/webhook_repo.gointernal/notifications/webhook_sender.gointernal/notifications/webhook_service.gointernal/notifications/webhook_types.gointernal/notifications/webpush_logic_test.gointernal/notifications/webpush_sender.gointernal/requests/notify.gointernal/requests/notify_test.gointernal/requests/repository.gointernal/requests/service.gointernal/requests/service_test.gointernal/requests/store.gomigrations/sql/20260611193802_request_fulfilled_notifications.sqlweb/src/api/types.tsweb/src/components/RealtimeEventsProvider.tsxweb/src/pages/Notifications.tsxweb/src/pages/admin-settings/AdminSettingsLayout.test.tsxweb/src/pages/admin-settings/AdminSettingsLayout.tsxweb/src/pages/admin-settings/NotificationsAdminSettings.tsxweb/src/pages/settings/NotificationsSettings.tsx
💤 Files with no reviewable changes (1)
- internal/notifications/delivery_repo.go
🚧 Files skipped from review as they are similar to previous changes (16)
- internal/notifications/webpush_logic_test.go
- cmd/silo/main.go
- web/src/pages/admin-settings/AdminSettingsLayout.tsx
- web/src/api/types.ts
- internal/notifications/webhook_payload_generic.go
- web/src/components/RealtimeEventsProvider.tsx
- internal/api/handlers/notifications_webhooks.go
- internal/notifications/webhook_payload_discord.go
- internal/notifications/webpush_sender.go
- internal/notifications/webhook_repo.go
- web/src/pages/settings/NotificationsSettings.tsx
- internal/notifications/webhook_types.go
- internal/notifications/webhook_service.go
- internal/notifications/webhook_logic_test.go
- internal/notifications/webhook_sender.go
- internal/notifications/system.go
Codex + CodeRabbit review fixes, all verified against current behavior: - Web Push: single-writer VAPID provisioning via a new conditional SetIfAbsent settings write (no split-brain identity across nodes), and read/decode failures now surface instead of silently rotating the keypair; the eager-provisioning goroutine joins the shutdown WaitGroup - Web Push: endpoint reassignment purges the previous owner's pending attempts inside the upsert transaction, with an ownership re-check at send time - Webhooks: per-profile cap enforced atomically (advisory-locked count+insert), typed pgconn unique-violation mapping, create-time type/URL mismatch rejection, send-time HTTPS re-check, and Retry-After HTTP-date support (shared, clamped parser also used by web push) - Delivery workers: transient delivery-row lookup errors leave the claim to lease expiry instead of permanently failing the attempt - Interest: history-only imports now feed the index (userstore history hooks + completed-history folding in recompute/rebuild), rebuild also recomputes existing interest rows so removed sources get cleaned up, and failed flush mutations requeue (bounded) instead of dropping - Retention: read notifications age from read_at, not created_at - Startup: scan queue workers start only after the availability detector is wired, so resumed scans cannot skip availability recording - mail: settings-store read failures propagate instead of reading as "not configured" - DB: new migration adds episode ordinal/key CHECK constraints - Web: service worker restricts notification clicks to same-origin URLs, preferences popover gets an error+retry state, and the realtime profile-rebind backoff grows to 5 minutes to keep shared channels stable through notifications-only outages Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
web/src/pages/Notifications.tsx (1)
206-206: 💤 Low valueConsider destructuring
isErrorfor more explicit error handling.While the current
!prefscheck likely works in practice, React Query can retain stale data during refetch errors. Explicitly checkingisErrorwould be more precise and match the earlier review guidance.♻️ Optional refinement
- const { data: prefs, isLoading, refetch } = useNotificationPreferences(); + const { data: prefs, isLoading, isError, refetch } = useNotificationPreferences();Then update the condition on line 261:
- ) : !prefs ? ( + ) : isError || !prefs ? (🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/Notifications.tsx` at line 206, Destructure isError from the useNotificationPreferences hook (const { data: prefs, isLoading, isError, refetch } = useNotificationPreferences()) and update the component's render condition that currently checks !prefs to explicitly account for isError (e.g., treat isError like a loading/error state before rendering prefs). Locate the conditional that gates rendering of preferences (the check using prefs) and include isError in that condition so stale data during refetch errors doesn't bypass error handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@web/src/pages/Notifications.tsx`:
- Line 206: Destructure isError from the useNotificationPreferences hook (const
{ data: prefs, isLoading, isError, refetch } = useNotificationPreferences()) and
update the component's render condition that currently checks !prefs to
explicitly account for isError (e.g., treat isError like a loading/error state
before rendering prefs). Locate the conditional that gates rendering of
preferences (the check using prefs) and include isError in that condition so
stale data during refetch errors doesn't bypass error handling.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: bac41b5d-659b-47cd-875b-8df885de4b14
📒 Files selected for processing (24)
cmd/silo/main.gointernal/api/handlers/notifications_webhooks.gointernal/catalog/encrypted_settings_repo.gointernal/catalog/server_settings_repo.gointernal/mail/mail.gointernal/notifications/delivery_repo.gointernal/notifications/interest_hooks.gointernal/notifications/interest_repo.gointernal/notifications/interest_updater.gointernal/notifications/system.gointernal/notifications/webhook_guard.gointernal/notifications/webhook_http.gointernal/notifications/webhook_payload_discord.gointernal/notifications/webhook_repo.gointernal/notifications/webhook_sender.gointernal/notifications/webhook_service.gointernal/notifications/webhook_types.gointernal/notifications/webpush_repo.gointernal/notifications/webpush_sender.gointernal/notifications/webpush_service.gomigrations/sql/20260611202951_episode_ordinal_checks.sqlweb/public/sw.jsweb/src/components/RealtimeEventsProvider.tsxweb/src/pages/Notifications.tsx
🚧 Files skipped from review as they are similar to previous changes (13)
- internal/notifications/webhook_guard.go
- internal/api/handlers/notifications_webhooks.go
- internal/notifications/webhook_http.go
- internal/notifications/webhook_payload_discord.go
- cmd/silo/main.go
- web/src/components/RealtimeEventsProvider.tsx
- internal/notifications/delivery_repo.go
- internal/notifications/webhook_sender.go
- internal/mail/mail.go
- internal/notifications/webpush_sender.go
- internal/notifications/interest_updater.go
- internal/notifications/webpush_repo.go
- internal/notifications/system.go
Adds email as a notification channel built on the shared SMTP core (mail.Sender). Email mode is a per-account preference (off, daily digest, or per-episode) stored in notification_email_prefs; delivery is an account-watermark sweep over notification_deliveries that dedupes cross-profile duplicates, advancing the watermark only after a successful send. Admin controls cover the channel kill switch, the per-episode allowance (off coerces those accounts to the digest), digest hour, and an external URL for deep links inside emails. Availability is advertised through /notifications/capability and the user settings page gains an Email section for opt-in. Co-Authored-By: Claude Fable 5 <[email protected]>
Letting users point server-originated HTTP at arbitrary destinations is an admin decision, so notifications.webhooks_enabled now defaults to off instead of acting as a default-on kill switch. The flag is also enforced at webhook creation and test sends (delivery was already gated at enqueue and dispatch); existing webhooks stay manageable while disabled so rows are never stranded. The admin toggle moves into the Webhook Guards group with an off default, and the user settings page hides the Webhooks section entirely when the capability is unavailable, matching the other channel sections. Co-Authored-By: Claude Fable 5 <[email protected]>
Adds Discord direct messages as a notification channel. Users link their Discord account via OAuth2 (identify scope only, one-time server-side state rows); a bot delivers their inbox notifications as DMs. - Extract the email channel's watermark sweep into a generic account-channel engine; email and Discord are now thin adapters, so the SKIP LOCKED claim / watermark-after-send durability logic exists once. - New internal/discord REST client (token exchange, identity, open DM, send message) — no Gateway connection, no new dependencies. - Opt-in master switch (notifications.discord_enabled, default off) gates delivery, linking, capability, and the admin settings reveal. - Admin UI: credentials (secret + bot token encrypted at rest), dev portal setup checklist, bot invite link buttons, and a test button that bypasses the settings read cache and is disabled while credential edits are unsaved. - DM failures from missing shared guild (Discord 50007) surface as link health in user settings and self-heal via capped backoff. - New combined mode (per_episode_and_digest) for email and Discord: instant sends all day plus a daily digest recapping the whole window since the previous digest. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
web/src/pages/admin-settings/NotificationsAdminSettings.tsx (1)
72-76: 💤 Low valueConsider adding error handling for clipboard access.
The
navigator.clipboard.writeText()call is voided, so if clipboard access fails (e.g., permissions, non-HTTPS context), the success toast will still appear but the copy won't happen. Consider wrapping in a try/catch or handling the promise rejection.♻️ Optional improvement
onClick={() => { - void navigator.clipboard.writeText(discordInviteUrl(trimmed)); - setCopied(true); - toast.success("Invite link copied"); - window.setTimeout(() => setCopied(false), 2000); + navigator.clipboard.writeText(discordInviteUrl(trimmed)) + .then(() => { + setCopied(true); + toast.success("Invite link copied"); + window.setTimeout(() => setCopied(false), 2000); + }) + .catch(() => { + toast.error("Failed to copy to clipboard"); + }); }}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/admin-settings/NotificationsAdminSettings.tsx` around lines 72 - 76, Wrap the navigator.clipboard.writeText(discordInviteUrl(trimmed)) call in an async try/catch instead of voiding it: await the promise returned by navigator.clipboard.writeText, only call setCopied(true) and toast.success("Invite link copied") on success, and in the catch call toast.error or console.error to surface the failure; ensure the onClick handler (where discordInviteUrl(trimmed), setCopied, toast.success and window.setTimeout are used) is converted to an async function or returns the promise so the error path can be handled.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/api/router.go`:
- Around line 1560-1564: The Discord routes are currently mounted under the
profile-scoped subrouter (inheriting apimw.RequireProfile) causing profile-less
sessions to fail; move the discord route registrations
(discordNotificationsHandler.HandleGetPreferences, HandleUpdatePreferences,
HandleUnlink, HandleLinkInit) out of the profile-scoped "/notifications"
subrouter and register them on the auth-only group/router that applies
authentication but not apimw.RequireProfile so they remain account-scoped;
ensure the conditional check for discordNotificationsHandler != nil is preserved
and that the new placement is adjacent to other auth-only routes to avoid
changing middleware.
In `@internal/notifications/account_channel_engine.go`:
- Around line 210-214: When sending per-account you must re-check channel
availability and abort if disabled: add a second gate in processAccount (or just
before calling channel.send) to call w.channel.enabled(ctx) again and return
errChannelUnavailable if it returns false; update processAccount (or the code
path invoking channel.send) so that the function respects this new early-return
and no longer proceeds to channel.send after the channel is toggled off, keeping
existing runPass() behavior unchanged.
- Around line 338-397: The digest logic currently fetches at most
channelFetchLimit rows once (via w.deliveries.ListForUserSince) and then
advances last_digest_at even if more rows remain; change this to fully drain the
digest window before stamping: replace the single ListForUserSince call with a
loop that repeatedly calls w.deliveries.ListForUserSince (advancing the start
cursor to the last fetched row) and accumulates all rows into rows/items until a
call returns fewer than channelFetchLimit (no more pages) or no rows; compute
watermark from the true final fetched row, preserve the ChannelModeDailyDigest
filtering (the items slice creation for unread rows), and only call
w.channel.markSent/tx.Commit once the full window has been drained so you don't
advance last_digest_at past undispatched rows.
---
Nitpick comments:
In `@web/src/pages/admin-settings/NotificationsAdminSettings.tsx`:
- Around line 72-76: Wrap the
navigator.clipboard.writeText(discordInviteUrl(trimmed)) call in an async
try/catch instead of voiding it: await the promise returned by
navigator.clipboard.writeText, only call setCopied(true) and
toast.success("Invite link copied") on success, and in the catch call
toast.error or console.error to surface the failure; ensure the onClick handler
(where discordInviteUrl(trimmed), setCopied, toast.success and window.setTimeout
are used) is converted to an async function or returns the promise so the error
path can be handled.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c00cb16c-2c7c-4866-bb6f-9efe34b56d11
📒 Files selected for processing (33)
.env.examplecmd/silo/main.godocs/superpowers/plans/notifications/07-email-channel.mdinternal/api/handlers/notifications.gointernal/api/handlers/notifications_discord.gointernal/api/handlers/notifications_email.gointernal/api/handlers/notifications_webhooks.gointernal/api/router.gointernal/catalog/encrypted_settings_repo.gointernal/discord/client.gointernal/discord/client_test.gointernal/notifications/account_channel_engine.gointernal/notifications/delivery_repo.gointernal/notifications/discord_dm.gointernal/notifications/discord_prefs_repo.gointernal/notifications/email_compose.gointernal/notifications/email_digest.gointernal/notifications/email_logic_test.gointernal/notifications/email_prefs_repo.gointernal/notifications/settings.gointernal/notifications/system.gointernal/notifications/webhook_logic_test.gointernal/notifications/webhook_payload_discord.gointernal/notifications/webhook_service.gomigrations/sql/20260611201720_email_notification_channel.sqlmigrations/sql/20260611223317_discord_notification_channel.sqlmigrations/sql/20260611234431_account_channel_combined_mode.sqlweb/src/api/types.tsweb/src/hooks/queries/keys.tsweb/src/hooks/queries/notifications.tsweb/src/hooks/useSettingsForm.tsweb/src/pages/admin-settings/NotificationsAdminSettings.tsxweb/src/pages/settings/NotificationsSettings.tsx
✅ Files skipped from review due to trivial changes (2)
- docs/superpowers/plans/notifications/07-email-channel.md
- migrations/sql/20260611223317_discord_notification_channel.sql
🚧 Files skipped from review as they are similar to previous changes (7)
- web/src/hooks/queries/keys.ts
- internal/notifications/webhook_logic_test.go
- internal/api/handlers/notifications_webhooks.go
- internal/notifications/webhook_service.go
- internal/api/handlers/notifications.go
- internal/notifications/webhook_payload_discord.go
- internal/notifications/delivery_repo.go
Re-key the email notification channel from login accounts to profiles. Each profile owns its mode, dispatch watermark, and destination address; there is deliberately no fallback to the account email, so the account holder no longer receives mail for every household profile. A profile receives nothing until its own address is verified. - Genericize the watermark-sweep engine over a recipient key (accountChannel[K]): email keys by profile_id, Discord stays on user_id. Delivery reads move into the channel adapters. - Custom addresses verify via single-use SHA-256-hashed token links served by a public endpoint; enabling the channel requires a verified address, and clearing the address switches the channel off. - Addresses are globally unique (case-insensitive): rejected when verified for another profile or matching another account's email or username. Checked at request time, re-checked at verify time (first-to-verify wins), backstopped by a partial unique index. - Every email carries an RFC 8058 one-click unsubscribe link backed by a per-profile capability token, minted lazily under the claim tx. - Child profiles cannot set addresses (and so receive no email in v1). - Verification sends are rate limited (1/min, 10/day per profile); mail.Message gains custom header support for List-Unsubscribe. - Migration drops the account-level prefs table without carrying opt-ins over, so nobody gets surprise emails post-upgrade. Android/Apple notification settings need follow-up for the new profile-scoped response shape and address-management endpoints. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@migrations/sql/20260612001031_profile_email_notifications.sql`:
- Around line 19-20: The SQL migration comment for the column custom_email is
stale and contradicts the implementation in email_digest.go: update the comment
on the migration (the line alongside "custom_email text NOT NULL DEFAULT ''") to
state that an empty string means "no verified address; no account-email fallback
— the profile receives nothing until its own address is verified" (or similar
wording), so the comment matches the behavior enforced by email_digest.go and
the PR objectives.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f15a9db5-4d43-45cf-accd-d22c109dab5d
📒 Files selected for processing (17)
internal/api/handlers/notifications_email.gointernal/api/router.gointernal/mail/mail.gointernal/notifications/account_channel_engine.gointernal/notifications/delivery_repo.gointernal/notifications/discord_dm.gointernal/notifications/discord_prefs_repo.gointernal/notifications/email_address.gointernal/notifications/email_compose.gointernal/notifications/email_digest.gointernal/notifications/email_logic_test.gointernal/notifications/email_prefs_repo.gointernal/notifications/system.gomigrations/sql/20260612001031_profile_email_notifications.sqlweb/src/api/types.tsweb/src/hooks/queries/notifications.tsweb/src/pages/settings/NotificationsSettings.tsx
🚧 Files skipped from review as they are similar to previous changes (9)
- internal/notifications/account_channel_engine.go
- web/src/api/types.ts
- internal/notifications/email_compose.go
- internal/mail/mail.go
- internal/api/router.go
- internal/notifications/discord_dm.go
- internal/notifications/discord_prefs_repo.go
- web/src/hooks/queries/notifications.ts
- internal/notifications/system.go
| -- Verified destination address; '' = fall back to users.email. | ||
| custom_email text NOT NULL DEFAULT '', |
There was a problem hiding this comment.
Stale comment contradicts implementation.
The comment says '' = fall back to users.email, but the implementation in email_digest.go (line 79-81) and the PR objectives explicitly state there is no account-email fallback — a profile receives nothing until its own address is verified.
Suggested fix
- -- Verified destination address; '' = fall back to users.email.
+ -- Verified destination address; '' = none, channel is inert until set.
custom_email text NOT NULL DEFAULT '',📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| -- Verified destination address; '' = fall back to users.email. | |
| custom_email text NOT NULL DEFAULT '', | |
| -- Verified destination address; '' = none, channel is inert until set. | |
| custom_email text NOT NULL DEFAULT '', |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@migrations/sql/20260612001031_profile_email_notifications.sql` around lines
19 - 20, The SQL migration comment for the column custom_email is stale and
contradicts the implementation in email_digest.go: update the comment on the
migration (the line alongside "custom_email text NOT NULL DEFAULT ''") to state
that an empty string means "no verified address; no account-email fallback — the
profile receives nothing until its own address is verified" (or similar
wording), so the comment matches the behavior enforced by email_digest.go and
the PR objectives.
Replace the bare-bones inline HTML in notification, verification, and admin test emails with a shared branded layout in internal/mail, matching the web UI's Midnight Cinema theme (dark card shell, wordmark, mono episode-code badges, white primary CTA). The shell is built for email clients: tables + inline styles, explicit dark color-scheme, Outlook-safe button, and a width:100%/max-width pattern so the card shrinks correctly on phones. Plain-text bodies, subjects, and the link-free-when-unconfigured guarantee are unchanged; the admin test email gains an HTML body so the SMTP test doubles as a design preview. Co-Authored-By: Claude Fable 5 <[email protected]>
…h under claim Digest sends read one channelFetchLimit page and then stamped last_digest_at, permanently dropping overflow rows from combined-mode recaps and slipping digest-only overflow by a day per page. Digest legs now page listSince until the window is empty before stamping; renderers already cap displayed items, so large drains stay deliverable. Per-episode sends keep single-page reads — their watermark-advance semantics were already correct. Also re-check the channel's enabled() under the claim lock so flipping the admin kill switch stops an in-flight pass immediately instead of after it completes; the existing errChannelUnavailable path aborts the pass without penalizing the recipient. Co-Authored-By: Claude Fable 5 <[email protected]>
The Discord DM channel's prefs, link-init, and unlink endpoints are account-level — the handlers only read the user ID — but were mounted inside the /notifications subrouter, whose RequireProfile middleware 400s any request without an X-Profile-Id header. Register them as static paths on the auth-only group instead, the same coexistence pattern the public email-link routes already use (static paths win over the mounted subrouter's wildcards; verified empirically, no middleware leak onto profile-scoped routes). Co-Authored-By: Claude Fable 5 <[email protected]>
…nd request activity
Add admin-owned broadcast destinations ("community channels"): Discord or
generic webhooks fed straight from release_events by a per-channel watermark
sweep, announcing newly added movies/episodes as grouped digest posts plus
configurable media request lifecycle events (submitted/approved/declined/
fulfilled).
- Extend release_events with a kind discriminator and add a movie
availability spine (movie_availability + kind-keyed
notification_content_seed_state; first full scan seeds silently so
upgrades never flood the movie back catalog)
- Sweep worker reads events by (created_at, id) cursor with batch-window
grouping, per-channel backoff, and auto-disable; request events post
best-effort via new requests.LifecycleNotifier hooks
- Reuse the webhook stack throughout: URL encryption (new AAD namespace),
SSRF guard, embed limits, HMAC signing; shared type/name validation
extracted for both services
- Admin CRUD API under /admin/notifications/server-channels and a Server
Channels section in the notifications admin settings UI
Co-Authored-By: Claude Fable 5 <[email protected]>
tsc -b (the production build) collapses flatMap over the as-const union of two differently shaped readonly field tuples to unknown, failing the Docker frontend stage; a bare tsc --noEmit accepted it. Give the field entries one explicit shared type so flatMap and channel[field.key] resolve. Co-Authored-By: Claude Fable 5 <[email protected]>
…, and ratings Upgrade all outbound Discord surfaces (personal webhooks, bot DMs, server channels, request events) from bare title/description embeds to rich ones: poster thumbnail, overview teaser, TMDB/IMDb/TVDB links, rating and genre fields, content-rating footer, and a clickable title URL. Artwork respects the v1 privacy contract via a new admin poster mode (notifications.discord.poster_mode): "provider" (default) only emits public provider-CDN URLs, "server" additionally presigns locally cached posters from this server's image storage, "off" drops images entirely. Builders never derive artwork URLs themselves; the sender layer resolves PosterURL through System.discordPosterURL. To keep provider-CDN URLs derivable after image caching rewrites poster_path to a local storage key, media_items gains poster_source_path, captured during cacheItemImages, preserved across refreshes that keep the cached poster, and cleared on explicit poster overrides. Co-Authored-By: Claude Fable 5 <[email protected]>
…channel cards Replace the flat wall of setting groups with three zones that mirror how notifications actually flow: a pipeline card framing the master switches as Record events -> Fan out -> Deliver (with paused-stage explanations), expandable per-channel cards with collapsed status chips (digest hour, Discord credential state, failing server channels, SSRF warning), and an Advanced zone for fanout tuning and retention. Discord's setup wall becomes a collapsible guide; settings stay editable while a channel is off so admins can configure before enabling. Same setting keys and form plumbing throughout. Co-Authored-By: Claude Fable 5 <[email protected]>
The shared PopoverContent primitive ships with p-0, but the preferences popover never added its own padding, leaving toggle rows flush against the border. Add p-4, separate the master switch from category toggles with a divider, and dim dependent rows while the master switch is off. Co-Authored-By: Claude Fable 5 <[email protected]>
Code reviewFound 1 issue:
silo-server/internal/catalog/encrypted_settings_repo.go Lines 95 to 107 in e1b5bab silo-server/internal/catalog/encrypted_settings_repo_test.go Lines 141 to 157 in e1b5bab 🤖 Generated with Claude Code - If this code review was useful, please react with 👍. Otherwise, react with 👎. |
- pin the four new sensitive setting keys (SMTP password, Discord secret/bot token, VAPID keypair) in the encryption audit test so a future drop from SensitiveSettingKeys fails CI - bound account-channel digest drains strictly before the stamped digest time so consecutive digest windows partition rows exactly, instead of recapping rows created at or after the previous stamp - keep the events websocket open when an event-frame snapshot fails, matching the writeSnapshotFrame degrade-gracefully contract - rename the seed task to Seed Content Availability to match its episode+movie seeding behavior - carry poster_source_path into realtime dispatch rows per the DeliveryRow contract Co-Authored-By: Claude Fable 5 <[email protected]>
Codex + CodeRabbit review fixes, all verified against current behavior: - Web Push: single-writer VAPID provisioning via a new conditional SetIfAbsent settings write (no split-brain identity across nodes), and read/decode failures now surface instead of silently rotating the keypair; the eager-provisioning goroutine joins the shutdown WaitGroup - Web Push: endpoint reassignment purges the previous owner's pending attempts inside the upsert transaction, with an ownership re-check at send time - Webhooks: per-profile cap enforced atomically (advisory-locked count+insert), typed pgconn unique-violation mapping, create-time type/URL mismatch rejection, send-time HTTPS re-check, and Retry-After HTTP-date support (shared, clamped parser also used by web push) - Delivery workers: transient delivery-row lookup errors leave the claim to lease expiry instead of permanently failing the attempt - Interest: history-only imports now feed the index (userstore history hooks + completed-history folding in recompute/rebuild), rebuild also recomputes existing interest rows so removed sources get cleaned up, and failed flush mutations requeue (bounded) instead of dropping - Retention: read notifications age from read_at, not created_at - Startup: scan queue workers start only after the availability detector is wired, so resumed scans cannot skip availability recording - mail: settings-store read failures propagate instead of reading as "not configured" - DB: new migration adds episode ordinal/key CHECK constraints - Web: service worker restricts notification clicks to same-origin URLs, preferences popover gets an error+retry state, and the realtime profile-rebind backoff grows to 5 minutes to keep shared channels stable through notifications-only outages Co-Authored-By: Claude Fable 5 <[email protected]>
Merge feat/notifications-v1: a durable, profile-scoped notification system spanning availability detection, fanout, multi-channel delivery, and the web/admin UI. 19 commits, ~22k lines, 11 migrations. Core pipeline - Availability seeding with per-library seed markers so back-catalog imports never flood; release_events -> profile interest fanout with settling delay and per-series burst caps; FOR UPDATE SKIP LOCKED claims for multi-node safety; durable per-profile inbox with cross-library dedupe; interest tracked via a userstore decorator so every mutation path feeds one chokepoint. - Request-fulfilled notifications delivered across all channels. - Feature flags default ON as kill switches; seeding and backfill run automatically at startup. Channels - In-app inbox with realtime websocket delivery authenticated by single-use handshake tickets, unread badge, per-reason preferences. - Web Push: self-provisioned VAPID keys (private half encrypted at rest), RFC 8291 end-to-end encrypted payloads, service worker and subscribe flow. - Outbound webhooks (gated behind admin opt-in): generic JSON with HMAC signing and Discord webhooks with rich embeds (posters, provider links, ratings); HTTPS-only private-destination guard at registration and connect time; URLs/secrets encrypted at rest; durable outbox with backoff and consecutive-failure auto-disable. - Email: shared SMTP core (internal/mail) with branded HTML templates; per-profile verified addresses with per-episode or digest delivery and unsubscribe links. - Discord bot DMs with account linking flow. - Admin server channels broadcasting new content and request activity to Discord. Web/admin UI - Notifications inbox page, settings with delivery health, sidebar badge; admin settings redesigned around pipeline and channel cards with email config and synchronous test sends. Specs in docs/superpowers/plans/notifications/ (APNs/FCM deferred to v2; remaining follow-ups tracked in the v1.5 roadmap).
#4737) * fix(web): pick a backup warning toggle's singular for exactly one item The backup warning toggles chose "Show the account" or "Show the accounts" with a plural on the count. The label prints no number, and in Russian, Ukrainian, Croatian, Lithuanian, Latvian and Slovenian CLDR's "one" form also covers 21, 31 or 101, so a backup that left out 21 accounts showed the singular label. The toggles now pass "exactlyOne", "exactlyTwo" or "other" to the catalog's select, which keeps the dual Arabic and Slovenian use for exactly two. Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(web): sync translations to 2026.11.21-d2ccdf3 Brings in the backup warning toggle keys that select on {amount} (Silo-Server/silo-translations#132 and #136) and the other catalog changes released since the last pin. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(web): run the backup toggle test on the catalogs CI checks out CI's web tests check out only the English and pseudo-English catalogs, so the test can't import the Russian or Arabic ones. It now formats the pseudo-English catalog under Russian plural rules, and checks the exactly-two branch with a small catalog of its own. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(web): check every backup warning toggle label, closed and open The test read three of the six labels and passed when any one of them differed. It now reads the accounts, files, and file-group toggles both closed and open, and checks each label on its own. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Problem
Silo had no user-facing notification system: a new episode of a favorited or in-progress series arrives silently. The design work in
docs/superpowers/plans/notifications/(imported in this PR) specifies a durable, profile-scoped system; this PR implements everything in it that requires no external infrastructure, plus Web Push and a shared SMTP core.What's included
Foundation (spec 01) — availability seeding with per-library seed markers ("newly available" = newly released to this server; back-catalog imports can never flood),
release_events→profile_series_interestfanout with settling delay, per-series burst caps, andFOR UPDATE SKIP LOCKEDmulti-node claims; durable per-profile inbox with cross-library dedupe; forward-sync cursor API; websocket channel authenticated by short-lived single-use handshake tickets (no tokens in query strings); web inbox + badge + preferences; startup/daily seeding, interest-rebuild, and retention tasks.Outbound webhooks (spec 04) — Discord embeds (text-only per the v1 privacy contract — the user's server origin never reaches Discord) and generic JSON with Stripe-style HMAC signing. HTTPS-only + private-destination guard at registration and connect time (DNS-rebinding mitigation), URLs/secrets encrypted at rest, durable per-target outbox in the fanout transaction, 24h backoff, 3×-consecutive-4xx auto-disable with a loop-guarded in-app notice.
Web Push (spec 05) — ships before APNs/FCM because it needs zero third-party accounts: VAPID keys are self-provisioned at startup (atomic JSON setting, private half encrypted at rest) and payloads are E2E-encrypted (RFC 8291), so the vendor push service never sees content. Service worker + subscribe flow in Settings → Notifications.
Shared SMTP core (
internal/mail, doc) — feature-agnosticmail.Senderover liveemail.*settings with an admin settings page + synchronous test send. No consumer yet by design; the email digest is scoped in the v1.5 roadmap.Why this approach
user_profiles: user state may live in per-user SQLite stores, so profile deletion purges notification rows in code.Linked specs
docs/superpowers/plans/notifications/00–06 (02/03 APNs/FCM deferred to v2 by decision; 06 tracks v1.5 follow-ups).Verification
golangci-lint: 0 issues in the new packages; full Go + web suites green.Risks / follow-ups
pending/retryingoutbox semantics use lease-based claims (90s) + a 60s stale-pending recovery sweep; a crash mid-send delays delivery, never drops it.notifications.*knobs, and request-fulfilled notifications are scoped in the v1.5 roadmap.AI use
Implemented by Claude (Fable 5) under direction, with human review; review fixes (atomic VAPID keypair persistence, user-scoped endpoint unsubscribe) are incorporated.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Documentation