Skip to content

Add Apple push notifications support - #255

Merged
Quick104 merged 3 commits into
mainfrom
feat/push-notifications
Jul 1, 2026
Merged

Quick104 merged 3 commits into
mainfrom
feat/push-notifications

Conversation

@Quick104

@Quick104 Quick104 commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add Apple push relay settings, admin registration flows, and capability exposure
  • Route push delivery through durable outbox and dispatcher paths
  • Add notification display payloads for private in-app enrichment and update admin search/UI

Testing

  • Added and updated unit tests for push settings, payload generation, dispatch, and admin handlers
  • Added UI coverage for the notifications admin settings page

Summary by CodeRabbit

  • New Features

    • Added an Apple/iOS Push Relay channel to admin notifications settings, including relay registration and privacy disclosure.
    • Added Apple push device registration, plus Apple push delivery display metadata endpoints.
    • Enabled Apple push delivery fanout with durable attempts and retry handling via the configured relay.
  • Bug Fixes

    • Updated the Apple push capability indicator to reflect actual availability and enablement.
    • Improved Apple push delivery display behavior (including no-store caching and correct 404/500 handling).
    • Hardened relay configuration: stricter URL handling, and prevented direct edits to managed relay credentials (including no API key leakage).

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f2bbc80e-de18-4e14-a666-1c0c42d269b3

📥 Commits

Reviewing files that changed from the base of the PR and between 9810c79 and b76254a.

📒 Files selected for processing (3)
  • internal/api/handlers/admin.go
  • web/src/pages/admin-settings/NotificationsAdminSettings.test.tsx
  • web/src/pages/admin-settings/NotificationsAdminSettings.tsx

📝 Walkthrough

Walkthrough

This PR adds Apple push device registration, relay-backed delivery attempts, Apple push sending and testing, dynamic notification display metadata, new admin and user API endpoints, database schema, system wiring, and admin settings UI for a Silo Push Relay channel.

Changes

Apple Push Relay Feature

Layer / File(s) Summary
Notification settings and sensitive key handling
internal/notifications/settings.go, internal/catalog/encrypted_settings_repo.go, internal/catalog/encrypted_settings_repo_test.go
Adds Apple push relay setting keys/accessors and marks the relay API key as a sensitive encrypted setting.
Apple push device registration
internal/notifications/push_devices.go, internal/notifications/push_devices_test.go
Defines push device constants, service normalization, repository upsert/delete behavior, and supporting unit and DB-backed tests.
Push delivery attempt persistence
internal/notifications/push_delivery.go
Adds the push delivery attempt model and repository methods for listing devices, enqueueing, claiming, finalizing, and recording outcomes.
Push relay sender and test flow
internal/notifications/push_sender.go, internal/notifications/push_sender_test.go
Implements retry backoff, relay request handling, push test execution, and dispatcher wrapping, plus tests for request construction and error mapping.
Shared channel dispatcher core
internal/notifications/channel_dispatcher.go, internal/notifications/webhook_dispatcher.go, internal/notifications/webpush_sender.go
Introduces a generic dispatcher core and refactors webhook/web-push dispatchers to use shared queue and retry behavior.
Notification display metadata
internal/notifications/display.go, internal/notifications/webpush_sender.go, internal/notifications/webpush_logic_test.go
Adds display metadata generation by delivery type and routes web-push payload rendering through it.
System, fanout, and dispatch wiring
internal/notifications/system.go, internal/notifications/fanout_worker.go, internal/notifications/operational_dispatch.go, internal/notifications/operational_dispatch_test.go
Wires push-device services into system startup, purge, fanout, and operational dispatch paths, with integration coverage for queued Apple push attempts.
Admin Apple push handler and relay registration
internal/api/handlers/admin_apple_push.go, internal/api/handlers/admin_apple_push_test.go, internal/api/handlers/admin.go, internal/api/router.go
Adds admin endpoints for Apple push testing and relay registration, plus setting validation and route wiring.
User-facing push display and device registration
internal/api/handlers/notifications.go, internal/api/handlers/notifications_apple_display_test.go, internal/api/handlers/notifications_push_devices.go, internal/api/handlers/notifications_push_devices_test.go, internal/api/router.go
Adds Apple push display and device registration endpoints, updates capability output, and adds route/test coverage.
Database migrations
migrations/sql/20260701143000_push_devices.sql, migrations/sql/20260701170000_push_delivery_attempts.sql, migrations/push_devices_test.go
Adds tables, constraints, indexes, and contract tests for push devices and delivery attempts.
Admin settings UI
web/src/pages/admin-settings/NotificationsAdminSettings.tsx, web/src/pages/admin-settings/NotificationsAdminSettings.test.tsx, web/src/pages/admin-settings/AdminSettingsLayout.test.tsx, web/src/lib/adminSettingsSearch.ts
Adds the Silo Push Relay admin settings card, relay registration UI, privacy disclosure, and search metadata.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AdminSettingsUI
  participant AdminApplePushHandler
  participant PushRelay
  participant ServerSettings
  AdminSettingsUI->>AdminApplePushHandler: POST /admin/notifications/push/relay/register
  AdminApplePushHandler->>PushRelay: POST /v1/deployments/register
  PushRelay-->>AdminApplePushHandler: deployment_id, api_key, apns_topics
  AdminApplePushHandler->>ServerSettings: persist relay URL, deployment ID, API key
  AdminApplePushHandler-->>AdminSettingsUI: registration response
Loading
sequenceDiagram
  participant FanoutWorker
  participant PushDeviceRepository
  participant PushDispatcher
  participant pushSender
  participant PushRelay
  FanoutWorker->>PushDeviceRepository: ListEnabledAppleByProfiles + EnqueuePushAttempts
  PushDispatcher->>PushDeviceRepository: ClaimPendingPushForDelivery / ClaimDuePushAttempts
  PushDispatcher->>pushSender: processAttempt(attempt)
  pushSender->>PushRelay: POST push payload
  PushRelay-->>pushSender: relay outcome
  pushSender->>PushDeviceRepository: FinalizePushAttempt / RecordPushSuccess / RecordPushFailure
Loading

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the PR’s main change: adding Apple push notifications support.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/push-notifications

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 1, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 02fe3ee685

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

last_failure_code text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT push_devices_profile_device_platform_key UNIQUE (profile_id, device_id, platform),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce one row per APNs token

Because this only dedupes by (profile_id, device_id, platform), the same APNs token can be registered repeatedly under a new local device ID or another profile; ListEnabledAppleByProfiles then fans out to every enabled row, so one physical APNs endpoint can receive duplicate pushes and keep receiving pushes for old profiles after a profile switch/reinstall. Consider making apns_token_hash unique/reassigning the existing row, similar to the web push endpoint model.

Useful? React with 👍 / 👎.

Comment on lines +113 to +114
response.Title != "New episode of Severance" ||
response.Body != "S2E1 - Hello, Ms. Cobel" ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update DB-backed display test expectations

When SILO_TEST_DATABASE_URL is set, this test fails because HandleApplePushDisplay uses BuildNotificationDisplay, whose episode formatter now returns The latest episode of Severance S02E01 just dropped! with body Hello, Ms. Cobel; these older title/body expectations will never match the handler response.

Useful? React with 👍 / 👎.

@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
{}

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (5)
internal/notifications/webpush_logic_test.go (1)

21-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider covering the remaining BuildNotificationDisplay branches.

TestBuildNotificationDisplay only exercises "episode available", "request declined", and "unknown type". request_fulfilled, request_approved, and webhook_auto_disabled are indirectly covered via TestBuildWebPushPayload but their ThreadID/Category fields (unique to NotificationDisplay) aren't asserted anywhere.

Also applies to: 86-119

🤖 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 `@internal/notifications/webpush_logic_test.go` around lines 21 - 24, Expand
TestBuildNotificationDisplay to explicitly cover the remaining
BuildNotificationDisplay branches for request_fulfilled, request_approved, and
webhook_auto_disabled. Use the existing BuildNotificationDisplay function and
assert the NotificationDisplay-specific ThreadID and Category fields for each
case, since these branches are only indirectly exercised in
TestBuildWebPushPayload today. Keep the current coverage for episode available,
request declined, and unknown type, but add direct assertions for the missing
notification types.
internal/notifications/fanout_worker.go (1)

357-389: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate profile-dedup / attempt-construction logic across outboxes.

enqueuePushOutbox repeats the same profile-ID dedup pattern already used in enqueueWebPushOutbox (lines 394-420), and its device→PushDeliveryAttempt construction loop is nearly identical to the one in operational_dispatch.go's push block (lines 82-100). Consider extracting a shared helper (e.g., uniqueProfileIDs(inserted []InsertedDelivery) []string and a buildPushAttempts(deliveryID string, devices []PushDevice) []PushDeliveryAttempt) to avoid the growing copy-paste across these three call sites.

♻️ Example helper extraction
func uniqueProfileIDs(inserted []InsertedDelivery) []string {
	seen := make(map[string]struct{}, len(inserted))
	ids := make([]string, 0, len(inserted))
	for _, row := range inserted {
		if _, ok := seen[row.ProfileID]; !ok {
			seen[row.ProfileID] = struct{}{}
			ids = append(ids, row.ProfileID)
		}
	}
	return ids
}

func buildPushAttempts(deliveryID string, devices []PushDevice) []PushDeliveryAttempt {
	attempts := make([]PushDeliveryAttempt, 0, len(devices))
	for _, device := range devices {
		attempts = append(attempts, PushDeliveryAttempt{
			ID:                     ulid.Make().String(),
			NotificationDeliveryID: &deliveryID,
			PushDeviceID:           device.ID,
			TriggerType:            PushTriggerDelivery,
		})
	}
	return attempts
}
🤖 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 `@internal/notifications/fanout_worker.go` around lines 357 - 389,
`enqueuePushOutbox` is duplicating the profile de-duplication and push-attempt
building logic used elsewhere, so extract shared helpers to keep the outbox code
consistent and easier to maintain. Move the unique profile collection from
`enqueuePushOutbox` and `enqueueWebPushOutbox` into a helper like
`uniqueProfileIDs`, and factor the device-to-`PushDeliveryAttempt` loop into a
reusable builder like `buildPushAttempts` that can be used here and in
`operational_dispatch.go`’s push path. Keep the existing behavior and symbols
such as `InsertedDelivery`, `PushDeliveryAttempt`, and `PushTriggerDelivery`
unchanged while switching the call sites to the new helpers.
web/src/pages/admin-settings/AdminSettingsLayout.test.tsx (1)

16-38: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicate QueryClient construction between the two render helpers.

renderLayout and renderInteractiveLayout both build an identical new QueryClient({ defaultOptions: { queries: { retry: false } } }). Consider factoring this into a shared helper to avoid drift if the options ever need to change.

♻️ Proposed refactor
+function createTestQueryClient() {
+  return new QueryClient({ defaultOptions: { queries: { retry: false } } });
+}
+
 function renderLayout(search = "") {
-  const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+  const client = createTestQueryClient();

   return renderToStaticMarkup(
     <QueryClientProvider client={client}>
       <MemoryRouter initialEntries={[`/admin/settings${search}`]}>
         <AdminSettingsLayout />
       </MemoryRouter>
     </QueryClientProvider>,
   );
 }

 function renderInteractiveLayout(search = "") {
-  const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+  const client = createTestQueryClient();

   return render(
     <QueryClientProvider client={client}>
       <MemoryRouter initialEntries={[`/admin/settings${search}`]}>
         <AdminSettingsLayout />
       </MemoryRouter>
     </QueryClientProvider>,
   );
 }
🤖 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/AdminSettingsLayout.test.tsx` around lines 16 -
38, Both render helpers are duplicating the same QueryClient setup, so factor
the shared `new QueryClient({ defaultOptions: { queries: { retry: false } } })`
construction into a single helper and reuse it from `renderLayout` and
`renderInteractiveLayout`. Keep the `AdminSettingsLayout` test wrappers
unchanged otherwise, and update both helpers to call the shared QueryClient
factory so future option changes stay consistent.
internal/api/handlers/admin_apple_push.go (1)

199-224: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Relay registration failures aren't logged server-side.

Errors from h.client.Do, non-2xx relay responses, and JSON unmarshal failures are only ever returned to the caller — nothing is logged via slog. For a self-hosted relay dependency, this makes production troubleshooting (e.g. "why did relay registration fail last night") harder than necessary.

🤖 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 `@internal/api/handlers/admin_apple_push.go` around lines 199 - 224, Relay
registration failures are only returned, not recorded, so add server-side slog
logging in the relay registration flow around h.client.Do and the response
parsing path. Log when the HTTP request fails, when a non-2xx relay response is
received, and when json.Unmarshal of the relay response fails, using the
existing relayRegistrationError context (status/code/message) so operators can
diagnose failures later. Keep the returned errors unchanged, but ensure each
failure path emits a clear slog entry before returning.
internal/notifications/settings.go (1)

356-382: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicate URL trim logic between write-path and read-path.

PushRelayURL's trailing-slash trim (Line 364) duplicates the same strings.TrimRight(..., "/") normalization done in admin.go's HandleUpdateSetting (Line 2152). Since the write path already normalizes and validates the value, this is currently harmless, but if one side changes (e.g., admin.go loosens/tightens validation) the two could silently diverge.

🤖 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 `@internal/notifications/settings.go` around lines 356 - 382, PushRelayURL
currently repeats the same trailing-slash normalization already performed in
HandleUpdateSetting, so the read path and write path can drift. Update
PushRelayURL in Settings to rely on the stored value as-is (or extract a shared
normalization helper used by both PushRelayURL and HandleUpdateSetting) so there
is a single source of truth for PushRelayURL trimming and validation.
🤖 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/admin_apple_push.go`:
- Around line 156-174: Handle the relay settings update in HandleRegisterRelay
as an atomic operation instead of three independent h.settings.Set calls.
Capture the existing values for notifications.SettingPushRelayURL,
notifications.SettingPushRelayDeploymentID, and
notifications.SettingPushRelayAPIKey up front, then if any later write fails,
roll back the already-written keys to their previous values before returning an
error. Keep the cache invalidation in sync only after all three settings are
successfully persisted.

In `@internal/notifications/push_delivery.go`:
- Around line 286-311: FinalizePushAttempt currently updates
push_delivery_attempts by id only, so a stale worker can overwrite a newer
result after lease expiry. Update the FinalizePushAttempt query to include an
optimistic guard on the previously claimed state and attempt number, using the
existing attemptNumber parameter plus the row’s claim/finalization fields from
PushDeviceRepository. Ensure the UPDATE only applies when the row still matches
the expected in-flight attempt, and handle the no-row-updated case as a stale
finalize rather than success.

In `@internal/notifications/push_devices.go`:
- Around line 141-162: Normalize push_mode the same way as APNsEnvironment in
push_devices.go: in the registration validation path, trim and lowercase the
value before the switch so case-insensitive inputs are accepted consistently.
Update the PushDevices registration logic around the pushMode handling to
compare against the normalized value, while still defaulting empty input to
PushModePrivatePush. Also adjust or add tests for the
ApplePushDeviceRegistration flow to cover mixed-case push_mode values like “OFF”
and “Private_Push”.

In `@internal/notifications/push_sender.go`:
- Around line 105-106: The `processAttempt` path in `push_sender.go` is
permanently failing claimed deliveries when `ApplePushDeliveryEnabled(ctx)` is
false, which should instead be retried later. Update the logic around the
`processAttempt`/`finalize` flow to separate the global delivery-toggle check
from device invalidation: keep device-level failures going through `finalize`,
but when Apple push delivery is globally disabled, do not mark the attempt as
failed and do not finalize the row so the queued work remains eligible for
retry.
- Around line 133-137: The push success path in push_sender.go ignores the error
from FinalizePushAttempt, which can mark the device as successful even when the
attempt was not finalized. In the result.OK branch of the push sender logic,
check and handle the error returned by s.devices.FinalizePushAttempt before
calling s.devices.RecordPushSuccess, and abort or log/return on failure so
success metadata is only updated after finalization succeeds.

In `@migrations/sql/20260701143000_push_devices.sql`:
- Around line 3-36: The push_devices_apple_fields_check constraint is written as
an unconditional AND, so it currently requires every row to be apple instead of
only requiring APNS fields when platform is apple. Update the CHECK in the
push_devices table definition to use a conditional implication pattern, similar
to push_delivery_attempts_delivery_required_check, so non-apple platforms can be
added later without failing this constraint while still enforcing apns_* fields
for apple rows.

---

Nitpick comments:
In `@internal/api/handlers/admin_apple_push.go`:
- Around line 199-224: Relay registration failures are only returned, not
recorded, so add server-side slog logging in the relay registration flow around
h.client.Do and the response parsing path. Log when the HTTP request fails, when
a non-2xx relay response is received, and when json.Unmarshal of the relay
response fails, using the existing relayRegistrationError context
(status/code/message) so operators can diagnose failures later. Keep the
returned errors unchanged, but ensure each failure path emits a clear slog entry
before returning.

In `@internal/notifications/fanout_worker.go`:
- Around line 357-389: `enqueuePushOutbox` is duplicating the profile
de-duplication and push-attempt building logic used elsewhere, so extract shared
helpers to keep the outbox code consistent and easier to maintain. Move the
unique profile collection from `enqueuePushOutbox` and `enqueueWebPushOutbox`
into a helper like `uniqueProfileIDs`, and factor the
device-to-`PushDeliveryAttempt` loop into a reusable builder like
`buildPushAttempts` that can be used here and in `operational_dispatch.go`’s
push path. Keep the existing behavior and symbols such as `InsertedDelivery`,
`PushDeliveryAttempt`, and `PushTriggerDelivery` unchanged while switching the
call sites to the new helpers.

In `@internal/notifications/settings.go`:
- Around line 356-382: PushRelayURL currently repeats the same trailing-slash
normalization already performed in HandleUpdateSetting, so the read path and
write path can drift. Update PushRelayURL in Settings to rely on the stored
value as-is (or extract a shared normalization helper used by both PushRelayURL
and HandleUpdateSetting) so there is a single source of truth for PushRelayURL
trimming and validation.

In `@internal/notifications/webpush_logic_test.go`:
- Around line 21-24: Expand TestBuildNotificationDisplay to explicitly cover the
remaining BuildNotificationDisplay branches for request_fulfilled,
request_approved, and webhook_auto_disabled. Use the existing
BuildNotificationDisplay function and assert the NotificationDisplay-specific
ThreadID and Category fields for each case, since these branches are only
indirectly exercised in TestBuildWebPushPayload today. Keep the current coverage
for episode available, request declined, and unknown type, but add direct
assertions for the missing notification types.

In `@web/src/pages/admin-settings/AdminSettingsLayout.test.tsx`:
- Around line 16-38: Both render helpers are duplicating the same QueryClient
setup, so factor the shared `new QueryClient({ defaultOptions: { queries: {
retry: false } } })` construction into a single helper and reuse it from
`renderLayout` and `renderInteractiveLayout`. Keep the `AdminSettingsLayout`
test wrappers unchanged otherwise, and update both helpers to call the shared
QueryClient factory so future option changes stay consistent.
🪄 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: 409c915c-fe06-46be-a5d8-631b12d44e95

📥 Commits

Reviewing files that changed from the base of the PR and between 656c487 and 02fe3ee.

📒 Files selected for processing (30)
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_apple_push.go
  • internal/api/handlers/admin_apple_push_test.go
  • internal/api/handlers/notifications.go
  • internal/api/handlers/notifications_apple_display_test.go
  • internal/api/handlers/notifications_push_devices.go
  • internal/api/handlers/notifications_push_devices_test.go
  • internal/api/router.go
  • internal/catalog/encrypted_settings_repo.go
  • internal/catalog/encrypted_settings_repo_test.go
  • internal/notifications/display.go
  • internal/notifications/fanout_worker.go
  • internal/notifications/operational_dispatch.go
  • internal/notifications/operational_dispatch_test.go
  • internal/notifications/push_delivery.go
  • internal/notifications/push_devices.go
  • internal/notifications/push_devices_test.go
  • internal/notifications/push_sender.go
  • internal/notifications/push_sender_test.go
  • internal/notifications/settings.go
  • internal/notifications/system.go
  • internal/notifications/webpush_logic_test.go
  • internal/notifications/webpush_sender.go
  • migrations/push_devices_test.go
  • migrations/sql/20260701143000_push_devices.sql
  • migrations/sql/20260701170000_push_delivery_attempts.sql
  • web/src/lib/adminSettingsSearch.ts
  • web/src/pages/admin-settings/AdminSettingsLayout.test.tsx
  • web/src/pages/admin-settings/NotificationsAdminSettings.test.tsx
  • web/src/pages/admin-settings/NotificationsAdminSettings.tsx

Comment on lines +156 to +174
if err := h.settings.Set(r.Context(), notifications.SettingPushRelayURL, relayURL); err != nil {
writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay URL")
return
}
if err := h.settings.Set(r.Context(), notifications.SettingPushRelayDeploymentID, relayResp.DeploymentID); err != nil {
writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay deployment id")
return
}
if err := h.settings.Set(r.Context(), notifications.SettingPushRelayAPIKey, relayResp.APIKey); err != nil {
writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay API key")
return
}
if h.system != nil && h.system.Settings != nil {
h.system.Settings.Invalidate(
notifications.SettingPushRelayURL,
notifications.SettingPushRelayDeploymentID,
notifications.SettingPushRelayAPIKey,
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Non-atomic multi-key settings write can leave relay config inconsistent.

HandleRegisterRelay writes SettingPushRelayURL, SettingPushRelayDeploymentID, and SettingPushRelayAPIKey via three sequential Set calls. If the process crashes or a later call fails (e.g. encryption error, transient DB failure) after an earlier one succeeds, the server ends up with a relay URL that doesn't match the persisted deployment ID/API key — silently breaking previously-working push delivery until an admin retries. Per the upstream contract, EncryptedSettingsRepo.Set encrypts sensitive setting keys (when value is non-empty) before delegating to the inner settings store per-call, with no visible multi-key transaction support.

Consider capturing the previous values up front and rolling back on partial failure, or persisting all three under a single settings entry so the write is atomic.

🔧 Suggested best-effort rollback
+	oldURL, _ := h.settings.Get(r.Context(), notifications.SettingPushRelayURL)
+	oldAPIKey, _ := h.settings.Get(r.Context(), notifications.SettingPushRelayAPIKey)
+
 	if err := h.settings.Set(r.Context(), notifications.SettingPushRelayURL, relayURL); err != nil {
 		writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay URL")
 		return
 	}
 	if err := h.settings.Set(r.Context(), notifications.SettingPushRelayDeploymentID, relayResp.DeploymentID); err != nil {
+		_ = h.settings.Set(r.Context(), notifications.SettingPushRelayURL, oldURL)
 		writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay deployment id")
 		return
 	}
 	if err := h.settings.Set(r.Context(), notifications.SettingPushRelayAPIKey, relayResp.APIKey); err != nil {
+		_ = h.settings.Set(r.Context(), notifications.SettingPushRelayURL, oldURL)
+		_ = h.settings.Set(r.Context(), notifications.SettingPushRelayAPIKey, oldAPIKey)
 		writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay API key")
 		return
 	}
🤖 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 `@internal/api/handlers/admin_apple_push.go` around lines 156 - 174, Handle the
relay settings update in HandleRegisterRelay as an atomic operation instead of
three independent h.settings.Set calls. Capture the existing values for
notifications.SettingPushRelayURL, notifications.SettingPushRelayDeploymentID,
and notifications.SettingPushRelayAPIKey up front, then if any later write
fails, roll back the already-written keys to their previous values before
returning an error. Keep the cache invalidation in sync only after all three
settings are successfully persisted.

Comment on lines +286 to +311
func (r *PushDeviceRepository) FinalizePushAttempt(ctx context.Context, attemptID, outcome string, attemptNumber int, relayRequestID string, upstreamStatus *int, upstreamReason, failureMessage string, nextRetryAt *time.Time) (*PushDeliveryAttempt, error) {
var relayRequestIDPtr *string
if relayRequestID != "" {
relayRequestIDPtr = &relayRequestID
}
var upstreamReasonPtr *string
if upstreamReason != "" {
upstreamReasonPtr = &upstreamReason
}
var failureMessagePtr *string
if failureMessage != "" {
failureMessagePtr = &failureMessage
}
rows, err := r.pool.Query(ctx, `
UPDATE push_delivery_attempts
SET outcome = $2,
attempt_number = $3,
attempted_at = now(),
next_retry_at = $4,
relay_request_id = $5,
upstream_status = $6,
upstream_reason = left($7, 256),
failure_message = left($8, 256),
updated_at = now()
WHERE id = $1`+pushAttemptReturning,
attemptID, outcome, attemptNumber, nextRetryAt, relayRequestIDPtr, upstreamStatus, upstreamReasonPtr, failureMessagePtr)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Guard finalization against stale workers.

FinalizePushAttempt updates by id only. If one worker exceeds the claim lease, another worker can reclaim/finalize the same row, and the stale worker can later overwrite the newer outcome. Add an optimistic guard on the claimed state and previous attempt number.

Proposed fix
-		WHERE id = $1`+pushAttemptReturning,
-		attemptID, outcome, attemptNumber, nextRetryAt, relayRequestIDPtr, upstreamStatus, upstreamReasonPtr, failureMessagePtr)
+		WHERE id = $1
+		  AND outcome = $9
+		  AND attempt_number = $3 - 1`+pushAttemptReturning,
+		attemptID, outcome, attemptNumber, nextRetryAt, relayRequestIDPtr, upstreamStatus, upstreamReasonPtr, failureMessagePtr, PushOutcomeRetrying)
📝 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.

Suggested change
func (r *PushDeviceRepository) FinalizePushAttempt(ctx context.Context, attemptID, outcome string, attemptNumber int, relayRequestID string, upstreamStatus *int, upstreamReason, failureMessage string, nextRetryAt *time.Time) (*PushDeliveryAttempt, error) {
var relayRequestIDPtr *string
if relayRequestID != "" {
relayRequestIDPtr = &relayRequestID
}
var upstreamReasonPtr *string
if upstreamReason != "" {
upstreamReasonPtr = &upstreamReason
}
var failureMessagePtr *string
if failureMessage != "" {
failureMessagePtr = &failureMessage
}
rows, err := r.pool.Query(ctx, `
UPDATE push_delivery_attempts
SET outcome = $2,
attempt_number = $3,
attempted_at = now(),
next_retry_at = $4,
relay_request_id = $5,
upstream_status = $6,
upstream_reason = left($7, 256),
failure_message = left($8, 256),
updated_at = now()
WHERE id = $1`+pushAttemptReturning,
attemptID, outcome, attemptNumber, nextRetryAt, relayRequestIDPtr, upstreamStatus, upstreamReasonPtr, failureMessagePtr)
func (r *PushDeviceRepository) FinalizePushAttempt(ctx context.Context, attemptID, outcome string, attemptNumber int, relayRequestID string, upstreamStatus *int, upstreamReason, failureMessage string, nextRetryAt *time.Time) (*PushDeliveryAttempt, error) {
var relayRequestIDPtr *string
if relayRequestID != "" {
relayRequestIDPtr = &relayRequestID
}
var upstreamReasonPtr *string
if upstreamReason != "" {
upstreamReasonPtr = &upstreamReason
}
var failureMessagePtr *string
if failureMessage != "" {
failureMessagePtr = &failureMessage
}
rows, err := r.pool.Query(ctx, `
UPDATE push_delivery_attempts
SET outcome = $2,
attempt_number = $3,
attempted_at = now(),
next_retry_at = $4,
relay_request_id = $5,
upstream_status = $6,
upstream_reason = left($7, 256),
failure_message = left($8, 256),
updated_at = now()
WHERE id = $1
AND outcome = $9
AND attempt_number = $3 - 1`+pushAttemptReturning,
attemptID, outcome, attemptNumber, nextRetryAt, relayRequestIDPtr, upstreamStatus, upstreamReasonPtr, failureMessagePtr, PushOutcomeRetrying)
🤖 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 `@internal/notifications/push_delivery.go` around lines 286 - 311,
FinalizePushAttempt currently updates push_delivery_attempts by id only, so a
stale worker can overwrite a newer result after lease expiry. Update the
FinalizePushAttempt query to include an optimistic guard on the previously
claimed state and attempt number, using the existing attemptNumber parameter
plus the row’s claim/finalization fields from PushDeviceRepository. Ensure the
UPDATE only applies when the row still matches the expected in-flight attempt,
and handle the no-row-updated case as a stale finalize rather than success.

Comment on lines +141 to +162
environment := strings.ToLower(strings.TrimSpace(input.APNsEnvironment))
if environment != APNsEnvironmentProd && environment != APNsEnvironmentSandbox {
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_environment must be production or sandbox", ErrPushDeviceInvalid)
}

topic := strings.TrimSpace(input.APNsTopic)
if topic == "" {
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is required", ErrPushDeviceInvalid)
}
if topic != ApplePushTopicSilo {
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is not supported", ErrPushDeviceUnsupported)
}

pushMode := strings.TrimSpace(input.PushMode)
if pushMode == "" {
pushMode = PushModePrivatePush
}
switch pushMode {
case PushModeOff, PushModeInAppOnly, PushModePrivatePush:
default:
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: push_mode is not supported", ErrPushDeviceUnsupported)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Inconsistent case normalization for push_mode.

APNsEnvironment is lowercased before comparison (line 141), but PushMode is only trimmed (line 154) and compared with case-sensitive switch. A client sending "Private_Push" or "OFF" will be rejected with ErrPushDeviceUnsupported even though the equivalent lowercase value is valid — an inconsistency with the environment field's normalization and untested by the current test suite (which only exercises exact-case constants).

🐛 Proposed fix
-	pushMode := strings.TrimSpace(input.PushMode)
+	pushMode := strings.ToLower(strings.TrimSpace(input.PushMode))
 	if pushMode == "" {
 		pushMode = PushModePrivatePush
 	}
📝 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.

Suggested change
environment := strings.ToLower(strings.TrimSpace(input.APNsEnvironment))
if environment != APNsEnvironmentProd && environment != APNsEnvironmentSandbox {
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_environment must be production or sandbox", ErrPushDeviceInvalid)
}
topic := strings.TrimSpace(input.APNsTopic)
if topic == "" {
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is required", ErrPushDeviceInvalid)
}
if topic != ApplePushTopicSilo {
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is not supported", ErrPushDeviceUnsupported)
}
pushMode := strings.TrimSpace(input.PushMode)
if pushMode == "" {
pushMode = PushModePrivatePush
}
switch pushMode {
case PushModeOff, PushModeInAppOnly, PushModePrivatePush:
default:
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: push_mode is not supported", ErrPushDeviceUnsupported)
}
environment := strings.ToLower(strings.TrimSpace(input.APNsEnvironment))
if environment != APNsEnvironmentProd && environment != APNsEnvironmentSandbox {
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_environment must be production or sandbox", ErrPushDeviceInvalid)
}
topic := strings.TrimSpace(input.APNsTopic)
if topic == "" {
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is required", ErrPushDeviceInvalid)
}
if topic != ApplePushTopicSilo {
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is not supported", ErrPushDeviceUnsupported)
}
pushMode := strings.ToLower(strings.TrimSpace(input.PushMode))
if pushMode == "" {
pushMode = PushModePrivatePush
}
switch pushMode {
case PushModeOff, PushModeInAppOnly, PushModePrivatePush:
default:
return ApplePushDeviceRegistration{}, fmt.Errorf("%w: push_mode is not supported", ErrPushDeviceUnsupported)
}
🤖 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 `@internal/notifications/push_devices.go` around lines 141 - 162, Normalize
push_mode the same way as APNsEnvironment in push_devices.go: in the
registration validation path, trim and lowercase the value before the switch so
case-insensitive inputs are accepted consistently. Update the PushDevices
registration logic around the pushMode handling to compare against the
normalized value, while still defaulting empty input to PushModePrivatePush.
Also adjust or add tests for the ApplePushDeviceRegistration flow to cover
mixed-case push_mode values like “OFF” and “Private_Push”.

Comment thread internal/notifications/push_sender.go Resolved
Comment on lines +133 to +137
if result.OK {
updated, _ := s.devices.FinalizePushAttempt(ctx, attempt.ID, PushOutcomeDelivered, attemptNumber,
result.RelayRequestID, &result.HTTPStatus, result.UpstreamReason, "", nil)
_ = s.devices.RecordPushSuccess(ctx, device.ID)
return updated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Handle finalization failure before recording success.

If the relay accepts the push but FinalizePushAttempt fails, the attempt remains retryable and may be sent again later. Don’t ignore this error; log/return before updating device success metadata.

Proposed fix
 	if result.OK {
-		updated, _ := s.devices.FinalizePushAttempt(ctx, attempt.ID, PushOutcomeDelivered, attemptNumber,
+		updated, err := s.devices.FinalizePushAttempt(ctx, attempt.ID, PushOutcomeDelivered, attemptNumber,
 			result.RelayRequestID, &result.HTTPStatus, result.UpstreamReason, "", nil)
+		if err != nil && ctx.Err() == nil {
+			s.logger.Warn("finalize delivered push attempt failed", "attempt_id", attempt.ID, "error", err)
+			return nil
+		}
 		_ = s.devices.RecordPushSuccess(ctx, device.ID)
 		return updated
 	}
🤖 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 `@internal/notifications/push_sender.go` around lines 133 - 137, The push
success path in push_sender.go ignores the error from FinalizePushAttempt, which
can mark the device as successful even when the attempt was not finalized. In
the result.OK branch of the push sender logic, check and handle the error
returned by s.devices.FinalizePushAttempt before calling
s.devices.RecordPushSuccess, and abort or log/return on failure so success
metadata is only updated after finalization succeeds.

Comment on lines +3 to +36
CREATE TABLE public.push_devices (
id text PRIMARY KEY,
user_id integer NOT NULL,
profile_id text NOT NULL,
device_id varchar(128) NOT NULL,
platform text NOT NULL,
provider text NOT NULL,
apns_environment text,
apns_topic text,
apns_token_ciphertext text,
apns_token_hash text,
server_device_id text NOT NULL,
push_mode text NOT NULL DEFAULT 'private_push',
enabled boolean NOT NULL DEFAULT true,
last_seen_at timestamptz,
last_success_at timestamptz,
last_failure_at timestamptz,
last_failure_code text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT push_devices_profile_device_platform_key UNIQUE (profile_id, device_id, platform),
CONSTRAINT push_devices_server_device_id_key UNIQUE (server_device_id),
CONSTRAINT push_devices_platform_check CHECK (platform IN ('apple')),
CONSTRAINT push_devices_provider_check CHECK (provider IN ('silo_relay')),
CONSTRAINT push_devices_apns_environment_check CHECK (apns_environment IN ('production', 'sandbox')),
CONSTRAINT push_devices_push_mode_check CHECK (push_mode IN ('off', 'in_app_only', 'private_push')),
CONSTRAINT push_devices_apple_fields_check CHECK (
platform = 'apple'
AND apns_environment IS NOT NULL
AND apns_topic IS NOT NULL
AND apns_token_ciphertext IS NOT NULL
AND apns_token_hash IS NOT NULL
)
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

push_devices_apple_fields_check is an unconditional AND, not a per-platform implication.

Lines 29-35 read:

CONSTRAINT push_devices_apple_fields_check CHECK (
    platform = 'apple'
    AND apns_environment IS NOT NULL
    ...
)

This forces every row to have platform = 'apple' — it's not "if apple then these fields are required" (which the nullable apns_* columns imply is the intent), it's "every row must be apple AND have these fields." Today this is harmless only because push_devices_platform_check already restricts platform IN ('apple'). But the moment a future migration adds another platform (e.g. android), any such row will violate this constraint and fail to insert, since it isn't 'apple'. The sibling migration in this same PR (push_delivery_attempts_delivery_required_check) correctly implements this same "required-if" pattern as an implication ((trigger_type = 'delivery' AND ... IS NOT NULL) OR trigger_type = 'test'), so this constraint should follow the same shape.

🐛 Proposed fix
     CONSTRAINT push_devices_apple_fields_check CHECK (
-        platform = 'apple'
-        AND apns_environment IS NOT NULL
-        AND apns_topic IS NOT NULL
-        AND apns_token_ciphertext IS NOT NULL
-        AND apns_token_hash IS NOT NULL
+        platform != 'apple'
+        OR (
+            apns_environment IS NOT NULL
+            AND apns_topic IS NOT NULL
+            AND apns_token_ciphertext IS NOT NULL
+            AND apns_token_hash IS NOT NULL
+        )
     )
🤖 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/20260701143000_push_devices.sql` around lines 3 - 36, The
push_devices_apple_fields_check constraint is written as an unconditional AND,
so it currently requires every row to be apple instead of only requiring APNS
fields when platform is apple. Update the CHECK in the push_devices table
definition to use a conditional implication pattern, similar to
push_delivery_attempts_delivery_required_check, so non-apple platforms can be
added later without failing this constraint while still enforcing apns_* fields
for apple rows.

- Gate the capability endpoint's apple_push availability on the admin
  delivery toggle, matching web push: Available now means setup will
  actually deliver.
- Reject direct admin writes to push_relay_deployment_id/api_key; the
  relay issues them as a pair during registration and a lone write
  desyncs them (and poisons the next rotation request).
- Purge a device's registrations under other profiles when it
  re-registers, so a profile switch on a shared device stops the old
  profile's pushes (attempts cascade); adds a DB-backed test.
- Extract the shared channelDispatcher core + retry sweep and rebuild
  the webhook/web push/Apple push dispatchers on it instead of keeping
  three copies of the worker-pool/retry loop.
- Deduplicate relay URL validation (admin setting + register flow) and
  the push outbox attempt-building loops behind shared helpers.
- Cap free-text decline reasons in notification display bodies.
- Fix TestHandleApplePushDisplayDB expectations to match the shared
  display copy (test previously failed under SILO_TEST_DATABASE_URL).

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Quick104 commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 9810c79 addressing the code-review findings:

  1. Capability gating — HandleCapability now reports apple_push.available only when notifications.apple_push_delivery_enabled is on (in addition to the cipher/store wiring), matching how the adjacent web push block gates on its setting. The device registration endpoint itself stays available so clients holding tokens keep them fresh across admin toggles.
  2. Relay credential pairing — PUT /admin/settings/notifications.push_relay_deployment_id (and ...push_relay_api_key) is now rejected with a pointer to POST /admin/notifications/push/relay/register; the relay issues the pair atomically and a lone write desyncs them or feeds an arbitrary id into the next rotation.
  3. Stale cross-profile registrations — UpsertApple now purges the same install's rows under other profiles inside the upsert transaction (delivery attempts cascade), so a profile switch on a shared device stops the previous profile's pushes. Covered by a new DB-backed test (TestPushDeviceRepositoryUpsertApplePurgesOtherProfiles).
  4. Dispatcher dedup — extracted a generic channelDispatcher core (bounded worker pool + optional retry sweep); the webhook, web push, and Apple push dispatchers and the webhook retry worker are now thin wrappers instead of three copies of the loop.
  5. Smaller dedup — relay URL validation shared between the admin setting and register flow (including the default-URL literal via notifications.DefaultPushRelayURL); push outbox attempt construction shared between fanout and operational dispatch via newPushDeliveryAttempts.
  6. Display body cap — free-text decline reasons are truncated to 240 chars in BuildNotificationDisplay.
  7. Test fix — TestHandleApplePushDisplayDB asserted display copy the shared builder never produced and failed under SILO_TEST_DATABASE_URL; expectations updated to the canonical copy already asserted in webpush_logic_test.go.

Verified with go build ./..., go test for internal/notifications, internal/api/handlers, and migrations against a freshly migrated database, plus a golangci-lint before/after diff (no new findings).

🤖 Generated with Claude Code

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/notifications/webpush_sender.go (1)

9-10: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Keep fmt imported while fmt.Sprintf is still used.

The import cleanup removed fmt, but Line 191 still calls fmt.Sprintf, so this file will not compile.

Proposed fix
 import (
 	"context"
+	"fmt"
 	"log/slog"
 	"net/http"
 	"time"
 )
🤖 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 `@internal/notifications/webpush_sender.go` around lines 9 - 10, The import
cleanup in webpush_sender.go removed fmt even though WebpushSender still uses
fmt.Sprintf, so the file no longer compiles. Restore the fmt import alongside
the existing imports and verify the formatting call in the WebpushSender path
still resolves correctly without changing the current string construction logic.
🧹 Nitpick comments (1)
internal/notifications/display.go (1)

122-133: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Guard against max <= 0 to avoid a slice panic.

runes[:max-1] underflows to a negative index if max is ever 0 or negative. The only current call site passes the fixed displayBodyMaxLen (240), so this isn't reachable today, but the helper is general-purpose and a future caller with a smaller/zero bound would panic instead of degrading gracefully.

🛡️ Optional defensive guard
 func truncateDisplayText(s string, max int) string {
+	if max <= 0 {
+		return ""
+	}
 	runes := []rune(s)
 	if len(runes) <= max {
 		return s
 	}
 	return strings.TrimSpace(string(runes[:max-1])) + "…"
 }
🤖 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 `@internal/notifications/display.go` around lines 122 - 133,
truncateDisplayText should defensively handle max <= 0 before slicing runes,
since runes[:max-1] can panic on zero or negative bounds. Update the helper to
return a safe fallback (for example, the original string or an empty/truncated
result without slicing) when max is non-positive, while keeping the existing
behavior for valid limits; this change belongs in truncateDisplayText near
displayBodyMaxLen.
🤖 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/admin.go`:
- Around line 2152-2164: Direct writes to notifications.push_relay_url in
admin.go still bypass the push relay registration flow and can leave the stored
URL out of sync with the deployment ID/API key pair. Update the settings
handling in the same switch that already rejects
notifications.SettingPushRelayDeploymentID and
notifications.SettingPushRelayAPIKey so that notifications.SettingPushRelayURL
is also rejected with a bad_request and a message pointing to
HandleRegisterRelay / POST /admin/notifications/push/relay/register. Keep
HandleRegisterRelay as the only path that persists the URL, deployment ID, and
API key together.

---

Outside diff comments:
In `@internal/notifications/webpush_sender.go`:
- Around line 9-10: The import cleanup in webpush_sender.go removed fmt even
though WebpushSender still uses fmt.Sprintf, so the file no longer compiles.
Restore the fmt import alongside the existing imports and verify the formatting
call in the WebpushSender path still resolves correctly without changing the
current string construction logic.

---

Nitpick comments:
In `@internal/notifications/display.go`:
- Around line 122-133: truncateDisplayText should defensively handle max <= 0
before slicing runes, since runes[:max-1] can panic on zero or negative bounds.
Update the helper to return a safe fallback (for example, the original string or
an empty/truncated result without slicing) when max is non-positive, while
keeping the existing behavior for valid limits; this change belongs in
truncateDisplayText near displayBodyMaxLen.
🪄 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: 7a41a38a-f05e-4497-9f61-62f64f60374b

📥 Commits

Reviewing files that changed from the base of the PR and between 02fe3ee and 9810c79.

📒 Files selected for processing (16)
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_apple_push.go
  • internal/api/handlers/notifications.go
  • internal/api/handlers/notifications_apple_display_test.go
  • internal/notifications/channel_dispatcher.go
  • internal/notifications/display.go
  • internal/notifications/fanout_worker.go
  • internal/notifications/operational_dispatch.go
  • internal/notifications/push_delivery.go
  • internal/notifications/push_devices.go
  • internal/notifications/push_devices_test.go
  • internal/notifications/push_sender.go
  • internal/notifications/push_sender_test.go
  • internal/notifications/settings.go
  • internal/notifications/webhook_dispatcher.go
  • internal/notifications/webpush_sender.go
🚧 Files skipped from review as they are similar to previous changes (10)
  • internal/notifications/operational_dispatch.go
  • internal/api/handlers/notifications_apple_display_test.go
  • internal/notifications/push_sender_test.go
  • internal/notifications/settings.go
  • internal/notifications/push_devices_test.go
  • internal/notifications/fanout_worker.go
  • internal/api/handlers/notifications.go
  • internal/notifications/push_delivery.go
  • internal/api/handlers/admin_apple_push.go
  • internal/notifications/push_devices.go

Comment thread internal/api/handlers/admin.go Resolved
…only

Direct writes to notifications.push_relay_url via the admin settings
endpoint bypassed the relay registration flow, letting the stored URL
drift out of sync with the deployment id / API key pair the relay
minted for it. Reject the URL alongside the deployment id and API key
in the settings handler; POST /admin/notifications/push/relay/register
remains the only path that persists all three together.

The admin UI's Relay URL field now edits local draft state and is
applied by the Register/Rotate action instead of the settings save.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 merged commit 82d0a89 into main Jul 1, 2026
1 check was pending
@Quick104
Quick104 deleted the feat/push-notifications branch July 1, 2026 21:25
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
* Add push notifications support

* fix(notifications): address push notification review findings

- Gate the capability endpoint's apple_push availability on the admin
  delivery toggle, matching web push: Available now means setup will
  actually deliver.
- Reject direct admin writes to push_relay_deployment_id/api_key; the
  relay issues them as a pair during registration and a lone write
  desyncs them (and poisons the next rotation request).
- Purge a device's registrations under other profiles when it
  re-registers, so a profile switch on a shared device stops the old
  profile's pushes (attempts cascade); adds a DB-backed test.
- Extract the shared channelDispatcher core + retry sweep and rebuild
  the webhook/web push/Apple push dispatchers on it instead of keeping
  three copies of the worker-pool/retry loop.
- Deduplicate relay URL validation (admin setting + register flow) and
  the push outbox attempt-building loops behind shared helpers.
- Cap free-text decline reasons in notification display bodies.
- Fix TestHandleApplePushDisplayDB expectations to match the shared
  display copy (test previously failed under SILO_TEST_DATABASE_URL).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(notifications): route push relay URL writes through registration only

Direct writes to notifications.push_relay_url via the admin settings
endpoint bypassed the relay registration flow, letting the stored URL
drift out of sync with the deployment id / API key pair the relay
minted for it. Reject the URL alongside the deployment id and API key
in the settings handler; POST /admin/notifications/push/relay/register
remains the only path that persists all three together.

The admin UI's Relay URL field now edits local draft state and is
applied by the Register/Rotate action instead of the settings save.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant