Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(notifications): browser push notifications (#1867)

Naveen Kashyapa270acc4578b
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 7e0c953164..555dc1a09d 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2945,7 +2945,8 @@ with no actions — indistinguishable from "nothing to do". Demo data and hand-m
(a few actions each) never came near the limit; it took load data to see it.
**Rule:** An id list for `.in()` must be bounded by something you control (the page size), and
-chunked when that bound is large — about 100 ids per request. When the related rows hang off
+chunked when that bound is large — about 100 ids per request (`fetchAllByIds` in
+`@carbon/database` does the chunking and the paging). When the related rows hang off
a foreign key, embed them in the first read instead of looking them up afterwards. And a
loader never swaps a failed read for an empty list: log it and throw.
@@ -3334,6 +3335,47 @@ of `salesInvoice`; backfilled by `20261006220901_sales-invoice-opportunity-backf
**Applies to:** `packages/jobs/src/inngest/functions/tasks/company-restore.ts` (`wipeAndLoad`); any new job that sets `session_replication_role`.
+## macOS silently replaces a web notification that reuses a tag
+
+**Context:** Browser push notifications (`apps/erp/public/push-worker.js`) passed each notification's `tag` (`job-assignment:<id>`, `carbon-test`) to `showNotification`, so a second push about the same thing would replace the first instead of stacking.
+
+**Problem:** On macOS the browser hands the tag to the OS as the notification's identifier, and the OS replaces a notification with the same identifier silently: no banner, only an updated entry in Notification Center. The first test arrived while banners were still off, and every later test replaced it without a sound, so push looked broken although every send returned `201` (2026-10-08). `renotify: true` did not change it. The cause was only visible in the macOS log (`log show --predicate 'process == "usernoted"'`): `updatedExisting: true`.
+
+**Rule:** Never pass a reused `tag` to `showNotification` when the user must see the repeat. Close the older notifications yourself (`registration.getNotifications()`, match on `notification.data.tag`), then show the new one with no `tag`, so it gets a fresh identifier. To debug a push that "does not arrive", read the send's status code first, then the OS notification log, before changing code.
+
+**Applies to:** `apps/erp/public/push-worker.js`; any future service worker or Notification API caller.
+
+## A new key in an Inngest step's return breaks runs in flight at deploy
+
+**Context:** The `notify` function's step `filter-recipients-by-preference` returned `{ emailRecipientIds, slackRecipientIds }`. Browser notifications added `pushRecipientIds` to the same step, under the same step id, and the code after it read `pushRecipientIds.length` (2026-10-08).
+
+**Problem:** Inngest replays a completed step from its memoized output. A run that started before the deploy and resumes after it gets the OLD output, with no `pushRecipientIds`, so `.length` throws and the notification fails. Typecheck cannot see it: the type describes the new code, not the stored output. Self-review caught it before merge.
+
+**Rule:** When a step's return grows a key, read that key with a default (`pushRecipientIds = []`) and comment why, or rename the step id so old runs re-execute it (only when the step is idempotent). Never assume a memoized step output has the current shape. (The `pushRecipientIds` key was removed again later, when push stopped having a per-topic switch; the example stays as the pattern.)
+
+**Applies to:** every `step.run` in `packages/jobs/src/inngest/functions/**` whose return shape changes.
+
+
+## A notification click on an uncontrolled tab opens nothing
+
+**Context:** `push-worker.js` handled `notificationclick` with `clients.matchAll({ type: "window", includeUncontrolled: true })`, then `focus()` and `navigate()` on the first Carbon tab (2026-10-09).
+
+**Problem:** `WindowClient.navigate()` rejects for a tab the worker does not control: a tab opened before the worker was installed, or a hard-reloaded one. The rejection ended the click handler, so the click opened nothing. No error reached the page.
+
+**Rule:** Call `matchAll({ type: "window" })` without `includeUncontrolled` when you will call `navigate()`. Focus first, because the click allows focus for a short time only. Wrap the focus and the navigation in `try`, and call `clients.openWindow()` when either fails or no tab exists.
+
+**Applies to:** `apps/erp/public/push-worker.js`; any service worker that navigates a client.
+
+## A push service's 401 or 403 does not mean the subscription is dead
+
+**Context:** After the VAPID key changed, WNS answered 401 for a subscription made with the old key, and FCM answers 403 for the same case. Deleting the row on 401/403 was proposed so such rows stop failing (2026-10-09).
+
+**Problem:** Apple's push service answers 403 when it refuses our own token (`BadJwtToken`, for example a contact address it does not accept). That refusal hits every Safari subscription at once. A delete on 403 would remove every Safari row on each push, the page load would save them again, and no Safari user would ever get a push, with no error anywhere.
+
+**Rule:** Delete a subscription only on 404 or 410. On 401 or 403, log a warning with the push service's body and keep the row (`pushDeliveryOutcome` → `rejected`). An old-key row is replaced on the browser's next page load or ages out.
+
+**Applies to:** `packages/jobs/src/inngest/functions/notifications/push-outcome.ts`, `send-push.ts`; any Web Push sender.
+
## A generated avatar is a seed, so the library version decides the face
**Context:** `user.avatarUrl` stores a generated avatar as `dicebear:<style>:<seed>[:<rrggbb>]` (`packages/utils/src/avatar.ts`). The browser draws it with DiceBear every time it renders (`packages/react/src/utils/generatedAvatar.ts`). Nothing about the picture is stored, only the seed.
@@ -3363,3 +3405,13 @@ of `salesInvoice`; backfilled by `20261006220901_sales-invoice-opportunity-backf
**Rule:** Never put an import attribute on a JSON import in code that also runs in the browser. Make the server bundle the package instead: add it to `ssrNoExternal` in each app's `vite.config.ts` (the ERP and MES lists apply to both `ssr.noExternal` and `environments.ssr.resolve.noExternal`). To check the browser side, fetch the module from the dev server (`curl $ERP_URL/@fs<absolute path>`) and confirm the `import()` call has no second argument.
**Applies to:** `packages/react/src/utils/generatedAvatar.ts`; any isomorphic code that imports JSON from a dependency.
+
+## One Inngest send carries at most 512 KB, and a rendered email is about 17 KB
+
+**Context:** `notify` rendered every recipient's notification email in one step, then sent all the `carbon/send-email` events with one `step.sendEvent` (2026-10-09).
+
+**Problem:** One rendered `NotificationEmail` is about 16.9 KB, because the event carries the full HTML. Inngest accepts at most 512 KB in one send and 4 MB in one step's output. So email to about 30 recipients or more could fail the send, and about 240 filled the step. A group notification reaches those sizes; a test with one recipient never does.
+
+**Rule:** Size a fan-out by its bytes, not its count. When each event carries a rendered body, render and send it in chunks (`EMAIL_CHUNK` in `notify.ts`), each chunk in its own step with an indexed id (`render-emails-${index}`). A new step id replays a run in flight at deploy, so a send step that changes id sends again for those runs.
+
+**Applies to:** `packages/jobs/src/inngest/functions/notifications/notify.ts`; any job that fans out events with large payloads.
diff --git a/.ai/plans/2026-10-08-web-push-notifications.md b/.ai/plans/2026-10-08-web-push-notifications.md
new file mode 100644
index 0000000000..e503222a8d
--- /dev/null
+++ b/.ai/plans/2026-10-08-web-push-notifications.md
@@ -0,0 +1,888 @@
+# Push notifications in the browser (Web Push) — implementation plan
+
+**Spec:** .ai/specs/2026-10-08-web-push-notifications.md
+**Research:** none. The `/feature` run skipped research (`.ai/runs/2026-10-08-web-push-notifications.md`).
+**Branch:** naveenkash/carbon-browser-notifications
+
+## Progress
+- [x] Task 1: Add the `pushSubscription` table and widen the preference channel
+- [x] Task 2: Add the push channel to `@carbon/notifications`
+- [x] Task 3: Add the VAPID env vars to `@carbon/env`
+- [x] Task 4: Add the `carbon/send-push` event to `@carbon/lib`
+- [x] Task 5: Add the `send-push` job
+- [x] Task 6: Fan out push from `notify`
+- [x] Task 7: Add the ERP models and service functions
+- [x] Task 8: Add the `/api/push-subscription` route
+- [x] Task 9: Add the service worker `push-worker.js`
+- [x] Task 10: Add the `usePushSubscription` hook
+- [x] Task 11: Add the device card and the Browser column to Account → Notifications
+- [x] Task 12: Unsubscribe on Sign Out
+- [x] Task 13: Extract and translate the new strings
+- [x] Task 14: Update the docs, the rules and the AGENTS.md files
+- [x] Task 15: Run the final gates
+
+## Dependencies
+
+- Task 1 comes first. Every later task that reads `pushSubscription` needs its generated types.
+- Tasks 2, 3 and 4 are independent of each other. Each one needs only Task 1.
+- Task 5 needs Tasks 3 and 4.
+- Task 6 needs Tasks 2, 3, 4 and 5.
+- Task 7 needs Tasks 1 and 2.
+- Task 8 needs Tasks 3, 4 and 7.
+- Task 9 is independent of all other tasks.
+- Task 10 needs Task 8. It also needs the worker file path from Task 9.
+- Task 11 needs Tasks 7, 8 and 10.
+- Task 12 needs Task 10.
+- Task 13 needs Tasks 11 and 12.
+- Task 14 needs Tasks 1 to 12.
+- Task 15 needs every other task.
+
+## Rules for every task
+
+- Start every new source file with its SPDX header. Run `pnpm --filter @carbon/checks license-headers` after you create it. All new files in this plan are AGPL: none is under `packages/ee/` and none has `.ee.` in its name.
+- Do not use JavaScript `Date` for arithmetic or formatting. For a timestamp to store, use `datetime.timestamp()` from `@carbon/utils`, as `notify.ts` does.
+- Do not use `Math.round`, `Math.ceil`, `Math.floor` or `.toFixed`.
+- Do not commit. The user asks for each commit (`.ai/runs/2026-10-08-web-push-notifications.md`, item 9).
+
+---
+
+## Task 1: Add the `pushSubscription` table and widen the preference channel
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_push-subscription.sql` (from `pnpm db:migrate:new`)
+- Modify: `packages/database/src/authz/manifest.ts` — add the `pushSubscription` rule
+- Create: `packages/database/supabase/migrations/<timestamp>_authz-push-subscription.sql` (from `authz migration`)
+- Copy from (precedent): `packages/database/supabase/migrations/20260714095112_notification-preferences.sql` and the `notificationPreference` rule in `manifest.ts` (line 1026)
+
+**Steps:**
+1. Run `pnpm db:migrate:new push-subscription`.
+2. Write this SQL into the new file. It has no `CREATE POLICY`, because the manifest owns the policies.
+
+```sql
+-- One browser push subscription per (user, company, endpoint). A user-owned
+-- device row, shaped like "notificationPreference": xid() id, no audit columns.
+CREATE TABLE IF NOT EXISTS "pushSubscription" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "userId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "endpoint" TEXT NOT NULL,
+ "p256dh" TEXT NOT NULL,
+ "auth" TEXT NOT NULL,
+ "userAgent" TEXT,
+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT now(),
+ "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT now(),
+
+ CONSTRAINT "pushSubscription_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "pushSubscription_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "pushSubscription_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "pushSubscription_endpoint_companyId_key" UNIQUE ("endpoint", "companyId")
+);
+
+ALTER TABLE "pushSubscription" ENABLE ROW LEVEL SECURITY;
+
+CREATE INDEX IF NOT EXISTS "pushSubscription_userId_companyId_idx"
+ ON "pushSubscription" ("userId", "companyId");
+
+CREATE INDEX IF NOT EXISTS "pushSubscription_companyId_idx"
+ ON "pushSubscription" ("companyId");
+
+ALTER TABLE "notificationPreference"
+ DROP CONSTRAINT IF EXISTS "notificationPreference_channel_check";
+
+ALTER TABLE "notificationPreference"
+ ADD CONSTRAINT "notificationPreference_channel_check"
+ CHECK ("channel" IN ('email', 'slack', 'push'));
+```
+
+3. In `manifest.ts`, add this rule in alphabetical order (after the `purchase*` keys, before `quote*`):
+
+```ts
+ pushSubscription: policies({
+ select: and(owner("userId"), member("companyId")),
+ insert: and(owner("userId"), member("companyId")),
+ update: {
+ using: owner("userId"),
+ check: and(owner("userId"), member("companyId"))
+ },
+ delete: and(owner("userId"), member("companyId"))
+ }),
+```
+
+4. Run `pnpm db:migrate`. It applies the migration and runs `authz sync`.
+5. Run `pnpm --filter @carbon/database authz migration push-subscription`.
+6. Run `pnpm run generate:types`.
+7. Run `pnpm --filter @carbon/database test -- migration.test`.
+8. Run `pnpm db:check:backups`.
+
+If `pnpm db:migrate` reports that the local database is unreachable, STOP and report. Do not rebuild the database.
+
+**Verify:**
+```bash
+grep -c '"pushSubscription"' packages/database/src/types.ts
+# Expected: a number greater than 0
+pnpm --filter @carbon/database test -- migration.test
+# Expected: all tests pass
+pnpm db:check:backups
+# Expected: the check passes, or reports only that the new table is new
+```
+
+**Out of scope:** the company backup engine, the demo datasets, `serviceWorker.js`.
+
+---
+
+## Task 2: Add the push channel to `@carbon/notifications`
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/notifications/src/index.ts`
+- Create: `packages/notifications/src/push.test.ts`
+
+**Steps:**
+1. Add `Push = "push"` to `enum NotificationDestination`. Update the enum comment: push, email and slack are opt-in extras.
+2. Change `NotificationPreferenceChannel` to `"email" | "slack" | "push"`.
+3. In `getNotificationTopicChannels`, make the `default` arm return `["email", "slack", "push"]`. Leave `Changelog` as `["email"]`.
+4. Add this exported function below `getNotificationTopicChannels`:
+
+```ts
+// Push follows the external channels: an event that emails or posts to Slack
+// also pushes. In-app-only events (IntegrationSync re-fires every sweep) stay
+// quiet on the device.
+export function wantsPushDelivery(
+ destinations: readonly NotificationDestination[]
+): boolean {
+ return destinations.some(
+ (destination) =>
+ destination === NotificationDestination.Push ||
+ destination === NotificationDestination.Email ||
+ destination === NotificationDestination.Slack
+ );
+}
+```
+
+5. Move the `NotificationDestination` enum above `wantsPushDelivery` if the compiler reports a use before definition.
+6. In `push.test.ts`, test 4 cases of `wantsPushDelivery`: `[InApp]` → false; `[InApp, Email]` → true; `[Slack]` → true; `[Push]` → true.
+7. Add 1 test: `getNotificationTopicChannels(NotificationTopic.Job)` contains `"push"`, and `getNotificationTopicChannels(NotificationTopic.Changelog)` does not.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/notifications test
+# Expected: all tests pass, including push.test.ts
+pnpm exec turbo run typecheck --filter=@carbon/notifications
+# Expected: no errors
+```
+
+**Out of scope:** `defaultDestinations` in `notify.ts` (Task 6 does not change it).
+
+---
+
+## Task 3: Add the VAPID env vars to `@carbon/env`
+
+> **Superseded 2026-10-09:** the env vars were removed. `getVapidDetails()` in `packages/env/src/push.server.ts` (`@carbon/env/push.server`) derives the pair from `SESSION_SECRET`. See the spec's changelog.
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/env/src/schema.ts` — new group `push`, 3 vars
+- Modify: `packages/env/src/index.ts` — export the 3 values and `isPushConfigured()`
+- Modify: `.env.example` — a commented push block
+- Copy from (precedent): the `slack` group in `schema.ts` (lines 308–338)
+
+**Steps:**
+1. Add `"push"` to the `Group` union in `schema.ts`.
+2. Add `push: "Push notifications"` to `FEATURES`.
+3. Add this block after the `slack` block in `schema`:
+
+```ts
+ // ── push ──────────────────────────────────────────────────────────────────
+ VAPID_PUBLIC_KEY: {
+ group: "push",
+ description:
+ "Web Push public key (pnpm dlx web-push generate-vapid-keys). Generate once: a new pair makes every user turn push on again",
+ needed: true
+ },
+ VAPID_PRIVATE_KEY: {
+ group: "push",
+ description: "Web Push private key, paired with VAPID_PUBLIC_KEY",
+ secret: true,
+ needed: true
+ },
+ VAPID_SUBJECT: {
+ group: "push",
+ description: "Contact for push services: a mailto: or https: URL",
+ needed: true
+ },
+```
+
+4. In `index.ts`, near `ERP_URL`, add:
+
+```ts
+// Web Push. All three or none: the notify job and the account page treat a
+// half-set pair as "push off" (validateEnv warns about it).
+export const VAPID_PUBLIC_KEY = getEnv("VAPID_PUBLIC_KEY");
+export const VAPID_PRIVATE_KEY = getEnv("VAPID_PRIVATE_KEY");
+export const VAPID_SUBJECT = getEnv("VAPID_SUBJECT");
+
+export function isPushConfigured(): boolean {
+ return Boolean(VAPID_PUBLIC_KEY && VAPID_PRIVATE_KEY && VAPID_SUBJECT);
+}
+```
+
+5. Do not add the vars to `getBrowserEnv()`. The settings loader sends the public key (spec, Design Decisions).
+6. In `.env.example`, after the SMTP block, add:
+
+```
+# Web Push (browser notifications; leave unset to disable push)
+# Generate once with: pnpm dlx web-push generate-vapid-keys
+# VAPID_PUBLIC_KEY=""
+# VAPID_PRIVATE_KEY=""
+# VAPID_SUBJECT="mailto:[email protected]"
+```
+
+**Verify:**
+```bash
+pnpm --filter @carbon/env test
+# Expected: all tests pass (deployments.test.ts included)
+pnpm exec turbo run typecheck --filter=@carbon/env
+# Expected: no errors
+```
+
+**Out of scope:** `sst.config.ts`, `ci/src/deploy.ts`, `vercel-production.json`. Production keys are an ops step for the user (report it in the hand-off).
+
+---
+
+## Task 4: Add the `carbon/send-push` event to `@carbon/lib`
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/lib/src/events.ts` — new event type
+- Modify: `packages/lib/src/trigger.ts` — new map entry
+- Copy from (precedent): `"carbon/send-slack"` in `events.ts` (line 46)
+
+**Steps:**
+1. In `events.ts`, after `"carbon/send-slack"`, add:
+
+```ts
+ // Web Push events: one per pushSubscription row
+ "carbon/send-push": {
+ data: {
+ subscriptionId: string;
+ companyId: string;
+ title: string;
+ body: string;
+ url: string;
+ tag: string;
+ };
+ };
+```
+
+2. In `trigger.ts`, add `"send-push": "carbon/send-push",` after `"send-slack"`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/lib
+# Expected: no errors
+```
+
+**Out of scope:** none.
+
+---
+
+## Task 5: Add the `send-push` job
+
+**Depends on:** Tasks 3, 4
+**Files:**
+- Modify: `packages/jobs/package.json` — add `web-push`, dev `@types/web-push`
+- Create: `packages/jobs/src/inngest/functions/notifications/push-outcome.ts`
+- Create: `packages/jobs/src/inngest/functions/notifications/push-outcome.test.ts`
+- Create: `packages/jobs/src/inngest/functions/notifications/send-push.ts`
+- Modify: `packages/jobs/src/inngest/functions/notifications/index.ts`
+- Modify: `packages/jobs/src/inngest/index.ts` — register the function
+- Copy from (precedent): `send-slack.ts` and `delivery-failure.ts` / `delivery-failure.test.ts` in the same folder
+
+**Steps:**
+1. Run `pnpm --filter @carbon/jobs add web-push`.
+2. Run `pnpm --filter @carbon/jobs add -D @types/web-push`.
+3. Create `push-outcome.ts`:
+
+```ts
+export type PushOutcome = "delivered" | "gone" | "retry" | "fail";
+
+// What a push service's HTTP status means for the subscription row.
+// 404 / 410: the subscription is gone for good, so the caller deletes it.
+// 429 / 5xx: transient, so the caller throws and Inngest retries.
+// Any other non-2xx: a bad request that a retry would repeat.
+export function pushDeliveryOutcome(statusCode: number): PushOutcome {
+ if (statusCode >= 200 && statusCode < 300) return "delivered";
+ if (statusCode === 404 || statusCode === 410) return "gone";
+ if (statusCode === 429 || statusCode >= 500) return "retry";
+ return "fail";
+}
+```
+
+4. In `push-outcome.test.ts`, test 6 statuses: 201 → delivered, 404 → gone, 410 → gone, 413 → fail, 429 → retry, 503 → retry.
+5. Create `send-push.ts`. Copy the shape of `send-slack.ts`. The function:
+ 1. `inngest.createFunction({ id: "send-push", retries: 3 }, { event: "carbon/send-push" }, …)`.
+ 2. If `isPushConfigured()` is false, return `{ skipped: "push not configured" }`.
+ 3. In `step.run("load-subscription")`, read `id, endpoint, p256dh, auth` from `pushSubscription` by `id` and `companyId` with `getCarbonServiceRole()`. If the read returns an error, throw it.
+ 4. If no row exists, return `{ skipped: "subscription not found" }`.
+ 5. In `step.run("send-push")`, call `webpush.sendNotification(...)`:
+
+```ts
+await webpush.sendNotification(
+ { endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
+ JSON.stringify({ title, body, url, tag }),
+ {
+ TTL: 86400,
+ urgency: "normal",
+ vapidDetails: {
+ subject: VAPID_SUBJECT!,
+ publicKey: VAPID_PUBLIC_KEY!,
+ privateKey: VAPID_PRIVATE_KEY!
+ }
+ }
+);
+```
+
+ 6. Catch the error. Read `statusCode` from it: `web-push` throws a `WebPushError` with `statusCode`. If the error has no `statusCode`, throw it again (a network error, so Inngest retries).
+ 7. Map the status with `pushDeliveryOutcome`.
+ 8. If the outcome is `gone`, return `{ status: statusCode, gone: true }` from the step.
+ 9. If the outcome is `retry`, throw an `Error` that names the status.
+ 10. If the outcome is `fail`, throw `new NonRetriableError(...)` with the status and the response body.
+ 11. On success, return `{ status: result.statusCode }`.
+ 12. If the send step returned `gone: true`, run `step.run("delete-subscription")`. It deletes the row by `id` and `companyId` with the service role. If the delete returns an error, throw it.
+6. Import the VAPID values and `isPushConfigured` from `@carbon/env`.
+7. Export `sendPushFunction` from `notifications/index.ts`.
+8. Import `sendPushFunction` in `packages/jobs/src/inngest/index.ts`. Add it to the functions list next to `sendSlackFunction` (lines 62–64 and 117–119).
+
+If `web-push` throws an error type that has no `statusCode` property, STOP and report. Do not guess the field name.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs test -- push-outcome
+# Expected: 6 tests pass
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: no errors
+```
+
+**Out of scope:** `send-email.ts`, `send-slack.ts`, delivery tracking (`increment_notification_delivery`).
+
+---
+
+## Task 6: Fan out push from `notify`
+
+**Depends on:** Tasks 2, 3, 4, 5
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/notifications/notify.ts`
+
+**Steps:**
+1. Import `isPushConfigured` from `@carbon/env` and `wantsPushDelivery` from `@carbon/notifications`.
+2. After `const wantsSlack = …`, add:
+
+```ts
+ // Push is free on every plan and follows the external channels; a
+ // deployment without VAPID keys has no push channel at all.
+ const wantsPush = isPushConfigured() && wantsPushDelivery(destinations);
+```
+
+3. Change the condition of the step `filter-recipients-by-preference` to `wantsEmail || wantsSlack || wantsPush`.
+4. In that step, change `mutedFor`'s parameter type to `NotificationPreferenceChannel` (import it from `@carbon/notifications`).
+5. In that step, compute `const pushMuted = mutedFor("push");`.
+6. In that step, also return `pushRecipientIds: userIds.filter((id) => !pushMuted.has(id))`.
+7. In the fallback object, add `pushRecipientIds: userIds`. Destructure `pushRecipientIds` with the other 2.
+8. 🛑 Do not change the step id `filter-recipients-by-preference`. In-flight runs resume by step id; the new key is only an extra field.
+9. After the Slack fan-out block, add the push fan-out:
+
+```ts
+ // ---- Push fan-out ----
+ // One carbon/send-push per device row, so each device retries on its own.
+ if (wantsPush && pushRecipientIds.length > 0) {
+ const pushEvents = await step.run(
+ "resolve-push-subscriptions",
+ async () => {
+ const { data: subscriptions, error } = await client
+ .from("pushSubscription")
+ .select("id")
+ .eq("companyId", payload.companyId)
+ .in("userId", pushRecipientIds);
+ if (error) {
+ console.error("Failed to load push subscriptions", error);
+ throw error;
+ }
+ const url = buildNotificationLink(
+ payload.event,
+ primaryDocumentId,
+ payload.companyId,
+ payload.documentType
+ );
+ const title = getNotificationEmailHeading(payload.event);
+ return (subscriptions ?? []).map((subscription) => ({
+ data: {
+ body: description,
+ companyId: payload.companyId,
+ subscriptionId: subscription.id,
+ tag: `${payload.event}:${primaryDocumentId}`,
+ title,
+ url
+ },
+ name: "carbon/send-push" as const
+ }));
+ }
+ );
+ if (pushEvents.length > 0) {
+ await step.sendEvent("fan-out-push", pushEvents);
+ }
+ }
+```
+
+10. Update the comment above `defaultDestinations`: push also goes to every event that has Email or Slack.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: no errors
+pnpm --filter @carbon/jobs test
+# Expected: all tests pass
+grep -n '"resolve-push-subscriptions"\|"fan-out-push"\|"filter-recipients-by-preference"' packages/jobs/src/inngest/functions/notifications/notify.ts
+# Expected: 3 lines
+```
+
+**Out of scope:** `notification-digest.ts` (the digest cron sends no push), `defaultDestinations` entries.
+
+---
+
+## Task 7: Add the ERP models and service functions
+
+**Depends on:** Tasks 1, 2
+**Files:**
+- Modify: `apps/erp/app/modules/account/account.models.ts`
+- Modify: `apps/erp/app/modules/account/account.service.ts`
+- Copy from (precedent): `notificationPreferenceValidator` and `upsertNotificationPreference` in the same files
+
+**Steps:**
+1. In `account.models.ts`, change `notificationPreferenceValidator.channel` to `z.enum(["email", "slack", "push"])`.
+2. In `account.models.ts`, add:
+
+```ts
+// The browser's PushSubscription.toJSON(), plus the endpoint it replaces when
+// the service worker re-subscribes after a pushsubscriptionchange.
+export const pushSubscriptionValidator = z.object({
+ endpoint: z.string().url(),
+ keys: z.object({
+ p256dh: z.string().min(1),
+ auth: z.string().min(1)
+ }),
+ oldEndpoint: z.string().url().optional()
+});
+
+export const pushSubscriptionEndpointValidator = z.object({
+ endpoint: z.string().url()
+});
+```
+
+3. In `account.service.ts`, change the `channel` type of `upsertNotificationPreference` to `NotificationPreferenceChannel` (from `@carbon/notifications`).
+4. In `account.service.ts`, add 3 functions with a one-line doc comment and NO `@mcp` tag:
+
+```ts
+/** Reads this device's push subscription for the user and company. */
+export async function getPushSubscription(
+ client: SupabaseClient<Database>,
+ args: { userId: string; companyId: string; endpoint: string }
+) {
+ return client
+ .from("pushSubscription")
+ .select("id")
+ .eq("userId", args.userId)
+ .eq("companyId", args.companyId)
+ .eq("endpoint", args.endpoint)
+ .maybeSingle();
+}
+
+/** Saves this device's push subscription for the user and company. */
+export async function upsertPushSubscription(
+ client: SupabaseClient<Database>,
+ subscription: {
+ userId: string;
+ companyId: string;
+ endpoint: string;
+ p256dh: string;
+ auth: string;
+ userAgent: string | null;
+ }
+) {
+ return client
+ .from("pushSubscription")
+ .upsert(
+ { ...subscription, updatedAt: datetime.timestamp() },
+ { onConflict: "endpoint,companyId" }
+ )
+ .select("id")
+ .single();
+}
+
+/** Removes this device's push subscription for the user and company. */
+export async function deletePushSubscription(
+ client: SupabaseClient<Database>,
+ args: { userId: string; companyId: string; endpoint: string }
+) {
+ return client
+ .from("pushSubscription")
+ .delete()
+ .eq("userId", args.userId)
+ .eq("companyId", args.companyId)
+ .eq("endpoint", args.endpoint);
+}
+```
+
+5. Import `datetime` from `@carbon/utils` if the file does not already import it.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+pnpm run generate:mcp && git status --short apps/erp | grep -i mcp
+# Expected: no MCP file changes caused by the 3 new functions
+```
+
+If `generate:mcp` changes an MCP file because of the new functions, STOP and report.
+
+**Out of scope:** `getNotificationPreferences`, other account services.
+
+---
+
+## Task 8: Add the `/api/push-subscription` route
+
+**Depends on:** Tasks 3, 4, 7
+**Files:**
+- Create: `apps/erp/app/routes/api+/push-subscription.ts`
+- Modify: `apps/erp/app/utils/path.ts` — add `pushSubscription: \`${api}/push-subscription\`` next to `messagingNotify` (line 217)
+- Copy from (precedent): `apps/erp/app/routes/api+/messaging.notify.ts`
+
+**Steps:**
+1. Export only an `action`. The route has no loader and no default export.
+2. Call `requirePermissions(request, {})`. Read `client`, `userId` and `companyId`.
+3. If `isPushConfigured()` is false, return `data({ error: "Push is not configured" }, { status: 404 })`.
+4. If `request.method === "PUT"`:
+ 1. Parse `await request.json()` with `pushSubscriptionValidator.safeParse`. If it fails, return status 400.
+ 2. If `oldEndpoint` is set, call `deletePushSubscription(client, { userId, companyId, endpoint: oldEndpoint })`.
+ 3. With `getCarbonServiceRole()`, delete the `pushSubscription` rows where `endpoint` equals the new endpoint and `userId` is not this user. This step stops a shared browser from getting the previous user's notifications.
+ 4. Call `upsertPushSubscription(client, { userId, companyId, endpoint, p256dh: keys.p256dh, auth: keys.auth, userAgent: request.headers.get("user-agent") })`.
+ 5. If any call returns an error, return status 500 with `{ error: message }`.
+ 6. Return `{ id }`.
+5. If `request.method === "DELETE"`:
+ 1. Parse the body with `pushSubscriptionEndpointValidator`. If it fails, return status 400.
+ 2. Call `deletePushSubscription`. If it returns an error, return status 500.
+ 3. Return `{ ok: true }`.
+6. If `request.method === "POST"`:
+ 1. Parse the body with `pushSubscriptionEndpointValidator.extend({ intent: z.literal("test") })`. If it fails, return status 400.
+ 2. Call `getPushSubscription`. If no row exists, return status 404.
+ 3. Set `title` to "Carbon" and `body` to "Push notifications work on this device."
+ 4. Set `url` to `` `${getAppUrl()}${path.to.notificationSettings}` ``. Import `getAppUrl` from `@carbon/env`.
+ 5. Call `trigger("send-push", { subscriptionId: row.id, companyId, title, body, url, tag: "carbon-test" })`.
+ 6. Return `{ ok: true }`.
+7. For any other method, return status 405.
+8. Import `trigger` from `@carbon/jobs`, as `messaging.notify.ts` does.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+```
+
+**Out of scope:** CSRF changes. The `securityMiddleware` already checks the origin of a same-origin `fetch`.
+
+---
+
+## Task 9: Add the service worker `push-worker.js`
+
+**Depends on:** none
+**Files:**
+- Create: `apps/erp/public/push-worker.js`
+- Copy from (precedent): the SPDX header of `apps/erp/public/serviceWorker.js` (deleted 2026-10-09; use `pnpm --filter @carbon/checks license-headers`)
+
+**Steps:**
+1. Write the file with 3 listeners and no `fetch` listener:
+
+```js
+// Web Push for Carbon: shows the notification, opens its link on click, and
+// re-registers a subscription the browser rotated. No fetch handler — this
+// worker caches nothing.
+
+self.addEventListener("push", (event) => {
+ let payload = {};
+ try {
+ payload = event.data ? event.data.json() : {};
+ } catch {
+ payload = { body: event.data ? event.data.text() : "" };
+ }
+ const title = payload.title || "Carbon";
+ event.waitUntil(
+ self.registration.showNotification(title, {
+ body: payload.body || "",
+ tag: payload.tag,
+ icon: "/carbon-mark-dark.png",
+ data: { url: payload.url || "/" }
+ })
+ );
+});
+
+self.addEventListener("notificationclick", (event) => {
+ event.notification.close();
+ const url = (event.notification.data && event.notification.data.url) || "/";
+ event.waitUntil(
+ (async () => {
+ const windows = await self.clients.matchAll({
+ type: "window",
+ includeUncontrolled: true
+ });
+ const target = new URL(url, self.location.origin);
+ for (const client of windows) {
+ if (new URL(client.url).origin === target.origin && "focus" in client) {
+ await client.focus();
+ if ("navigate" in client) await client.navigate(target.href);
+ return;
+ }
+ }
+ await self.clients.openWindow(target.href);
+ })()
+ );
+});
+
+self.addEventListener("pushsubscriptionchange", (event) => {
+ event.waitUntil(
+ (async () => {
+ const old = event.oldSubscription;
+ const key = old && old.options && old.options.applicationServerKey;
+ if (!key) return;
+ const next =
+ event.newSubscription ||
+ (await self.registration.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: key
+ }));
+ await fetch("/api/push-subscription", {
+ method: "PUT",
+ credentials: "same-origin",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ...next.toJSON(), oldEndpoint: old.endpoint })
+ });
+ })()
+ );
+});
+```
+
+2. Run `pnpm --filter @carbon/checks license-headers`.
+
+**Verify:**
+```bash
+node --check apps/erp/public/push-worker.js && echo OK
+# Expected: OK
+pnpm exec biome check apps/erp/public/push-worker.js
+# Expected: no errors
+```
+
+**Out of scope:** `apps/erp/public/serviceWorker.js` (left unregistered here; deleted 2026-10-09), MES.
+
+---
+
+## Task 10: Add the `usePushSubscription` hook
+
+**Depends on:** Tasks 8, 9
+**Files:**
+- Create: `apps/erp/app/utils/push.ts` — `urlBase64ToUint8Array`
+- Create: `apps/erp/app/utils/push.test.ts`
+- Create: `apps/erp/app/hooks/usePushSubscription.ts`
+- Copy from (precedent): `apps/erp/app/hooks/useNotifications.tsx` (hook shape, `getLogger`)
+
+**Steps:**
+1. In `push.ts`, export `urlBase64ToUint8Array(base64Url: string): Uint8Array`:
+ 1. Pad the string with `=` to a length that is a multiple of 4.
+ 2. Replace `-` with `+` and `_` with `/`.
+ 3. Decode with `atob`, then copy each char code into a `Uint8Array`.
+2. In `push.test.ts`, test 2 cases: `"AQID"` → `[1, 2, 3]`, and `"-_8"` → `[251, 255]`.
+3. In `usePushSubscription.ts`, export `type PushState = "loading" | "unsupported" | "denied" | "off" | "on"`.
+4. Export `usePushSubscription({ publicKey }: { publicKey: string | null })`. It returns `{ state, busy, turnOn, turnOff, sendTest }`.
+5. On mount (`useEffect`), compute the state:
+ 1. If `publicKey` is null, set `unsupported`.
+ 2. If `"serviceWorker" in navigator`, `"PushManager" in window` or `"Notification" in window` is false, set `unsupported`.
+ 3. If `Notification.permission === "denied"`, set `denied`.
+ 4. Call `navigator.serviceWorker.getRegistration("/")`. Read `registration?.pushManager.getSubscription()`.
+ 5. If no subscription exists, set `off`.
+ 6. If a subscription exists, `PUT` it to `path.to.api.pushSubscription`. This step re-syncs the row for the current company. If the response is OK, set `on`. Else set `off`.
+6. `turnOn()`:
+ 1. Call `Notification.requestPermission()`. If the result is `denied`, set `denied` and return. If it is `default`, return.
+ 2. Call `navigator.serviceWorker.register("/push-worker.js", { scope: "/" })`.
+ 3. Await `navigator.serviceWorker.ready`.
+ 4. Call `pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(publicKey) })`.
+ 5. `PUT` `subscription.toJSON()` as JSON.
+ 6. If the response is OK, set `on`. Else call `subscription.unsubscribe()`, set `off`, and show `toast.error`.
+7. `turnOff()`:
+ 1. Read the current subscription. If none exists, set `off` and return.
+ 2. Send `DELETE` with `{ endpoint }`.
+ 3. Call `subscription.unsubscribe()`.
+ 4. Set `off`.
+8. `sendTest()`: send `POST` with `{ endpoint, intent: "test" }`. If the response is OK, show `toast.success`. Else show `toast.error`.
+9. Set `busy` to true while `turnOn`, `turnOff` or `sendTest` runs.
+10. Wrap each action in `try`/`catch`. Log with `logger.error` and show `toast.error` on failure.
+11. Use `toast` from `@carbon/react`. Use `useLingui` for the toast text.
+12. Also export `unsubscribeThisDevice(): Promise<void>` (not a hook). It reads the current subscription, sends `DELETE`, and calls `unsubscribe()`. It never throws. Task 12 uses it.
+
+**Verify:**
+```bash
+pnpm --filter erp test -- push.test
+# Expected: 2 tests pass
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+```
+
+**Out of scope:** `useNotifications.tsx`, the bell.
+
+---
+
+## Task 11: Add the device card and the Browser column to Account → Notifications
+
+**Depends on:** Tasks 7, 8, 10
+**Files:**
+- Modify: `apps/erp/app/routes/x+/account+/notifications.tsx`
+- Copy from (precedent): the same file's `Card` and `Switch` cells; `Button` from `@carbon/react`
+
+**Steps:**
+1. In the loader, add `push: isPushConfigured() ? { publicKey: VAPID_PUBLIC_KEY as string } : null` to the returned object.
+2. In the component, read `push` from `useLoaderData`.
+3. Call `usePushSubscription({ publicKey: push?.publicKey ?? null })`.
+4. If `push` is not null, render a second `Card` above the topic card:
+ 1. `CardTitle`: "This device".
+ 2. `CardDescription` and actions by state:
+
+| `state` | Text | Buttons |
+|---|---|---|
+| `loading` | none | none |
+| `off` | "Get notifications on this device, even when Carbon is closed." | **Turn on** (`variant="primary"`) |
+| `on` | "Push notifications are on for this device." | **Send a test notification** (`variant="secondary"`), **Turn off** (`variant="secondary"`) |
+| `denied` | "Notifications are blocked for Carbon in this browser's site settings." | none |
+| `unsupported` | "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first." | none |
+
+ 3. Set `isDisabled={busy}` on each button.
+5. Change the `Channel` cells:
+ 1. If `push` is not null, add a header cell **Browser** after Slack.
+ 2. If `push` is not null, add `cell("push", t\`browser\`)` after the Slack cell.
+6. If `push` is not null, use the new card description: "In-app notifications are always delivered. Choose which topics also reach you by email, Slack or on your devices." When Slack is not active, drop "Slack" from the text. Use one `<Trans>` per variant, like the existing code.
+7. Keep the existing `isEnabled`, `isPending` and `toggle` code. It already works for any channel.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+pnpm exec biome check apps/erp/app/routes/x+/account+/notifications.tsx apps/erp/app/hooks/usePushSubscription.ts apps/erp/app/utils/push.ts
+# Expected: no errors
+```
+
+**Out of scope:** the email plan note, the Slack loader query.
+
+---
+
+## Task 12: Unsubscribe on Sign Out
+
+**Depends on:** Task 10
+**Files:**
+- Modify: `apps/erp/app/components/AvatarMenu.tsx` — the Sign Out `<Form>` (line 299)
+
+**Steps:**
+1. Import `useSubmit` from `react-router` and `unsubscribeThisDevice` from `~/hooks/usePushSubscription`.
+2. Add an `onSubmit` handler to the Sign Out `<Form>`:
+ 1. Call `event.preventDefault()`.
+ 2. Read the form element from `event.currentTarget`.
+ 3. `await Promise.race([unsubscribeThisDevice(), wait(1000)])`. `wait` is a local promise that resolves after 1 000 ms with `setTimeout`.
+ 4. Call `submit(form)`.
+3. Keep the `method="post"` and `action={path.to.logout}` attributes, so the form still works if the script fails.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+```
+
+**Out of scope:** the other `logoutAction` users (`MfaEnrollmentRequired`, `SessionLockOverlay`, `_public+/mfa.tsx`, `_public+/unlock.tsx`, `select-company+/_index.tsx`, `onboarding+/plan.tsx`). A user on those screens has not turned on push in this session. The spec lists the expired-session gap under Risks.
+
+---
+
+## Task 13: Extract and translate the new strings
+
+**Depends on:** Tasks 11, 12
+**Files:**
+- Modify: `packages/locale/locales/*/*.po`
+
+**Steps:**
+1. Run `pnpm run lingui:extract` from the repo root.
+2. Run the `/translate` skill to fill the empty `msgstr` entries.
+
+**Verify:**
+```bash
+git diff --stat packages/locale/locales | tail -1
+# Expected: the .po files changed
+```
+
+**Out of scope:** strings outside this feature.
+
+---
+
+## Task 14: Update the docs, the rules and the AGENTS.md files
+
+**Depends on:** Tasks 1–12
+**Files:**
+- Modify: `docs/content/docs/reference/account.mdx` — the "Notification preferences" section and the AgentContext notes
+- Modify: `docs/content/docs/reference/notifications.mdx` — the channels list
+- Modify: `docs/content/docs/platform/self-hosting/environment-variables.mdx` — the 3 VAPID vars
+- Modify: `packages/jobs/AGENTS.md` — a `send-push` row next to the other notification functions
+- Modify: `packages/notifications/AGENTS.md` — the `Push` destination and `wantsPushDelivery`
+- Modify: `.claude/rules/environment-configuration.md` — the `push` group
+
+**Steps:**
+1. Use the `carbon-docs` skill for the 3 docs pages. Ground each claim in the code from Tasks 1–12.
+2. In `account.mdx`, describe the "This device" card and the Browser column. Note that a user turns on push once per company and per browser.
+3. In `notifications.mdx`, add push as a channel. Say that push follows email and Slack, and that push needs the VAPID env vars.
+4. In `environment-variables.mdx`, add the 3 `<EnvVar>` entries next to the SMTP or Slack entries. Copy the descriptions from `schema.ts`.
+5. In `packages/jobs/AGENTS.md`, add `send-push` with the trigger `carbon/send-push` and the 404/410 delete rule.
+
+**Verify:**
+```bash
+pnpm --filter docs typecheck
+# Expected: no errors
+```
+
+**Out of scope:** a changelog entry (the user asks for that separately).
+
+---
+
+## Task 15: Run the final gates
+
+**Depends on:** every other task
+**Files:** none
+
+**Steps:**
+1. Run each command below. Fix each failure before you continue.
+2. Update the spec status to `in-progress` and add a changelog line for each divergence from the spec.
+3. Write the manual browser checklist into the run record (the run skipped `/test`):
+ 1. Restart the ERP and the Inngest dev server. (Originally: set the 3 VAPID vars. Since 2026-10-09 the pair is derived from `SESSION_SECRET`.)
+ 2. Open Account → Notifications, click **Turn on**, and allow the prompt.
+ 3. Click **Send a test notification**. Expect an OS notification. Click it and expect Account → Notifications.
+ 4. Close every Carbon tab. Assign a job to the user from a second account. Expect "Job assigned to you".
+ 5. Turn off the Jobs **Browser** switch. Assign another job. Expect no push and a new bell row.
+ 6. Click **Turn off**. Expect 0 `pushSubscription` rows for the user.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/notifications --filter=@carbon/env --filter=@carbon/lib --filter=@carbon/jobs --filter=erp
+# Expected: all tasks succeed
+pnpm --filter @carbon/notifications test && pnpm --filter @carbon/jobs test && pnpm --filter @carbon/env test
+# Expected: all tests pass
+pnpm --filter erp test -- push.test
+# Expected: 2 tests pass
+pnpm --filter @carbon/database test -- migration.test
+# Expected: all tests pass
+pnpm run lint
+# Expected: no errors
+pnpm --filter @carbon/checks license-headers && git status --short
+# Expected: no new header changes
+```
+
+**Out of scope:** commit and push. Ask the user first.
diff --git a/.ai/plans/2026-10-09-notify-large-recipient-lists.md b/.ai/plans/2026-10-09-notify-large-recipient-lists.md
new file mode 100644
index 0000000000..7ee8f92052
--- /dev/null
+++ b/.ai/plans/2026-10-09-notify-large-recipient-lists.md
@@ -0,0 +1,279 @@
+# Notifications for large recipient lists — implementation plan
+
+**Spec:** none. The input is the user's request on PR #1867: make `notify` work for a large group, not only the read limit.
+**Research:** none. The limits come from the code, `.claude/skills/inngest/SKILL.md` and a measurement on 2026-10-09.
+**Branch:** `naveenkash/carbon-browser-notifications` (PR #1867). The user chose this branch on 2026-10-09, so the work does not wait for the merge. The plan needs `fetchAllByIds` from that PR.
+
+## Why
+
+`notify` (`packages/jobs/src/inngest/functions/notifications/notify.ts`) handles each recipient list in one request, one insert or one send. That is correct for a few recipients. A group notification can have hundreds.
+
+PR #1867 fixed the reads: `fetchAllByIds` (`@carbon/database`) sends 100 ids per `.in()` request and pages each group. These limits remain:
+
+| Limit | Where in `notify.ts` | What fails |
+|---|---|---|
+| `.in()` writes each id into the URL; the gateway rejects a long request line (HTTP 431) | The 2 supersede updates in `write-in-app-notifications` | The digest step throws for a large group |
+| One round trip per recipient | The multi-item digest loop: 1 parent insert and 1 child insert per user | A large digest is slow, and the step can time out |
+| Inngest keeps a step output up to 4 MB | `resolve-email-recipients` returns the rendered HTML of every recipient | About 240 recipients fill 4 MB (16.9 KB per email) |
+| Inngest accepts a send batch up to 512 KB | `fan-out-emails`, `fan-out-slack`, `fan-out-push` send all events at once | Email fails at about 30 recipients (30 × 16.9 KB) |
+| Slack rate-limits `users.lookupByEmail` (Tier 3, 50+ calls a minute) | `resolve-slack-recipients` looks up every recipient at the same time | Not a lost DM: `@slack/web-api` waits for `Retry-After` and tries again, up to 10 times in about 30 minutes. A large first-time fan-out makes the step wait. |
+| One `user` read per Slack recipient | `getSlackUserIdByCarbonId` (`packages/ee/src/slack/lib/service.ts:252`) reads the email by user id | Only on a Redis cache miss (`slack-user:<id>`), so the first DM to a user only |
+
+The 16.9 KB is the rendered `NotificationEmail` for one job assignment with one detail row (`render(getNotificationEmailComponent(…))`, measured in a temporary vitest file).
+
+## Progress
+- [x] Task 1: Add the chunk sizes to `notify.ts`
+- [x] Task 2: Chunk the in-app supersede updates
+- [x] Task 3: Insert digest rows in batches, and chunk the flat insert
+- [x] Task 4: Render and send emails in chunks
+- [x] Task 5: Send the Slack and push events in chunks
+- [x] Task 6: Look up Slack users with the email in hand and bounded concurrency — skipped by the user, see the task
+- [x] Task 7: Use the shared `fetchAllByIds` in the production module
+- [x] Task 8: Update the docs and the lessons
+- [ ] Task 9: Run the gates and a large-group check
+
+## Dependencies
+
+- Task 1 comes first. Tasks 2, 3, 4 and 5 use its chunk sizes.
+- Tasks 2 and 3 change the same step. Do them in order.
+- Tasks 4, 5 and 6 are independent of each other after Task 1.
+- Task 7 is independent of every other task.
+- Task 8 needs Tasks 1–7. Task 9 comes last.
+
+## Caution: step ids and runs in flight
+
+Inngest replays a completed step from its stored output. It finds that output by the step id. See `.ai/lessons.md`, "A new key in an Inngest step's return breaks runs in flight at deploy".
+
+- If you keep a step id, keep the shape of its return value.
+- If you change the shape, give the step a new id.
+- A new id makes a run that is in flight at deploy run that step again. For a send step, that run sends its events again.
+- Deploy when no `carbon/notify` run is in flight, or accept one duplicate for each run in flight.
+
+---
+
+## Task 1: Add the chunk sizes to `notify.ts`
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/notifications/notify.ts` — 4 constants after the imports
+- Copy from (precedent): `for (const [index, batch] of chunkArray(…).entries())` in `packages/jobs/src/inngest/functions/integrations/accounting-master-sync.ts:222`
+
+The splitting helper already exists: `chunkArray` in `@carbon/utils`. A chunk's step id is a template string with its index, as in `scheduled/weekly.ts:294`. Do not add a wrapper for either (decision of the user, 2026-10-09).
+
+**Steps:**
+1. Add `chunkArray` to the existing `import { datetime } from "@carbon/utils"` line.
+2. Add `IN_FILTER_CHUNK = 100`. Comment: ids per `.in()` request, so the URL fits (HTTP 431).
+3. Add `INSERT_CHUNK = 500`. Comment: rows per `notification` insert.
+4. Add `EMAIL_CHUNK = 20`. Comment: 20 × 16.9 KB stays under the 512 KB send limit.
+5. Add `EVENT_CHUNK = 500`. Comment: Slack and push events are under 1 KB each.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: Tasks: 1 successful
+```
+
+**Out of scope:** a new helper module. Tasks 2–5 use `chunkArray(…).entries()` directly.
+
+Add each constant in the task that first uses it. Biome rejects an unused constant as an error, and the commit hook runs Biome. So Task 1 commits together with Task 2.
+
+## Task 2: Chunk the in-app supersede updates
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/notifications/notify.ts` — the `if (content.digest)` block in `write-in-app-notifications`
+
+**Steps:**
+1. Find the `Promise.all` with the 2 `update({ readAt, seenAt })` calls.
+2. Loop over `chunkArray(userIds, IN_FILTER_CHUNK)`, one chunk at a time.
+3. In each pass, run the 2 updates with `.in("userId", chunk)` instead of `userIds`.
+4. Keep `supersededAt` as one value for all chunks.
+5. If an update returns an error, log it and throw it, as the code does now.
+6. Keep the step id `write-in-app-notifications`. Its return value does not change.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: Tasks: 1 successful
+grep -n '.in("userId", userIds)' packages/jobs/src/inngest/functions/notifications/notify.ts
+# Expected: no line inside write-in-app-notifications
+```
+
+**Out of scope:** the order of supersede and insert. Supersede stays first, because it makes a retry self-healing.
+
+## Task 3: Insert digest rows in batches, and chunk the flat insert
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/notifications/notify.ts` — the `if (digestItems && digestItems.length > 1)` loop and the flat insert after it
+
+**Steps:**
+1. Replace the per-user loop with a loop over `chunkArray(userIds, IN_FILTER_CHUNK)`.
+2. For each chunk, build one parent row per user, with the same fields as now.
+3. Insert the parents in one call with `.select("id, userId")`.
+4. Build a map from `userId` to parent `id`.
+5. If a user in the chunk has no parent id, throw an error that names the user.
+6. Build the child rows for every user in the chunk, with `digestedInto` from the map.
+7. Insert the children in calls of at most `INSERT_CHUNK` rows each.
+8. Add each inserted count to `inserted`.
+9. For the flat path, insert `rows` in calls of at most `INSERT_CHUNK` rows each.
+10. Keep the return value `{ inserted, userIds }`, so the step id stays the same.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: Tasks: 1 successful
+pnpm --filter @carbon/jobs test
+# Expected: all tests pass
+```
+
+**Out of scope:** the `DigestNotification` UI and the shape of a digest row.
+
+If PostgREST does not return the inserted rows in input order, do not rely on order. The map in step 4 keys on `userId`, so order does not matter. If `.select("id, userId")` does not return `userId`, STOP and report.
+
+## Task 4: Render and send emails in chunks
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/notifications/notify.ts` — the `resolve-email-recipients` step and `fan-out-emails`
+
+**Steps:**
+1. Add a step `load-email-recipients` that returns `{ id, email, fullName }[]` from the `fetchAllByIds` read.
+2. Remove the `resolve-email-recipients` step. Its stored output has the old shape.
+3. Loop over `chunkArray(recipients, EMAIL_CHUNK).entries()`.
+4. For each chunk, run ``step.run(`render-emails-${index}`, …)`` with the render code that exists now.
+5. Return the events of that chunk only.
+6. Send them with ``step.sendEvent(`fan-out-emails-${index}`, events)``.
+7. Keep the subject, text, tracking and `to` fields exactly as now.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: Tasks: 1 successful
+grep -n '"resolve-email-recipients"\|"fan-out-emails"' packages/jobs/src/inngest/functions/notifications/notify.ts
+# Expected: no output (the old ids are gone)
+```
+
+**Out of scope:** `send-email.ts` and the `carbon/send-email` event shape. Other callers use them.
+
+Read the caution about step ids before you deploy. Inngest allows 1000 steps in one run, and each email chunk uses 2. If a group can have more than 9,000 email recipients, STOP and report.
+
+## Task 5: Send the Slack and push events in chunks
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/notifications/notify.ts` — `fan-out-slack` and `fan-out-push`
+
+**Steps:**
+1. Replace `step.sendEvent("fan-out-slack", slackEvents)` with a loop over `chunkArray(slackEvents, EVENT_CHUNK).entries()`.
+2. Send each chunk with ``step.sendEvent(`fan-out-slack-${index}`, chunk)``.
+3. Do the same for `fan-out-push` with `pushEvents`.
+4. Keep the `resolve-…` steps that build the events. Their return shapes do not change.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: Tasks: 1 successful
+grep -n 'sendEvent("fan-out-slack"\|sendEvent("fan-out-push"' packages/jobs/src/inngest/functions/notifications/notify.ts
+# Expected: no output
+```
+
+**Out of scope:** `send-slack.ts` and `send-push.ts`.
+
+## Task 6: Look up Slack users with the email in hand and bounded concurrency
+
+> **Skipped (2026-10-09, the user's decision).** The premise was wrong. A rate-limited lookup does not drop the user: `@slack/web-api` 7.15 defaults to `rejectRateLimitedCalls = false` and `tenRetriesInAboutThirtyMinutes`, so it waits and tries again. The `user` read happens only on a Redis cache miss. `getSlackUserIdByCarbonId` also has 6 callers inside `service.ts`, which the escape hatch in step 2 guards. The steps below stay as a record; do not do them.
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `packages/ee/src/slack/lib/service.ts` — `getSlackUserIdByCarbonId`
+- Modify: `packages/jobs/src/inngest/functions/notifications/notify.ts` — the Slack recipient lookup
+- Copy from (precedent): the bounded loop in `fetchAllRecords` (`packages/database/src/utils.ts`), which runs `PAGE_CONCURRENCY` requests at a time
+
+**Steps:**
+1. Run `git grep -n "getSlackUserIdByCarbonId"`. On 2026-10-09, `notify.ts` was the only caller.
+2. If there is another caller, STOP and report. Do not change a signature it uses.
+3. Rename it to `getSlackUserIdByEmail(accessToken, userId, email)`. Remove its `user` read.
+4. Keep the Redis cache key `slack-user:${userId}`, so cached ids stay valid.
+5. In `notify.ts`, read `id, email` for the Slack recipients with `fetchAllByIds`.
+6. Look up at most 5 users at a time. Wait for each group of 5 before the next.
+7. Count the users whose lookup returned nothing. Log the count once, with `companyId`.
+8. Keep the skip: a user with no Slack account gets no DM, as now.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/ee
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: Tasks: 1 successful (each)
+```
+
+**Out of scope:** retry on a Slack 429. Before you choose 5, read Slack's current rate tier for `users.lookupByEmail`. If the tier allows fewer than 20 calls a minute, STOP and report.
+
+`packages/ee` is commercial code. Keep its SPDX header. Do not move the function out of `packages/ee`.
+
+## Task 7: Use the shared `fetchAllByIds` in the production module
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/erp/app/modules/production/production.service.ts` — the private `fetchAllByIds` and `IN_FILTER_BATCH_SIZE`
+
+**Steps:**
+1. Delete the private `fetchAllByIds` function and the `IN_FILTER_BATCH_SIZE` constant.
+2. Add `fetchAllByIds` to the existing `import { … } from "@carbon/database"` line.
+3. Keep every call site as it is. The shared function has the same signature.
+4. Keep the `chunkArray` import. The planning-actions read still uses it.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: Tasks: 1 successful
+grep -n "async function fetchAllByIds" apps/erp/app/modules/production/production.service.ts
+# Expected: no output
+```
+
+**Out of scope:** the call sites, and any other module.
+
+## Task 8: Update the docs and the lessons
+
+**Depends on:** Tasks 1–7
+**Files:**
+- Modify: `packages/jobs/AGENTS.md` — the `notify` row
+- Modify: `.ai/lessons.md` — a new lesson
+
+**Steps:**
+1. Add a `notify` row. Say that it chunks its writes, renders and sends (`EMAIL_CHUNK` and the other sizes).
+2. Add a lesson about the 512 KB send limit and the 16.9 KB email.
+3. Use the format Context → Problem → Rule → Applies to.
+
+**Verify:**
+```bash
+grep -n "EMAIL_CHUNK" packages/jobs/AGENTS.md
+# Expected: 1 line
+```
+
+**Out of scope:** product docs. The change is not visible to a user.
+
+## Task 9: Run the gates and a large-group check
+
+**Depends on:** Tasks 1–8
+**Files:** none
+
+**Steps:**
+1. Run Biome on the changed files.
+2. Run the typecheck for `@carbon/jobs`, `@carbon/ee`, `@carbon/database` and `erp`, one at a time.
+3. Run the tests for `@carbon/jobs` and `@carbon/database`.
+4. Ask the user before you create test data for the large-group check.
+5. With approval, create a group of 1,200 users and send one notification to it.
+6. Check that `notification` has 1,200 new rows for that event.
+7. Check that the `carbon/notify` run has no failed step.
+8. If the company's plan includes email notifications, check for steps `fan-out-emails-0` to `fan-out-emails-59`.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs test
+# Expected: all tests pass
+pnpm --filter @carbon/database test
+# Expected: all tests pass
+```
+
+**Out of scope:** any database write without the user's approval (`.ai/lessons.md` and the user's standing rule).
diff --git a/.ai/runs/2026-10-08-web-push-notifications.md b/.ai/runs/2026-10-08-web-push-notifications.md
new file mode 100644
index 0000000000..ef2a77798e
--- /dev/null
+++ b/.ai/runs/2026-10-08-web-push-notifications.md
@@ -0,0 +1,54 @@
+# Feature run: Browser push notifications (Web Push) for the ERP
+
+- Date: 2026-10-08
+- Mode: fully-autonomous
+- Request: "i wanna go with option 2" (Web Push, which works when the browser is closed), then "yes go ahead with /feature".
+- Phase plan: research [skip — the requirements are clear and this is not ERP domain logic] · spec [run — new table, migration, dependency, service worker and channel across 3 packages] · plan [run] · execute [run] · test [skip — the user chose not to run it; push delivery needs a manual check] · self-review [run]
+
+## Agreed decisions (from the user, before the run)
+
+1. No plan gate. Push is free for all plans, like the in-app bell.
+2. Add `web-push` as a dependency of `@carbon/jobs`.
+3. ERP only. MES has no notification UI.
+4. The user turns on push per device at Account → Notifications. Each topic gets a "Browser" switch next to Email and Slack.
+5. Carbon sends one push per notification when it creates it. Push has no digest.
+6. If the VAPID env vars are missing, Carbon skips the push channel and hides the control.
+7. If the push service returns 404 or 410, Carbon deletes the subscription.
+8. Each deployment has one VAPID key pair in env vars.
+9. Carbon commits or pushes only when the user asks.
+
+## Decisions
+- Spec gate: the run resolved 7 open questions from codebase precedent. The spec marks each one **Autonomous**. No question is in Ask-First territory: the subscription table keeps `companyId`, and the user approved the `web-push` dependency. — 2026-10-08
+- Plan gate: the run approves the plan. It covers every acceptance criterion. Task 15 holds a manual browser checklist because the run skipped `/test`. — 2026-10-08
+- Review gate: the run fixed the 1 must-fix item. If a `notify` run is in flight across the deploy, it replays the old step output with no `pushRecipientIds`, and `.length` throws. The run now defaults the value to `[]`. It left the risks and suggestions to the user. — 2026-10-08
+
+## Phase log
+- spec: `.ai/specs/2026-10-08-web-push-notifications.md` written. STE-80 pass done.
+- plan: `.ai/plans/2026-10-08-web-push-notifications.md` written, 15 tasks. STE-80 pass done.
+- execute: 15 tasks done. Nothing committed: the user asks for each commit.
+ - Deviation 1: `packages/notifications/src/index.test.ts` pinned the old channel list `["email", "slack"]`. The run updated that assertion to include `"push"`.
+ - Deviation 2: `pnpm add web-push` also re-resolved unrelated peer dependencies in `pnpm-lock.yaml`. The run kept only the 49 `web-push` lines. `pnpm install --frozen-lockfile` passes.
+ - Deviation 3: `generate:mcp` changed `tool-manifest.digest.json`, because `upsertNotificationPreference` now accepts `push`. None of the 3 new functions became a tool.
+ - `pnpm db:check:backups` skipped: the local stack was not running.
+ - `/test` skipped by the user. The manual checklist is below.
+- self-review: 1 must-fix item, fixed (above). 5 risks and 4 suggestions go to the user. The `@carbon/jobs` typecheck passes after the fix.
+- After the run, with the user testing in Edge on macOS:
+ 1. `push-worker.js`: macOS replaced a notification with the same tag silently, so the worker now shows each push under a fresh identifier.
+ 2. The bell offers "Enable browser notifications" (a soft ask), with **Not now** snoozing it per browser.
+ 3. Browser notifications became a setting of the browser. One row per endpoint, pushes from every company the user belongs to, and a stop on every sign-out path (`clearAuthCookies` and the `carbon-push` cookie). The next user to sign in gets their own notifications with no prompt.
+ 4. Three more self-reviews. They added `restoreStep` with tests, the `VAPID_SUBJECT` check, the `userId` match in `send-push`, the folded migration, and the doc and lesson updates. The spec records each change in its changelog.
+
+## Manual browser checklist
+
+1. Restart the ERP and the Inngest dev server. The VAPID pair is derived from `SESSION_SECRET`; there is nothing to set (2026-10-09).
+2. Open Account → Notifications. Click **Enable** and allow the prompt.
+3. Close every Carbon tab. Assign a job to the user from a second account. Expect "Job assigned to you".
+4. Click **Disable**. Expect 0 `pushSubscription` rows for the endpoint.
+5. Enable again, sign out, and sign in as another user. Expect that user's notifications with no prompt, and none of the first user's.
+6. If no banner appears although `send-push` returns `201`, check macOS: System Settings → Notifications → Microsoft Edge allows banners, and no Focus mode is on.
+
+## Outcome
+- Built and verified. Push works end to end in Edge on macOS. The user committed each round on `naveenkash/carbon-browser-notifications`, and every commit is pushed.
+- Done: the local migration repair for the folded migration, and PR #1867 with the `Tracking spec:` line.
+- Later changes at the user's request: push mirrors in-app (no per-topic switch, no event filter), and the "Send a test notification" button is removed.
+- Open: screenshots for the PR, and moving the spec to `implemented/` after merge.
diff --git a/.ai/specs/2026-10-08-web-push-notifications.md b/.ai/specs/2026-10-08-web-push-notifications.md
new file mode 100644
index 0000000000..4dc4cc7b82
--- /dev/null
+++ b/.ai/specs/2026-10-08-web-push-notifications.md
@@ -0,0 +1,412 @@
+# Push notifications in the browser (Web Push)
+
+> Status: in-progress
+> Author: Claude
+> Date: 2026-10-08
+
+## TLDR
+
+Carbon shows a notification only in the ERP bell, by email or by Slack. If no Carbon tab is open, the user sees nothing until they open the app or read their mail. This spec adds a fourth channel: **push**.
+
+Push uses the Web Push standard to show an operating-system notification, even when every Carbon tab is closed. Browser notifications are a setting of the **browser**, not of a user. Once someone enables them in a browser, whoever is signed in there gets their own notifications, from every company they belong to. Signing out stops them at once. Like the in-app bell, push has no per-topic switch: every notification pushes.
+
+The `notify` job sends one push for each notification it creates. The job uses the `web-push` package and one VAPID key pair for each deployment. The pair is derived from `SESSION_SECRET`, so push needs no setup.
+
+## Overview diagram
+
+```mermaid
+sequenceDiagram
+ participant U as Browser
+ participant SW as push-worker.js
+ participant ERP as ERP routes
+ participant DB as pushSubscription
+ participant N as notify job
+ participant S as send-push job
+ participant P as Push service
+ U->>SW: Enable: register + subscribe
+ U->>ERP: PUT subscription, gets carbon-push cookie
+ ERP->>DB: upsert the row of this endpoint
+ N->>DB: read rows of push recipients
+ N->>S: carbon/send-push per row
+ S->>P: signed, encrypted request
+ P->>SW: push event, worker shows it
+ U->>ERP: sign out, cookie names the endpoint
+ ERP->>DB: delete rows of the endpoint
+ U->>ERP: next sign-in, the bell re-saves the row
+```
+
+## Problem Statement
+
+1. The `notify` job (`packages/jobs/src/inngest/functions/notifications/notify.ts`) had 3 channels: in-app, email and Slack.
+2. The in-app channel reaches the user only while an ERP tab is open. `useNotifications` listens on the realtime topic `user:<userId>:notification`.
+3. Email is a paid feature (`EMAIL_NOTIFICATIONS`, Business and Partner plans). On other plans, a user with no ERP tab open gets no signal at all.
+4. A planner who closes the browser at the end of a shift misses an approval request or a job assignment until the next login.
+
+Before this change, no code in `apps/` or `packages/` called the Notification API, the Push API or `navigator.serviceWorker`. The file `apps/erp/public/serviceWorker.js` existed, but no code registered it. It is deleted (2026-10-09).
+
+## Proposed Solution
+
+### How Web Push works in Carbon
+
+1. Each deployment has one VAPID key pair. `getVapidDetails()` (`@carbon/env/push.server`) derives it from `SESSION_SECRET`. There are no push env vars.
+2. The user clicks **Enable** on the bell's "Enable browser notifications" row or on the **Browser notifications** card at Account → Notifications.
+3. The browser asks for permission to show notifications.
+4. The page registers the service worker `/push-worker.js` and calls `pushManager.subscribe()` with the VAPID public key.
+5. The browser returns a subscription: an endpoint URL and 2 keys (`p256dh`, `auth`).
+6. The page sends the subscription with `PUT /api/push-subscription`.
+7. The route saves one `pushSubscription` row for this endpoint, owned by the signed-in user.
+8. The route sets the signed `carbon-push` cookie, which holds the endpoint.
+9. The page sets `browserNotificationsEnabled` in localStorage: browser notifications are now on for this browser.
+10. Later, the `notify` job finds the push recipients and their `pushSubscription` rows, and sends one `carbon/send-push` event per row.
+11. The `send-push` job signs and encrypts the payload with `web-push` and posts it to the endpoint.
+12. The push service sends the payload to the browser, where `push-worker.js` shows the notification.
+13. When the user clicks the notification, the worker focuses an open Carbon tab or opens a new one at the notification's link.
+
+### Sign-out and the next sign-in
+
+1. Every sign-out path calls `clearAuthCookies` (`@carbon/auth`): the explicit sign-out, a forced sign-out and an expired session on the login page.
+2. `clearAuthCookies` reads the `carbon-push` cookie, deletes every row of that endpoint and clears the cookie. Pushes for the user who left stop at once.
+3. The browser keeps its permission, its subscription and the `browserNotificationsEnabled` flag.
+4. When the next user signs in, `useRestoreBrowserNotifications` runs from the always-mounted bell, once per tab and user.
+5. If permission is granted and the flag is set, it saves the browser's subscription for the user signed in now, with no prompt.
+6. The new user only ever gets their own notifications: `notify` sends a push to the owner of the row and nobody else.
+
+### Which notifications push
+
+Push mirrors in-app. If the deployment has push keys (`isPushConfigured()`, true wherever `SESSION_SECRET` is set), every recipient of the in-app row gets a push in each browser where notifications are on. There is no topic filter and no event filter. So `IntegrationSync`, which fires again on each sync sweep while failures last, also pushes each time.
+
+`notify` reads subscriptions by `userId` only. The step `resolve-recipients` already limits the recipients to members of the notification's company. So a user gets the push of every company they belong to, and a company switch does not silence the browser.
+
+A digest from `notify` (more than one item) sends one push with the digest's `description`. The cron job `notification-digest` sends no push, because it only rolls up rows that `notify` already delivered.
+
+### Payload
+
+| Field | Value |
+|---|---|
+| `title` | `getNotificationEmailHeading(event)`, for example "Job assigned to you". A workflow notification uses its author's subject (the `description`). |
+| `body` | the notification `description`, for example "Job J00105 assigned to you". A workflow notification uses its author's message, with each `[label](url)` reduced to its label. |
+| `url` | `buildNotificationLink(event, documentId, companyId, documentType)`; `/api/link` switches the company first |
+| `tag` | `` `${event}:${primaryDocumentId}` ``; the worker closes an older notification with the same tag before it shows the new one |
+
+`web-push` encrypts the payload end to end (`aes128gcm`). The push service cannot read it.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Plan gating | None. Push is free on all plans. | Agreed with the user. Push is another view of the in-app notification, and the bell is free. |
+| Library | `web-push` in `@carbon/jobs` | Agreed with the user. It does VAPID signing and payload encryption, which are easy to get wrong by hand. |
+| Apps | ERP only | Agreed with the user. MES has no notification UI. |
+| Channel name | "push" in code; "browser notifications" in the UI | "Browser notifications" is the word a user understands. |
+| Per-topic switch | None. Push is not a `NotificationDestination` or a `NotificationPreferenceChannel`. | Agreed with the user: push mirrors in-app, which has no switch either. |
+| Setting scope | A setting of the browser, not of a user | Agreed with the user. A shared computer gives each signed-in person their own notifications without a new opt-in. Browser permission is per site and browser too. |
+| Subscription rows | One row per endpoint (`UNIQUE ("endpoint")`), owned by the signed-in user. `companyId` is the company the user enabled it from. | One browser has one endpoint, so one owner at a time. `companyId` keeps tenant attribution and the RLS member check. |
+| Companies | The user gets the push of every company they belong to | Agreed with the user. `resolve-recipients` already drops non-members. |
+| Table shape | `id` from `xid()`, single-column PK, no audit columns | Same shape as `notificationPreference` and `userModulePreference`: a user-owned preference row. |
+| RLS | Owner and company member, the same rule as `notificationPreference` | The user reads and writes only their own rows. The jobs and the sign-out cleanup use the service role. |
+| Same browser, new user | On save, the route deletes the rows of OTHER users with the same endpoint (service role) | Only the user signed in now may own the browser's row. |
+| Sign out | `clearAuthCookies` deletes the rows of the endpoint in the signed `carbon-push` cookie | Agreed with the user: signing out stops pushes on every path, not only the Sign Out button. |
+| Next sign-in | `useRestoreBrowserNotifications` saves the browser for the new user with no prompt, while `browserNotificationsEnabled` is set | Agreed with the user. The setting belongs to the browser. |
+| Status check | `GET /api/push-subscription?endpoint=` is read-only | Opening a page never claims the browser. Only **Enable** and the sign-in restore save a row. |
+| The soft ask | The bell's inbox shows "Enable browser notifications" while nobody has enabled them in this browser | The native prompt opens only from a click, so a user who is not interested says no to Carbon, not to the browser. A browser "Block" is close to permanent. |
+| Prompt snooze | **Not now** hides the row for 30 days in this browser; a second **Not now** or a **Disable** hides it for good | The row must not nag. Account → Notifications always keeps the setting. |
+| Disable | Off for this browser, for everyone who uses it | The setting belongs to the browser. |
+| Which events push | Every notification, like in-app | Agreed with the user. In-app-only events push too, including the repeated `IntegrationSync` alert. |
+| Digests | One push per `notify` call; no push from the digest cron | Agreed with the user. The cron only regroups delivered rows. |
+| Where the VAPID keys come from | Derived from `SESSION_SECRET` with HKDF-SHA256. The subject is the app URL when it is https, else `mailto:` + `SUPPORT_EMAIL`. | Agreed with the user: env vars were too much to manage. A pair generated at build time was rejected: images are published per commit, so it would rotate on each build and ship the private key. Without `SESSION_SECRET` (a `SKIP_ENV_VALIDATION` script) there is no push channel. |
+| Dead subscription | `send-push` deletes the row on HTTP 404 or 410. On 401 or 403 it logs a warning and keeps the row. | Agreed with the user. 404 and 410 mean that the subscription is gone for good. 401 and 403 usually mean another VAPID key, but Apple also sends 403 when it refuses our token, so a delete could remove every Safari row. |
+| Retries | Retry on 429 and 5xx; no retry on other 4xx | A 4xx other than 404, 410 and 429 is a bad request, and a retry fails again. |
+| Delivery options | `TTL` = 86 400 s (1 day), `urgency` = `normal` | A notification older than 1 day is old news. The bell still has it. |
+| Fan-out shape | `notify` sends one `carbon/send-push` event per subscription row | Same pattern as `carbon/send-email` and `carbon/send-slack`. Each browser retries on its own. |
+| Service worker | New file `apps/erp/public/push-worker.js`, scope `/`; the old `serviceWorker.js` is deleted | The old file cached logos and avatars, and that behavior was never live. A browser allows one worker per scope, so registering it at `/` later would have replaced `push-worker.js` and stopped every push. |
+| Worker updates | `skipWaiting()` on install and `clients.claim()` on activate | The worker caches nothing, so a new version can take over at once. |
+| Repeated pushes | The worker never passes `tag` to `showNotification`. It closes older notifications with the same `data.tag`, then shows the new one under a fresh identifier. | The browser gives the tag to macOS as the identifier, and macOS replaces a notification with the same identifier silently. `renotify` does not help. |
+| Rotated subscription | The worker handles `pushsubscriptionchange`. It subscribes again and sends the new subscription with the old endpoint. | A browser can rotate the subscription at any time. Without this step, push stops with no signal. |
+| Focused tab | The worker always shows the notification | Chrome requires a visible notification for each push (`userVisibleOnly: true`). |
+| VAPID public key in the browser | The settings loader and the app shell loader (`pushPublicKey`) return it. It is not in `window.env`. | The server derives the pair, and returns `null` when it has none. |
+| MCP exposure | The new service functions have no `@mcp` tag | A browser subscription is meaningless to an API caller (`conventions-services.md`). |
+| Env group | New group `push` in `FEATURES`, with all 3 vars `needed` | `validateEnv` then warns when push is half-configured. |
+
+## Data Model Changes
+
+1. A new table, `pushSubscription`, one row per endpoint (migration `20261008002726`). `notificationPreference` does not change: push is not a preference channel.
+2. A new rule in `packages/database/src/authz/manifest.ts`, and the generated authz migration `20261008002814`. No migration holds a `CREATE POLICY`.
+
+```mermaid
+erDiagram
+ user ||--o{ pushSubscription : "owns"
+ company ||--o{ pushSubscription : "enabled from"
+ pushSubscription {
+ text id PK
+ text userId FK
+ text companyId FK
+ text endpoint UK
+ text p256dh
+ text auth
+ text userAgent
+ timestamptz createdAt
+ timestamptz updatedAt
+ }
+```
+
+The table:
+
+```sql
+CREATE TABLE "pushSubscription" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "userId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "endpoint" TEXT NOT NULL,
+ "p256dh" TEXT NOT NULL,
+ "auth" TEXT NOT NULL,
+ "userAgent" TEXT,
+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT now(),
+ "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT now(),
+
+ CONSTRAINT "pushSubscription_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "pushSubscription_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "pushSubscription_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "pushSubscription_endpoint_key" UNIQUE ("endpoint")
+);
+
+ALTER TABLE "pushSubscription" ENABLE ROW LEVEL SECURITY;
+
+CREATE INDEX "pushSubscription_userId_companyId_idx"
+ ON "pushSubscription" ("userId", "companyId");
+CREATE INDEX "pushSubscription_companyId_idx"
+ ON "pushSubscription" ("companyId");
+```
+
+Manifest rule (same as `notificationPreference`):
+
+```ts
+pushSubscription: policies({
+ select: and(owner("userId"), member("companyId")),
+ insert: and(owner("userId"), member("companyId")),
+ update: { using: owner("userId"), check: and(owner("userId"), member("companyId")) },
+ delete: and(owner("userId"), member("companyId"))
+}),
+```
+
+The table holds no business data, so the demo datasets need no change. `wipe.ts` finds tables by their `companyId` column. `pushSubscription` is in `SECRET_TABLES` (`packages/jobs/src/backups/schema.ts`): a backup never carries a browser's endpoint and keys, and an in-place restore leaves the current browsers alone. `pnpm db:check:backups` passes.
+
+## API / Service Changes
+
+### `@carbon/notifications`
+
+No change to the destinations or the preference channels. Push is neither a `NotificationDestination` nor a `NotificationPreferenceChannel`: it mirrors in-app.
+
+### `@carbon/env`
+
+1. Add `packages/env/src/push.server.ts` (export `@carbon/env/push.server`, server-only because it imports `node:crypto`). `deriveVapidDetails(secret, appUrl)` is the pure derivation; `getVapidDetails()` memoizes it for `SESSION_SECRET`.
+2. `isPushConfigured()` returns true when `getVapidDetails()` is not null.
+
+### `@carbon/lib`
+
+1. Add the event `"carbon/send-push"` to `Events` with `data: { subscriptionId, userId, companyId, title, body, url, tag }`. `userId` is the recipient, and `companyId` is the notification's company.
+2. Do not add `"send-push"` to the `trigger` map. Only `notify` sends `carbon/send-push`, with `step.sendEvent`.
+
+### `@carbon/auth`
+
+1. `session.server.ts` exports `pushEndpointCookie`: the signed, `httpOnly` cookie `carbon-push`, on the session cookie's domain, with a 400-day `maxAge`.
+2. `clearAuthCookies` reads the cookie. If it holds an endpoint, it deletes every `pushSubscription` row of that endpoint with the service role, then clears the cookie. A cross-site navigation (`Sec-Fetch-Site: cross-site`) skips this, per the GET-write rule in `packages/auth/AGENTS.md`: the login loader runs it on a GET.
+3. The service-role client loads inside that cleanup, not at module load, so importing the session module builds no Supabase client.
+4. If the delete fails, sign-out still succeeds and the error goes to the log. The next 404 or 410 removes the row.
+
+### `@carbon/jobs`
+
+1. Add `web-push` (and `@types/web-push` as a dev dependency).
+2. Change `notify.ts`:
+ 1. Compute `wantsPush`: `isPushConfigured()`. The step `filter-recipients-by-preference` stays as it was: it filters email and Slack only.
+ 2. Add the step `resolve-push-subscriptions`. It reads the `pushSubscription` rows of every recipient (`userIds`, the same list as the in-app rows) whose `updatedAt` is within a session's lifetime (`pushSessionMaxAgeMs`: 12 h in a controlled environment, the 7-day session cookie elsewhere), and builds one `carbon/send-push` event per row, with the row's `userId`.
+ 3. Send the events with `step.sendEvent("fan-out-push", …)`.
+3. Add `send-push.ts` (function id `send-push`, 3 retries):
+ 1. Read the row by `subscriptionId` and `userId` with the service role. If no row matches, return: the browser was disabled, signed out or handed to another user since the fan-out.
+ 2. Call `webpush.sendNotification` with the VAPID details, `TTL: 86400` and `urgency: "normal"`.
+ 3. If the status is 404 or 410, delete the row and return.
+ 4. If the status is 401 or 403, log a warning with the push service's body and keep the row. WNS (401) and FCM (403) send these for a subscription made with another VAPID key. Apple sends 403 when it refuses our token, which hits every Safari row, so the row is never deleted on these codes.
+ 4. If the status is 429 or 5xx, throw, so that Inngest retries.
+ 5. For any other error, throw `NonRetriableError`.
+ 6. Put the status code on the step output, so the run record shows it.
+4. Register `sendPushFunction` in `packages/jobs/src/inngest/index.ts`.
+5. Put the error-to-action mapping in the pure function `pushDeliveryOutcome(statusCode)`, with a unit test.
+
+### ERP
+
+1. `account.models.ts`:
+ 1. Add `pushSubscriptionValidator`: `{ endpoint: url, keys: { p256dh, auth }, oldEndpoint?: url }`, and `pushSubscriptionEndpointValidator`: `{ endpoint: url }`.
+2. `account.service.ts`, with no `@mcp` tag:
+ 1. `getPushSubscription(client, { userId, endpoint })`
+ 2. `upsertPushSubscription(client, { userId, companyId, endpoint, p256dh, auth, userAgent })`, `onConflict: "endpoint"`
+ 3. `deletePushSubscription(client, { userId, endpoint })`
+ 4. `deleteBrowserPushSubscriptions(client, { endpoint, exceptUserId? })`: every user's rows for a browser endpoint. The route passes the service-role client.
+3. The resource route `apps/erp/app/routes/api+/push-subscription.ts`, gated by `requirePermissions(request, {})`. If push is not configured, `GET` returns `{ enabled: false }` and every write returns 404.
+ 1. `GET ?endpoint=`: return `{ enabled }` for the signed-in user. If the row exists, set the `carbon-push` cookie again, so a row saved before the cookie existed still ends at sign-out.
+ 2. `PUT`: validate the body. If `oldEndpoint` is set, delete that row. If the `carbon-push` cookie names a different endpoint, delete that endpoint's rows (service role): it is this browser's previous subscription. Delete the rows of other users with the same endpoint (service role). Upsert the row. Set the `carbon-push` cookie.
+ 3. `DELETE`: delete the row of this user and endpoint. Clear the cookie.
+4. The app shell loader (`x+/_layout.tsx`) returns `pushPublicKey`, which is `null` when push is not configured.
+
+## UI Changes
+
+### `apps/erp/public/push-worker.js` (new)
+
+1. `install`: `skipWaiting()`. `activate`: `clients.claim()`.
+2. `push`: parse the JSON payload. If it has a `tag`, close the shown notifications whose `data.tag` matches. Call `showNotification(title, { body, icon: "/carbon-mark-dark.png", data: { url, tag } })`.
+3. `notificationclick`: close the notification. Find a window client on the same origin that the worker controls, then focus it and navigate it to `data.url`. If no client exists, or the focus or the navigation fails, call `clients.openWindow(data.url)`. `navigate()` rejects for a client the worker does not control.
+4. `pushsubscriptionchange`: take `event.newSubscription`, else the registration's current subscription, else subscribe again with the old subscription's key. If none exists, stop. `PUT /api/push-subscription` the result, with `oldEndpoint` only when an old subscription exists.
+
+The icon is `/carbon-mark-dark.png`, the file that the ERP's `site.webmanifest` names.
+
+### `apps/erp/app/utils/push.ts` (new)
+
+1. `urlBase64ToUint8Array`: converts the base64url public key for `pushManager.subscribe()`.
+2. The bell row's snooze: `parsePromptDismissal`, `isPromptSnoozed`, `nextPromptDismissal`, `readPromptDismissal` and `dismissBrowserNotificationsPrompt`. They keep `browserNotificationsPrompt` in localStorage, per browser.
+3. The browser setting: `rememberBrowserNotifications(on)` and `areBrowserNotificationsEnabled()` keep `browserNotificationsEnabled` in localStorage.
+4. `restoreStep` decides what a page load does: `remember`, `save` or `skip`.
+5. `push.test.ts` covers the key conversion, the snooze rules and `restoreStep`.
+
+### `apps/erp/app/hooks/usePushSubscription.ts` (new)
+
+`usePushSubscription({ publicKey })` returns one state and 2 actions:
+
+| State | Meaning |
+|---|---|
+| `unsupported` | No `serviceWorker`, `PushManager` or `Notification` in `window`. Safari on iPhone or iPad without "Add to Home Screen" is in this state. |
+| `denied` | `Notification.permission === "denied"` |
+| `off` | The browser has no subscription, or the signed-in user has no row for it (`GET` status check) |
+| `on` | The browser has a subscription and the signed-in user owns its row |
+
+Actions:
+
+1. `turnOn()`: request permission, register `/push-worker.js`, subscribe with `userVisibleOnly: true`, `PUT` the subscription, then set `browserNotificationsEnabled`. If the browser's subscription was made with an older VAPID key, `subscribe` unsubscribes it first and the `PUT` carries its endpoint as `oldEndpoint`.
+2. `turnOff()`: `DELETE` the row, unsubscribe in the browser, then clear `browserNotificationsEnabled`.
+
+`useRestoreBrowserNotifications({ publicKey, userId })` runs once per tab and user:
+
+1. If permission is not `granted`, clear `browserNotificationsEnabled` and stop: the user revoked or reset it in the browser, so the bell may ask again.
+2. If the browser has a subscription and the user owns its row, set `browserNotificationsEnabled`.
+3. If neither the user owns the row nor `browserNotificationsEnabled` is set, stop.
+4. Subscribe (replacing a subscription made with an older VAPID key), then `PUT` it for the user signed in now. This runs on every tab load, also when the row exists: the save refreshes `updatedAt`, which `notify` reads to skip browsers whose session has ended.
+
+### The bell (`Layout/Topbar/Notifications.tsx`, `EnableBrowserNotifications.tsx`)
+
+1. The bell calls `useRestoreBrowserNotifications`. The bell is always mounted, so every page load in a tab reaches it.
+2. The inbox tab shows a row above the list or the empty state. Its title is "Enable browser notifications", and its text is "Get your Carbon notifications as they happen." Its buttons are **Enable** and **Not now**.
+3. The row shows only when all 4 conditions are true:
+ 1. Push is configured.
+ 2. Permission is not `denied`.
+ 3. `browserNotificationsEnabled` is not set.
+ 4. The prompt is not snoozed.
+4. The row hides itself when its status check says the user is already on.
+
+### Account → Notifications (`x+/account+/notifications.tsx`)
+
+1. The loader returns `push: { publicKey } | null`. The value is `null` when `isPushConfigured()` is false.
+2. If `push` is not null, the card **Browser notifications** sits above the topic table:
+ - `off`: the text "Get your Carbon notifications as they happen." and the button **Enable**.
+ - `on`: the text "Browser notifications are on for this browser." and the button **Disable**.
+ - `denied`: the text "Notifications are blocked for Carbon in this browser's site settings."
+ - `unsupported`: the text "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+3. **Disable** also snoozes the bell row for good.
+4. The topic table keeps only its Email and Slack columns: push has no per-topic switch.
+5. All new strings use Lingui macros, and `/translate` filled the 12 other locales.
+
+### Other
+
+No change to MES or to `useNotifications`. `AvatarMenu.tsx` is unchanged: sign-out cleanup lives in `@carbon/auth`.
+
+## Acceptance Criteria
+
+- [ ] A user clicks **Enable** at Account → Notifications and allows the prompt. The card says "Browser notifications are on for this browser".
+- [ ] After **Enable**, the database has exactly 1 `pushSubscription` row for that endpoint, owned by the user. The browser has the `carbon-push` cookie.
+- [ ] A second notification about the same job shows a second banner, not a silent replacement.
+- [ ] With every Carbon tab closed and the browser still running, assigning a job to the user shows "Job assigned to you". A click opens the job.
+- [ ] A user who belongs to 2 companies gets the push of a job assigned in each company, whichever company is open.
+- [ ] The topic table has no Browser column. Every notification, of every topic, pushes to each enabled browser of its recipient.
+- [ ] An `IntegrationSync` notification creates an in-app row and also pushes, like every in-app notification.
+- [ ] After sign-out, the endpoint has no row and the next assignment to the previous user sends no push to that browser.
+- [ ] Another user signs in to that browser. The browser gets that user's notifications with no prompt, and none of the previous user's.
+- [ ] **Disable** deletes the row and clears `browserNotificationsEnabled`. The next user to sign in gets no push and no bell row.
+- [ ] The bell shows "Enable browser notifications" only while nobody has enabled them in this browser. **Not now** hides it for 30 days.
+- [ ] With no `SESSION_SECRET` (`getVapidDetails()` is null), Account → Notifications shows no card, and the bell shows no row. `notify` sends no `carbon/send-push` event and does not fail.
+- [ ] `pushDeliveryOutcome` has unit tests for 201, 404, 410, 413, 429 and 503. `push.test.ts` covers the snooze rules.
+- [ ] `notificationPreferenceValidator` accepts only `email` and `slack`.
+- [ ] Scoped typecheck passes for `@carbon/auth`, `@carbon/jobs`, `@carbon/notifications`, `@carbon/env`, `@carbon/lib`, `erp` and `docs`. Biome passes. `migration.test.ts` passes.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| A session that ends without any sign-out path keeps its row | Low | Bounded: every page load saves the row again, and `notify` skips rows older than a session's lifetime (12 h in a controlled environment, the 7-day session cookie elsewhere). The next visit's login page or sign-in also replaces it. |
+| The login loader runs the push cleanup on a GET | Low | A cross-site navigation skips it, which is what the GET-write rule guards against; such rows lapse through the `updatedAt` cutoff. |
+| Changing the VAPID key pair (rotating `SESSION_SECRET`) breaks every subscription | Low | The next page load replaces a subscription made with an older key (`hasApplicationServerKey`), and the settings card shows it as off until then. A push to an old-key row gets 401 or 403, and `send-push` logs a warning and keeps the row. The browser's next page load replaces it, or it ages out after a session's lifetime. |
+| If the user revokes the permission in the browser, the browser-wide flag would stay set | Low | Fixed: the restore clears `browserNotificationsEnabled` whenever permission is not `granted`, so the bell can ask again. |
+| Safari can refuse `pushManager.subscribe()` without a user click, which the restore needs only when the browser lost its subscription | Low | The restore logs the error. **Enable** still works. |
+| Safari on iPhone or iPad supports push only for a Home Screen web app | Low | The `unsupported` text says so. The manifest already has `display: standalone`. |
+| `IntegrationSync` pushes every sweep: the outbound sweep runs every 30 minutes (`15,45 * * * *`) and, while failures remain, notifies the integration's last editor (`updatedBy`) | Low | Accepted by the user: push mirrors in-app exactly. `notify.ts` documents it on the `IntegrationSync` default. |
+| A recurring reminder (weekly training) pushes every cycle; email has a delivery cap, push does not | Low | The same notification is also in the bell each week. |
+| Company backups would carry `pushSubscription` rows | Low | Fixed: the table is in `SECRET_TABLES`, so it is never exported and an in-place restore keeps the current rows. |
+| A strict CSP later blocks the worker | Low | The strict policy already allows `worker-src 'self'` (`packages/auth/src/lib/security.ts`). |
+| A large group notification sends many push events | Low | One event per browser, the same scale as the email fan-out. Inngest queues the events. |
+| `web-push` is a new production dependency | Low | The user approved it. It is the reference library of the Web Push standard. |
+
+## Open Questions
+
+- [x] Should push need a paid plan? — **Answer (user):** No. Push is free on all plans.
+- [x] Which library sends the push? — **Answer (user):** `web-push` in `@carbon/jobs`.
+- [x] Which apps get push? — **Answer (user):** ERP only.
+- [x] How does a user opt in? — **Answer (user):** At Account → Notifications. A "Browser" switch per topic came first; the user later removed it, so push mirrors in-app. Later the user also added the bell's "Enable browser notifications" row, with the copy of option A.
+- [x] Do digests push? — **Answer (user):** One push per notification at creation. No digest for push.
+- [x] What happens without VAPID keys? — **Answer (user):** Carbon skips the channel and hides the controls. **Superseded 2026-10-09:** the keys are derived from `SESSION_SECRET`, so only a process without one has no channel.
+- [x] What happens to a dead subscription? — **Answer (user):** Carbon deletes it on 404 or 410.
+- [x] Is a subscription per user or per user and company? — **Answer (user, replaces the first autonomous answer "per user and company"):** The signed-in user gets the notifications of every company they belong to. One row per browser endpoint.
+- [x] What happens on sign-out? — **Answer (user):** Signing out stops the notifications in that browser, on every sign-out path.
+- [x] Is the setting per user or per browser? — **Answer (user):** Per browser. Once enabled, whoever signs in gets their own notifications.
+- [x] Which events push? — **Answer (user, replaces the first autonomous answer "destinations with Push, Email or Slack"):** Every notification, exactly like in-app, including in-app-only events.
+- [x] How does the user check that push works? — **Autonomous at first:** a "Send a test notification" button. **Answer (user, later):** remove it; a real notification is the check.
+- [x] What happens when the browser rotates a subscription? — **Autonomous:** `push-worker.js` handles `pushsubscriptionchange` and sends the new subscription.
+- [x] Should Carbon register the existing `serviceWorker.js`? — **Autonomous:** No. A new `push-worker.js` holds only the push handlers. **Later (user, 2026-10-09):** delete `serviceWorker.js`.
+- [x] Should Carbon skip the push when a Carbon tab has focus? — **Autonomous:** No. Chrome requires a visible notification for each push.
+
+## Changelog
+
+- 2026-10-08: Created by the autonomous `/feature` run (`.ai/runs/2026-10-08-web-push-notifications.md`). The user answered 7 questions before the run. The run resolved the other 7 itself and marks them **Autonomous** above.
+- 2026-10-08: Implemented on `naveenkash/carbon-browser-notifications`. The test POST route sets `tag` to `carbon-test`, so a second test replaces the first.
+- 2026-10-08: Two changes after testing:
+ 1. `push-worker.js` no longer passes `tag` to `showNotification`. Edge gives the tag to macOS as the notification's identifier, and macOS replaces a notification with the same identifier silently, so no banner appears. The worker closes older notifications with the same `data.tag` itself, then shows the new notification under a fresh identifier.
+ 2. The bell's inbox tab shows an "Enable browser notifications" row (`EnableBrowserNotifications.tsx`). It is the soft ask: the native prompt opens only from its **Enable** click. The settings card is now titled "Browser notifications", with **Enable** and **Disable** buttons.
+- 2026-10-08: A subscription now belongs to the browser and the user signed into it, not to one company.
+ 1. `endpoint` became unique: one row per browser. A second migration did this at first; before release it was folded into `20261008002726`.
+ 2. `notify` reads subscriptions by `userId` only, so a user gets the push of every company they belong to.
+ 3. Signing out stops pushes on every path, through the `carbon-push` cookie and `clearAuthCookies` (`@carbon/auth`). The change removes the client-side unsubscribe from `AvatarMenu`.
+ 4. Opening a page never claims the browser: the hook reads `GET /api/push-subscription?endpoint=`.
+- 2026-10-08: Browser notifications became a setting of the browser (`browserNotificationsEnabled`). `useRestoreBrowserNotifications` saves the browser for each user who signs in. **Not now** and **Disable** snooze the bell row per browser.
+- 2026-10-08: The spec body was rewritten to match the shipped design. The earlier sections described the per-company rows, the "This device" card and the AvatarMenu unsubscribe.
+- 2026-10-08: Two changes from self-review:
+ 1. `VAPID_SUBJECT` now has a `type` in `packages/env/src/schema.ts`. `validateEnv` reports a subject that does not start with `mailto:` or `https://` at startup, not on each send.
+ 2. `restoreStep` (`apps/erp/app/utils/push.ts`) holds the decision of `useRestoreBrowserNotifications`: `remember`, `save` or `skip`. `push.test.ts` covers the 3 cases.
+- 2026-10-08: From the third self-review:
+ 1. `carbon/send-push` carries the recipient's `userId`, and `send-push` sends only when the row still belongs to that user. The guarantee "only the recipient's browser" is now a check, not a result of how ids are assigned.
+ 2. The 2 unreleased migrations are one: `20261008002726` creates `pushSubscription` with `UNIQUE ("endpoint")`.
+- 2026-10-08: From the CodeRabbit review of PR #1867:
+ 1. `pushsubscriptionchange` no longer gives up when `oldSubscription` is null. The Push API makes both subscriptions nullable.
+ 2. `endBrowserPush` builds the service-role client inside its `try`, so sign-out still clears its cookies when the client cannot be built.
+ 3. A workflow push takes its author's subject as the title and their message as the body.
+ 4. `packages/database/AGENTS.md` documents the user-owned preference rows (`notificationPreference`, `userModulePreference`, `pushSubscription`) as an exception to the table template.
+- 2026-10-08: Push mirrors in-app, at the user's request. The per-topic **Browser** switch is gone. Push is no longer a `NotificationDestination` or a `NotificationPreferenceChannel`, and `wantsPushDelivery` is removed. `notify` pushes to every recipient of the in-app row, so in-app-only events such as `IntegrationSync` push too. The `notificationPreference` CHECK still allows `push`, unused.
+- 2026-10-08: The "Send a test notification" button is removed, at the user's request: the card's `on` state shows only **Disable**, `usePushSubscription` has no `sendTest`, and `/api/push-subscription` has no `POST` branch.
+- 2026-10-08: Risk fixes from the fourth self-review:
+ 1. Every page load saves the browser's row again (`updatedAt`). `notify` skips rows older than a session's lifetime, so a session that ends without a sign-out stops getting pushes within that window.
+ 2. `clearAuthCookies` skips the push cleanup on a cross-site navigation (the GET-write rule).
+ 3. A subscription made with an older VAPID key is replaced on the next page load or **Enable**, and its old row is deleted.
+ 4. The restore clears `browserNotificationsEnabled` when permission is no longer `granted`.
+ 5. `pushSubscription` joined `SECRET_TABLES`, so backups never carry it.
+ 6. The migration no longer widens the `notificationPreference.channel` CHECK.
+- 2026-10-09: The VAPID env vars are gone, at the user's request. `getVapidDetails()` (`@carbon/env/push.server`) derives the pair from `SESSION_SECRET` with HKDF-SHA256, so push works on every deployment with no setup. `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT` and the `push` env group are removed. Rotating `SESSION_SECRET` rotates the pair; each browser re-subscribes on its next visit. `deriveVapidDetails` is pinned by `packages/env/src/push.server.test.ts`.
+- 2026-10-09: Two fixes from a manual test:
+ 1. `pushDeliveryOutcome` maps 401 and 403 to `rejected`. WNS answered 401 for a subscription made with the old env-var key, and `send-push` failed on it for each notification. Now `send-push` logs a warning and completes. It keeps the row, at the user's request: Apple sends 403 for a token it refuses, and a delete would remove every Safari row.
+ 2. `notificationclick` uses only the tabs the worker controls, and opens a new window when the focus or the navigation fails. Before, `navigate()` rejected on an uncontrolled tab and the click opened nothing.
+ 3. `PUT /api/push-subscription` deletes the endpoint that the `carbon-push` cookie remembers when it differs from the new one. A browser that lost its subscription makes a new one with no `oldEndpoint`, and its old row waited for a failed push.
+ 4. `deriveVapidDetails` has a known-answer test, cross-checked with OpenSSL. A change to the hash, the salt or the info label changes every deployment's key, so the test fails.
+- 2026-10-09: Cleanup from self-review. The `"send-push"` entry left the `trigger` map: nothing called it, and only `notify` sends pushes. `pushDeliveryOutcome` lost its `delivered` result, because web-push throws only for a non-2xx status. `supportsPush` moved to `apps/erp/app/utils/push.ts`, so the bell row and the hook share one check. The route's two service-role deletes became `deleteBrowserPushSubscriptions`. The push cookie and the session cookie share one options object.
+- 2026-10-09: `apps/erp/public/serviceWorker.js` is deleted, at the user's request. No code registered it. Registered at scope `/`, it would replace `push-worker.js`.
diff --git a/.claude/rules/authentication-system.md b/.claude/rules/authentication-system.md
index 41bb548b61..b89d59e606 100644
--- a/.claude/rules/authentication-system.md
+++ b/.claude/rules/authentication-system.md
@@ -251,6 +251,18 @@ why there is no `form-action`: `.ai/plans/2026-09-28-csp-csrf.md`.
- `requireAuthSession` reads/validates; `getOrRefreshAuthSession` refreshes within
`REFRESH_ACCESS_TOKEN_THRESHOLD` (10 min) of expiry via `refreshAccessToken`.
- `destroyAuthSession` clears auth + company-id cookies, redirects to login.
+- `clearAuthCookies` (which `destroyAuthSession` and the login loader's
+ expired-session branch call) also ends this browser's push notifications: it
+ reads the signed `carbon-push` cookie (`pushEndpointCookie`, set by
+ `api+/push-subscription` when browser notifications are enabled), deletes every
+ `pushSubscription` row of that endpoint with the service role, and clears the
+ cookie. Every sign-out path therefore stops pushes in that browser. A cross-site
+ navigation (`Sec-Fetch-Site: cross-site`, the login GET from another site's
+ link) skips the cleanup, per the GET-write rule; such rows lapse anyway, because
+ `notify` skips rows no page load has refreshed within a session's lifetime. The
+ service-role client is imported inside that cleanup, not at module load, so
+ importing `session.server` builds no Supabase client (the session tests mock
+ `config/env` without the Supabase keys).
`updateCompanySession` / `updateSessionConsole` switch active company / console mode.
- **Console pin-in** (`@carbon/auth/console-pin.server`): which operator is pinned in
at a console terminal lives in the `console-pin-<companyId>` cookie, SIGNED with
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index 4c4adbb3e1..0e6f0c9ee5 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -85,7 +85,9 @@ both use it; `company-backup.ts` re-exports it), exported to app code as
accounts, currencies, dimensions).
- Skip/scope sets: `SECRET_TABLES` (`apiKey`, `apiKeyRateLimit`,
`companyIntegration`, `employeePin`, `webhook`, `oauthClient`, `oauthCode`, `oauthToken`,
- `ssoConnection`, `ssoDomain` — never travel; SSO rows carry values unique across all
+ `ssoConnection`, `ssoDomain`, `pushSubscription` — never travel; `pushSubscription` is a
+ browser's push endpoint and its encryption keys, so a restore must neither bring back
+ signed-out browsers nor wipe the current ones; SSO rows carry values unique across all
companies (`providerId`, a verified `domain`), so a cross-company copy collided;
`employeePin` holds console-PIN bcrypt hashes, a credential for a 4-digit PIN, and
stays in place on restore alongside `employee` (`IN_PLACE_SKIPPED_TABLES`), which is
diff --git a/.claude/rules/environment-configuration.md b/.claude/rules/environment-configuration.md
index fc47699f1c..6e63e2dd90 100644
--- a/.claude/rules/environment-configuration.md
+++ b/.claude/rules/environment-configuration.md
@@ -103,6 +103,25 @@ default 587), `SMTP_USER`, `SMTP_PASSWORD`, `SMTP_FROM` (default
Optional `RESEND_API_KEY` (marketing contacts; also a legacy SMTP fallback via
smtp.resend.com when `SMTP_*` is unset) and `RESEND_AUDIENCE_ID`.
+**Push** — no env vars. `getVapidDetails()` (`@carbon/env/push.server`,
+server-only because it imports `node:crypto`) derives the VAPID pair from
+`SESSION_SECRET` with HKDF-SHA256 (salt `carbon`, info `web-push-vapid/<n>`,
+the first `n` whose 32 bytes are a valid P-256 scalar) and memoizes it. The
+subject is `getAppUrl()` when it is https, else `mailto:` + `SUPPORT_EMAIL`.
+Every browser subscription is bound to the public key, so the pair must be
+stable: never generate it at build time (images are published per commit, which
+would rotate it and ship the private key). Rotating `SESSION_SECRET` rotates the
+pair — each browser re-subscribes on its next visit
+(`useRestoreBrowserNotifications`); until then, a push to an old-key row gets
+401 (WNS) or 403 (FCM), and `send-push` logs a warning and keeps the row. It
+never deletes on those codes: Apple answers 403 for a token it refuses, which
+would remove every Safari row. The hash, salt and info label are frozen —
+`push.server.test.ts` pins a known answer.
+`isPushConfigured()` is false only without `SESSION_SECRET` (a
+`SKIP_ENV_VALIDATION` script). The public key reaches the browser through the
+account notifications loader and the app shell loader (`pushPublicKey`), not
+`getBrowserEnv()`.
+
**Integrations (all optional)** — Ramp (`RAMP_CLIENT_ID`, public and exposed by
`getBrowserEnv()` for the authorize URL; `RAMP_CLIENT_SECRET`, server-only for code
exchange/token refresh), Slack (`SLACK_BOT_TOKEN`, `SLACK_CLIENT_ID`,
diff --git a/apps/erp/app/components/Layout/Topbar/EnableBrowserNotifications.tsx b/apps/erp/app/components/Layout/Topbar/EnableBrowserNotifications.tsx
new file mode 100644
index 0000000000..a177860f1d
--- /dev/null
+++ b/apps/erp/app/components/Layout/Topbar/EnableBrowserNotifications.tsx
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { Button } from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+import { useState } from "react";
+import { usePushSubscription } from "~/hooks/usePushSubscription";
+import {
+ areBrowserNotificationsEnabled,
+ dismissBrowserNotificationsPrompt,
+ isPromptSnoozed,
+ readPromptDismissal,
+ supportsPush
+} from "~/utils/push";
+
+// The soft ask: our own row, so a user who is not interested says no to us,
+// not to the browser — a browser "Block" is close to permanent. The native
+// prompt only ever opens from the Enable click.
+//
+// Browser notifications are a setting of this browser, so the row is offered
+// only until anyone enables them here; after that, whoever signs in gets
+// their own (useRestoreBrowserNotifications).
+function canAsk() {
+ return supportsPush() && Notification.permission !== "denied";
+}
+
+export function EnableBrowserNotifications({
+ publicKey
+}: {
+ publicKey: string | null;
+}) {
+ // Decided once, when the row mounts. The bell's popover renders its content
+ // only while open, so this never runs on the server; the window check in
+ // supportsPush keeps it safe if that changes.
+ const [eligible, setEligible] = useState(
+ () =>
+ Boolean(publicKey) &&
+ canAsk() &&
+ !areBrowserNotificationsEnabled() &&
+ !isPromptSnoozed(readPromptDismissal())
+ );
+
+ if (!eligible || !publicKey) return null;
+
+ return (
+ <EnableBrowserNotificationsRow
+ publicKey={publicKey}
+ onDismiss={() => {
+ dismissBrowserNotificationsPrompt();
+ setEligible(false);
+ }}
+ />
+ );
+}
+
+function EnableBrowserNotificationsRow({
+ publicKey,
+ onDismiss
+}: {
+ publicKey: string;
+ onDismiss: () => void;
+}) {
+ const { state, busy, turnOn } = usePushSubscription({ publicKey });
+
+ // Enabled, blocked from the prompt, or unsupported after all: nothing left
+ // to ask here.
+ if (state !== "off") return null;
+
+ return (
+ <div className="flex flex-col gap-2 border-b bg-muted/30 px-4 py-3">
+ <div className="flex flex-col gap-0.5">
+ <p className="text-sm font-medium">
+ <Trans>Enable browser notifications</Trans>
+ </p>
+ <p className="text-xs text-muted-foreground">
+ <Trans>Get your Carbon notifications as they happen.</Trans>
+ </p>
+ </div>
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant="primary"
+ onClick={turnOn}
+ isDisabled={busy}
+ isLoading={busy}
+ >
+ <Trans>Enable</Trans>
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ onClick={onDismiss}
+ isDisabled={busy}
+ >
+ <Trans>Not now</Trans>
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
index 533cf40b09..07e5fd8817 100644
--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
@@ -18,7 +18,8 @@ import {
Tabs,
TabsContent,
TabsList,
- TabsTrigger
+ TabsTrigger,
+ useRouteData
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { useEffect, useState } from "react";
@@ -55,10 +56,12 @@ import {
import { Link, useNavigate } from "react-router";
import { DateTime } from "~/components";
import { useNotifications, useUser } from "~/hooks";
+import { useRestoreBrowserNotifications } from "~/hooks/usePushSubscription";
import { usePeople } from "~/stores";
import type { Notification as NotificationRecord } from "~/types";
import { getRecordPath } from "~/utils/entity";
import { path } from "~/utils/path";
+import { EnableBrowserNotifications } from "./EnableBrowserNotifications";
type OutstandingTraining = {
trainingAssignmentId: string;
@@ -658,6 +661,12 @@ const Notifications = () => {
id: userId,
company: { id: companyId }
} = useUser();
+ const pushPublicKey =
+ useRouteData<{ pushPublicKey: string | null }>(path.to.authenticatedRoot)
+ ?.pushPublicKey ?? null;
+ // The bell is always mounted, so it is where a signed-back-in user's
+ // browser notifications come back.
+ useRestoreBrowserNotifications({ publicKey: pushPublicKey, userId });
const [isOpen, setOpen] = useState(false);
const [activeTab, setActiveTab] = useState("inbox");
// Loaded when the tab is opened, and again each time the popover reopens.
@@ -752,11 +761,15 @@ const Notifications = () => {
<TabsContent value="inbox" className="relative mt-0">
{!unreadNotifications.length && (
- <EmptyState description={t`No new notifications`} />
+ <>
+ <EnableBrowserNotifications publicKey={pushPublicKey} />
+ <EmptyState description={t`No new notifications`} />
+ </>
)}
{unreadNotifications.length > 0 && (
<ScrollArea className="pb-12 h-[485px]">
+ <EnableBrowserNotifications publicKey={pushPublicKey} />
<div className="divide-y">
{unreadNotifications.map((notification) => {
const event = notification.payload
diff --git a/apps/erp/app/hooks/usePushSubscription.ts b/apps/erp/app/hooks/usePushSubscription.ts
new file mode 100644
index 0000000000..4224aaba87
--- /dev/null
+++ b/apps/erp/app/hooks/usePushSubscription.ts
@@ -0,0 +1,271 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getLogger } from "@carbon/logger";
+import { toast } from "@carbon/react";
+import { useLingui } from "@lingui/react/macro";
+import { useCallback, useEffect, useState } from "react";
+import { path } from "~/utils/path";
+import {
+ areBrowserNotificationsEnabled,
+ hasApplicationServerKey,
+ rememberBrowserNotifications,
+ restoreStep,
+ supportsPush,
+ urlBase64ToUint8Array
+} from "~/utils/push";
+
+const logger = getLogger("erp", "usepushsubscription");
+
+const WORKER_URL = "/push-worker.js";
+
+export type PushState = "loading" | "unsupported" | "denied" | "off" | "on";
+
+async function currentSubscription() {
+ const registration = await navigator.serviceWorker.getRegistration("/");
+ return (await registration?.pushManager.getSubscription()) ?? null;
+}
+
+// Is the subscription on for the user signed in now? Read-only. The settings
+// card and the bell's restore ask at the same moment on the settings page;
+// concurrent asks for one endpoint share a request. Nothing is cached once it
+// settles, so the next ask sees an Enable or a Disable.
+const statusRequests = new Map<string, Promise<boolean>>();
+
+function isEnabledOnServer(endpoint: string) {
+ const inFlight = statusRequests.get(endpoint);
+ if (inFlight) return inFlight;
+ const request = (async () => {
+ const params = new URLSearchParams({ endpoint });
+ const response = await fetch(
+ `${path.to.api.pushSubscription}?${params.toString()}`,
+ { credentials: "same-origin" }
+ );
+ if (!response.ok) return false;
+ const status = (await response.json()) as { enabled?: boolean };
+ return status.enabled === true;
+ })().finally(() => statusRequests.delete(endpoint));
+ statusRequests.set(endpoint, request);
+ return request;
+}
+
+// Registers the worker and subscribes. Needs permission already granted.
+// Returns the browser's existing subscription when it was made with the
+// current VAPID key; one made with an older key is unsubscribed and replaced
+// (subscribe() refuses a new key while it exists), and its endpoint comes
+// back as replacedEndpoint so the server drops that row.
+async function subscribe(publicKey: string) {
+ await navigator.serviceWorker.register(WORKER_URL, { scope: "/" });
+ const registration = await navigator.serviceWorker.ready;
+ const existing = await registration.pushManager.getSubscription();
+ let replacedEndpoint: string | null = null;
+ if (
+ existing &&
+ !hasApplicationServerKey(existing.options.applicationServerKey, publicKey)
+ ) {
+ replacedEndpoint = existing.endpoint;
+ await existing.unsubscribe();
+ }
+ const subscription = await registration.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: urlBase64ToUint8Array(publicKey)
+ });
+ return { subscription, replacedEndpoint };
+}
+
+function saveSubscription(
+ subscription: PushSubscription,
+ replacedEndpoint: string | null
+) {
+ return sendSubscription("PUT", {
+ ...(subscription.toJSON() as Record<string, unknown>),
+ ...(replacedEndpoint ? { oldEndpoint: replacedEndpoint } : {})
+ });
+}
+
+function sendSubscription(
+ method: "PUT" | "DELETE",
+ body: Record<string, unknown>
+) {
+ return fetch(path.to.api.pushSubscription, {
+ method,
+ credentials: "same-origin",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ });
+}
+
+// The users this tab has already restored for. Module scope, not a ref: the
+// restore runs once per tab and user even if the bell remounts.
+const restoredFor = new Set<string>();
+
+// Browser notifications are a setting of this browser: once enabled, the
+// subscription is saved for whoever signs in. Sign-out deletes the row, so
+// this re-saves it for the user signed in now — without asking.
+export function useRestoreBrowserNotifications({
+ publicKey,
+ userId
+}: {
+ publicKey: string | null;
+ userId: string;
+}) {
+ useEffect(() => {
+ if (!publicKey || !supportsPush()) return;
+ if (Notification.permission !== "granted") {
+ // Revoked or reset in the browser's settings: the browser is no longer
+ // enabled, so the bell may ask again.
+ rememberBrowserNotifications(false);
+ return;
+ }
+ if (restoredFor.has(userId)) return;
+ restoredFor.add(userId);
+
+ (async () => {
+ try {
+ const existing = await currentSubscription();
+ const step = restoreStep({
+ ownedBySignedInUser: existing
+ ? await isEnabledOnServer(existing.endpoint)
+ : false,
+ browserEnabled: areBrowserNotificationsEnabled()
+ });
+ if (step === "skip") return;
+ if (step === "remember") rememberBrowserNotifications(true);
+ // Save on every tab load, also when the row exists: the save refreshes
+ // the row's updatedAt, and notify skips rows no session has refreshed
+ // within a session's lifetime (a signed-out-by-expiry browser).
+ const { subscription, replacedEndpoint } = await subscribe(publicKey);
+ const response = await saveSubscription(subscription, replacedEndpoint);
+ if (!response.ok) {
+ // Not restored: a later mount in this tab may try again.
+ restoredFor.delete(userId);
+ logger.error("Failed to restore browser notifications", {
+ status: response.status
+ });
+ }
+ } catch (error) {
+ restoredFor.delete(userId);
+ logger.error("Failed to restore browser notifications", { error });
+ }
+ })();
+ }, [publicKey, userId]);
+}
+
+export function usePushSubscription({
+ publicKey
+}: {
+ publicKey: string | null;
+}) {
+ const { t } = useLingui();
+ const [state, setState] = useState<PushState>("loading");
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ if (!publicKey || !supportsPush()) {
+ setState("unsupported");
+ return;
+ }
+ if (Notification.permission === "denied") {
+ setState("denied");
+ return;
+ }
+ let cancelled = false;
+ (async () => {
+ try {
+ const subscription = await currentSubscription();
+ if (!subscription) {
+ if (!cancelled) setState("off");
+ return;
+ }
+ // A subscription made with an older VAPID key cannot receive pushes;
+ // Enable replaces it.
+ if (
+ !hasApplicationServerKey(
+ subscription.options.applicationServerKey,
+ publicKey
+ )
+ ) {
+ if (!cancelled) setState("off");
+ return;
+ }
+ // The browser keeps its subscription across sign-outs, but signing
+ // out deletes the row: ask the server whether it is on for the user
+ // signed in now. Read-only — only Enable claims the browser.
+ const enabled = await isEnabledOnServer(subscription.endpoint);
+ if (!cancelled) setState(enabled ? "on" : "off");
+ } catch (error) {
+ logger.error("Failed to read the push subscription", { error });
+ if (!cancelled) setState("off");
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [publicKey]);
+
+ // Resolves false when the work threw (the failure is already toasted).
+ const run = useCallback(
+ async (work: () => Promise<void>, failure: string) => {
+ setBusy(true);
+ try {
+ await work();
+ return true;
+ } catch (error) {
+ logger.error(failure, { error });
+ toast.error(failure);
+ return false;
+ } finally {
+ setBusy(false);
+ }
+ },
+ []
+ );
+
+ const turnOn = useCallback(
+ () =>
+ run(async () => {
+ if (!publicKey) return;
+ const permission = await Notification.requestPermission();
+ if (permission === "denied") {
+ setState("denied");
+ return;
+ }
+ if (permission !== "granted") return;
+
+ const { subscription, replacedEndpoint } = await subscribe(publicKey);
+ const response = await saveSubscription(subscription, replacedEndpoint);
+ if (!response.ok) {
+ await subscription.unsubscribe();
+ setState("off");
+ toast.error(t`Failed to enable browser notifications`);
+ return;
+ }
+ rememberBrowserNotifications(true);
+ setState("on");
+ }, t`Failed to enable browser notifications`),
+ [publicKey, run, t]
+ );
+
+ const turnOff = useCallback(
+ () =>
+ run(async () => {
+ const subscription = await currentSubscription();
+ if (subscription) {
+ const response = await sendSubscription("DELETE", {
+ endpoint: subscription.endpoint
+ });
+ // Keep the browser on when its row could not be deleted.
+ if (!response.ok) {
+ throw new Error(`DELETE returned ${response.status}`);
+ }
+ await subscription.unsubscribe();
+ }
+ rememberBrowserNotifications(false);
+ setState("off");
+ }, t`Failed to disable browser notifications`),
+ [run, t]
+ );
+
+ return { state, busy, turnOn, turnOff };
+}
diff --git a/apps/erp/app/modules/account/account.models.ts b/apps/erp/app/modules/account/account.models.ts
index 6d812f249f..d0276355ba 100644
--- a/apps/erp/app/modules/account/account.models.ts
+++ b/apps/erp/app/modules/account/account.models.ts
@@ -13,6 +13,21 @@ export const notificationPreferenceValidator = z.object({
enabled: z.enum(["true", "false"])
});
+// The browser's PushSubscription.toJSON(), plus the endpoint it replaces when
+// the service worker re-subscribes after a pushsubscriptionchange.
+export const pushSubscriptionValidator = z.object({
+ endpoint: z.string().url(),
+ keys: z.object({
+ p256dh: z.string().min(1),
+ auth: z.string().min(1)
+ }),
+ oldEndpoint: z.string().url().optional()
+});
+
+export const pushSubscriptionEndpointValidator = z.object({
+ endpoint: z.string().url()
+});
+
export const onboardingUserValidator = z.object({
firstName: z.string().min(1, { message: "First name is required" }),
lastName: z.string().min(1, { message: "Last name is required" }),
diff --git a/apps/erp/app/modules/account/account.service.ts b/apps/erp/app/modules/account/account.service.ts
index b65bd7f960..711ce968bf 100644
--- a/apps/erp/app/modules/account/account.service.ts
+++ b/apps/erp/app/modules/account/account.service.ts
@@ -3,6 +3,8 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import type { Database } from "@carbon/database";
+import type { NotificationPreferenceChannel } from "@carbon/notifications";
+import { datetime } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { sanitize } from "~/utils/supabase";
@@ -55,7 +57,7 @@ export async function upsertNotificationPreference(
userId: string;
companyId: string;
topic: string;
- channel: "email" | "slack";
+ channel: NotificationPreferenceChannel;
enabled: boolean;
}
) {
@@ -68,6 +70,68 @@ export async function upsertNotificationPreference(
);
}
+/** Reads this browser's push subscription for the user. */
+export async function getPushSubscription(
+ client: SupabaseClient<Database>,
+ args: { userId: string; endpoint: string }
+) {
+ return client
+ .from("pushSubscription")
+ .select("id")
+ .eq("userId", args.userId)
+ .eq("endpoint", args.endpoint)
+ .maybeSingle();
+}
+
+/** Saves this browser's push subscription for the user. One row per browser;
+ * companyId is the company it was enabled from. */
+export async function upsertPushSubscription(
+ client: SupabaseClient<Database>,
+ subscription: {
+ userId: string;
+ companyId: string;
+ endpoint: string;
+ p256dh: string;
+ auth: string;
+ userAgent: string | null;
+ }
+) {
+ return client
+ .from("pushSubscription")
+ .upsert(
+ { ...subscription, updatedAt: datetime.timestamp() },
+ { onConflict: "endpoint" }
+ )
+ .select("id")
+ .single();
+}
+
+/** Removes every user's push subscription for a browser endpoint, or every
+ * user's but one with `exceptUserId`. Pass the service-role client: RLS shows
+ * a user only their own rows. */
+export async function deleteBrowserPushSubscriptions(
+ client: SupabaseClient<Database>,
+ args: { endpoint: string; exceptUserId?: string }
+) {
+ const query = client
+ .from("pushSubscription")
+ .delete()
+ .eq("endpoint", args.endpoint);
+ return args.exceptUserId ? query.neq("userId", args.exceptUserId) : query;
+}
+
+/** Removes this browser's push subscription for the user. */
+export async function deletePushSubscription(
+ client: SupabaseClient<Database>,
+ args: { userId: string; endpoint: string }
+) {
+ return client
+ .from("pushSubscription")
+ .delete()
+ .eq("userId", args.userId)
+ .eq("endpoint", args.endpoint);
+}
+
/** @mcp delete */
export async function deleteUserAttributeValue(
client: SupabaseClient<Database>,
diff --git a/apps/erp/app/modules/items/items.server.test.ts b/apps/erp/app/modules/items/items.server.test.ts
index 29a93d78c0..0ebba6b621 100644
--- a/apps/erp/app/modules/items/items.server.test.ts
+++ b/apps/erp/app/modules/items/items.server.test.ts
@@ -71,8 +71,9 @@ const MAX_ROWS = 1000;
// Stands in for the two list reads the batch guard makes. Supabase builders are
// thenables, so the chain resolves on await without a terminal method. Each
-// read is answered from the ids its own `in` filter carries and truncated at
-// MAX_ROWS, so a guard that stopped batching visibly drops rows.
+// read is answered from the ids its own `in` filter carries, sliced to the
+// `range` page fetchAllByIds asks for and truncated at MAX_ROWS, so a guard
+// that stopped batching or paging visibly drops rows.
function fakeListClient(
rows: { item?: Row[]; changeOrder?: Row[] },
errors: { item?: boolean; changeOrder?: boolean } = {}
@@ -82,6 +83,7 @@ function fakeListClient(
const failed = errors[table as keyof typeof errors] === true;
const all = rows[table as keyof typeof rows] ?? [];
let requested: string[] | null = null;
+ let page: [number, number] | null = null;
const builder = {
select: () => builder,
in: (_column: string, ids: string[]) => {
@@ -89,6 +91,11 @@ function fakeListClient(
return builder;
},
eq: () => builder,
+ order: () => builder,
+ range: (from: number, to: number) => {
+ page = [from, to];
+ return builder;
+ },
then: (
resolve: (value: {
data: Row[] | null;
@@ -102,6 +109,7 @@ function fakeListClient(
.filter(
(row) => !requested || requested.includes(row?.id as string)
)
+ .slice(page?.[0] ?? 0, page ? page[1] + 1 : undefined)
.slice(0, MAX_ROWS),
error: failed ? { message: `failed to read ${table}` } : null
})
diff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.ts
index d44299f46a..3e3457808c 100644
--- a/apps/erp/app/modules/items/items.server.ts
+++ b/apps/erp/app/modules/items/items.server.ts
@@ -4,13 +4,12 @@
import { error } from "@carbon/auth";
import { flash } from "@carbon/auth/session.server";
-import type { Database } from "@carbon/database";
+import { type Database, fetchAllByIds } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { oncePerRead } from "@carbon/logger/middleware.server";
import { NotificationEvent } from "@carbon/notifications";
-import { chunkArray } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { data } from "react-router";
import {
@@ -767,25 +766,9 @@ export type UnreleasedChangeOrderItem = {
changeOrderReadableId: string;
};
-// PostgREST caps a response at `max_rows` (1000) and an `in` filter rides in the
-// URL, so both reads walk their ids in batches. Truncating either one would drop
-// an item from the answer, and a missing row reads as "no change order holds it".
-const CHANGE_ORDER_ID_BATCH_SIZE = 500;
-
-async function readIdsInBatches<T>(
- ids: string[],
- read: (
- batch: string[]
- ) => PromiseLike<{ data: T[] | null; error: unknown | null }>
-): Promise<{ data: T[]; error: unknown | null }> {
- const rows: T[] = [];
- for (const batch of chunkArray(ids, CHANGE_ORDER_ID_BATCH_SIZE)) {
- const result = await read(batch);
- if (result.error) return { data: [], error: result.error };
- rows.push(...(result.data ?? []));
- }
- return { data: rows, error: null };
-}
+// Both reads go through fetchAllByIds: an `in` filter rides in the URL and a
+// response stops at PostgREST's row cap. Truncating either one would drop an
+// item from the answer, and a missing row reads as "no change order holds it".
// Two queries per batch of ids — the bulk item update can carry a whole table
// selection.
@@ -799,12 +782,13 @@ export async function getUnreleasedChangeOrderItems(
): Promise<{ data: UnreleasedChangeOrderItem[]; error: string | null }> {
if (args.itemIds.length === 0) return { data: [], error: null };
- const items = await readIdsInBatches(args.itemIds, (batch) =>
+ const items = await fetchAllByIds(args.itemIds, (batch) =>
client
.from("item")
.select("id, readableIdWithRevision, changeOrderId")
.in("id", batch)
.eq("companyId", args.companyId)
+ .order("id")
);
if (items.error) {
@@ -824,7 +808,7 @@ export async function getUnreleasedChangeOrderItems(
);
if (owned.length === 0) return { data: [], error: null };
- const changeOrders = await readIdsInBatches(
+ const changeOrders = await fetchAllByIds(
[...new Set(owned.map((item) => item.changeOrderId))],
(batch) =>
client
@@ -832,6 +816,7 @@ export async function getUnreleasedChangeOrderItems(
.select("id, changeOrderId, status")
.in("id", batch)
.eq("companyId", args.companyId)
+ .order("id")
);
if (changeOrders.error) {
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 469f2f6618..9fd5f328f5 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -3,7 +3,11 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import type { Database, Json } from "@carbon/database";
-import { fetchAllFromTable, fetchAllRecords } from "@carbon/database";
+import {
+ fetchAllByIds,
+ fetchAllFromTable,
+ fetchAllRecords
+} from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";
@@ -2945,29 +2949,6 @@ export async function updateJobBatchNumber(
.select("id, readableId");
}
-// An `in` filter rides in the request URL and a response stops at PostgREST's
-// row cap, so a read keyed by an id list walks the ids in groups and pages each
-// group. A read cut short either way would say "nothing there" for the rest.
-const IN_FILTER_BATCH_SIZE = 100;
-
-async function fetchAllByIds<T extends object>(
- ids: string[],
- buildQuery: (batch: string[]) => {
- range(
- from: number,
- to: number
- ): PromiseLike<{ data: T[] | null; error: PostgrestError | null }>;
- }
-): Promise<{ data: T[] | null; error: PostgrestError | null }> {
- const rows: T[] = [];
- for (const batch of chunkArray(ids, IN_FILTER_BATCH_SIZE)) {
- const result = await fetchAllRecords(() => buildQuery(batch));
- if (result.error) return { data: null, error: result.error };
- rows.push(...result.data);
- }
- return { data: rows, error: null };
-}
-
export type JobReleaseReadiness = {
jobs: {
id: string;
diff --git a/apps/erp/app/routes/api+/push-subscription.ts b/apps/erp/app/routes/api+/push-subscription.ts
new file mode 100644
index 0000000000..986e09262f
--- /dev/null
+++ b/apps/erp/app/routes/api+/push-subscription.ts
@@ -0,0 +1,193 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { pushEndpointCookie } from "@carbon/auth/session.server";
+import { isPushConfigured } from "@carbon/env/push.server";
+import { getLogger } from "@carbon/logger";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ deleteBrowserPushSubscriptions,
+ deletePushSubscription,
+ getPushSubscription,
+ pushSubscriptionEndpointValidator,
+ pushSubscriptionValidator,
+ upsertPushSubscription
+} from "~/modules/account";
+
+const logger = getLogger("erp", "push-subscription");
+
+// The carbon-push cookie names this browser's endpoint, so signing out
+// (clearAuthCookies in @carbon/auth) can delete its rows.
+const rememberEndpoint = async (endpoint: string) => ({
+ "Set-Cookie": await pushEndpointCookie.serialize(endpoint)
+});
+
+// GET ?endpoint= — are browser notifications on in this browser for the
+// signed-in user? Read-only: opening a page never claims the browser.
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+
+ if (!isPushConfigured()) return { enabled: false };
+
+ const parsed = pushSubscriptionEndpointValidator.safeParse({
+ endpoint: new URL(request.url).searchParams.get("endpoint")
+ });
+ if (!parsed.success) {
+ return data({ error: "Invalid subscription" }, { status: 400 });
+ }
+
+ const subscription = await getPushSubscription(client, {
+ userId,
+ endpoint: parsed.data.endpoint
+ });
+ if (subscription.error) {
+ logger.error("Failed to read push subscription", {
+ companyId,
+ error: subscription.error
+ });
+ return data({ error: subscription.error.message }, { status: 500 });
+ }
+ if (!subscription.data) return { enabled: false };
+
+ // Re-set the cookie: a subscription saved before the cookie existed must
+ // still end at sign-out.
+ return data(
+ { enabled: true },
+ { headers: await rememberEndpoint(parsed.data.endpoint) }
+ );
+}
+
+// This browser's Web Push subscription for the signed-in user.
+// PUT saves it (also from push-worker.js after a pushsubscriptionchange),
+// DELETE removes it.
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+
+ if (!isPushConfigured()) {
+ return data({ error: "Push is not configured" }, { status: 404 });
+ }
+
+ const body = await request.json().catch(() => null);
+
+ switch (request.method) {
+ case "PUT": {
+ const parsed = pushSubscriptionValidator.safeParse(body);
+ if (!parsed.success) {
+ return data({ error: "Invalid subscription" }, { status: 400 });
+ }
+ const { endpoint, keys, oldEndpoint } = parsed.data;
+
+ // This browser's previous endpoint, from the signed cookie. A browser
+ // that lost its subscription (permission reset, worker removed) makes a
+ // new one with no oldEndpoint to send, and its old row would otherwise
+ // wait for a failed push. Signed, so it only ever names this browser.
+ const remembered = await pushEndpointCookie.parse(
+ request.headers.get("Cookie")
+ );
+ const previousEndpoint =
+ typeof remembered === "string" &&
+ remembered &&
+ remembered !== endpoint &&
+ remembered !== oldEndpoint
+ ? remembered
+ : null;
+
+ // Independent of each other, so they run together: the endpoint this
+ // browser rotated away from, the one the cookie remembers, and other
+ // users' rows for this browser. One browser has one endpoint, and only
+ // the user signed in may own it; a previous user's row would otherwise
+ // block the upsert.
+ const [removed, forgotten, handedOver] = await Promise.all([
+ oldEndpoint
+ ? deletePushSubscription(client, { userId, endpoint: oldEndpoint })
+ : Promise.resolve({ error: null }),
+ previousEndpoint
+ ? deleteBrowserPushSubscriptions(getCarbonServiceRole(), {
+ endpoint: previousEndpoint
+ })
+ : Promise.resolve({ error: null }),
+ deleteBrowserPushSubscriptions(getCarbonServiceRole(), {
+ endpoint,
+ exceptUserId: userId
+ })
+ ]);
+ // Best effort: the first push to a dead row (404 / 410) removes it too.
+ if (forgotten.error) {
+ logger.error(
+ "Failed to remove this browser's previous push subscription",
+ {
+ companyId,
+ error: forgotten.error
+ }
+ );
+ }
+ if (removed.error) {
+ logger.error("Failed to remove the rotated push subscription", {
+ companyId,
+ error: removed.error
+ });
+ return data({ error: removed.error.message }, { status: 500 });
+ }
+ if (handedOver.error) {
+ logger.error("Failed to remove other users' push subscriptions", {
+ companyId,
+ error: handedOver.error
+ });
+ return data({ error: handedOver.error.message }, { status: 500 });
+ }
+
+ const saved = await upsertPushSubscription(client, {
+ userId,
+ companyId,
+ endpoint,
+ p256dh: keys.p256dh,
+ auth: keys.auth,
+ userAgent: request.headers.get("user-agent")
+ });
+ if (saved.error) {
+ logger.error("Failed to save push subscription", {
+ companyId,
+ error: saved.error
+ });
+ return data({ error: saved.error.message }, { status: 500 });
+ }
+ return data(
+ { id: saved.data.id },
+ { headers: await rememberEndpoint(endpoint) }
+ );
+ }
+
+ case "DELETE": {
+ const parsed = pushSubscriptionEndpointValidator.safeParse(body);
+ if (!parsed.success) {
+ return data({ error: "Invalid subscription" }, { status: 400 });
+ }
+ const removed = await deletePushSubscription(client, {
+ userId,
+ endpoint: parsed.data.endpoint
+ });
+ if (removed.error) {
+ logger.error("Failed to delete push subscription", {
+ companyId,
+ error: removed.error
+ });
+ return data({ error: removed.error.message }, { status: 500 });
+ }
+ return data(
+ { ok: true },
+ {
+ headers: {
+ "Set-Cookie": await pushEndpointCookie.serialize("", { maxAge: 0 })
+ }
+ }
+ );
+ }
+
+ default:
+ return data({ error: "Method not allowed" }, { status: 405 });
+ }
+}
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index 80b2e0eea1..05425e0074 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -23,6 +23,7 @@ import {
import { isApprovalRequired } from "@carbon/ee/approvals.server";
import { isAuditLogEnabled } from "@carbon/ee/audit.server";
import { getPlan } from "@carbon/ee/plan.server";
+import { getVapidDetails } from "@carbon/env/push.server";
import { getLogger } from "@carbon/logger";
import { getImplementationCheckStates } from "@carbon/onboarding/server";
import type { PrintingSettings } from "@carbon/printing";
@@ -325,6 +326,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
groups: groups.data ?? [],
permissions: claims?.permissions,
plan,
+ // Null hides the bell's "Enable browser notifications" row: the
+ // deployment has no push keys (no SESSION_SECRET).
+ pushPublicKey: getVapidDetails()?.publicKey ?? null,
role: claims?.role,
user: user.data,
modulePreferences: modulePreferences.data ?? [],
diff --git a/apps/erp/app/routes/x+/account+/notifications.tsx b/apps/erp/app/routes/x+/account+/notifications.tsx
index 4aa4e28d24..2fa7ebe59c 100644
--- a/apps/erp/app/routes/x+/account+/notifications.tsx
+++ b/apps/erp/app/routes/x+/account+/notifications.tsx
@@ -7,6 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { companyHasFeature } from "@carbon/ee/plan.server";
+import { getVapidDetails } from "@carbon/env/push.server";
import { validationError, validator } from "@carbon/form";
import {
getNotificationTopicChannels,
@@ -16,11 +17,13 @@ import {
USER_FACING_NOTIFICATION_TOPICS
} from "@carbon/notifications";
import {
+ Button,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
+ HStack,
Switch,
VStack
} from "@carbon/react";
@@ -28,6 +31,7 @@ import { msg } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, useFetchers, useLoaderData, useSubmit } from "react-router";
+import { usePushSubscription } from "~/hooks/usePushSubscription";
import {
getNotificationPreferences,
notificationPreferenceValidator,
@@ -35,6 +39,7 @@ import {
} from "~/modules/account";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
+import { dismissBrowserNotificationsPrompt } from "~/utils/push";
export const handle: Handle = {
breadcrumb: msg`Notifications`,
@@ -59,10 +64,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
companyHasFeature(client, companyId, { feature: "EMAIL_NOTIFICATIONS" })
]);
+ const pushKeys = getVapidDetails();
+
return {
preferences: preferences.data ?? [],
slackActive: slackIntegration.data?.active ?? false,
- emailPlanEnabled
+ emailPlanEnabled,
+ // Null hides every push control: the deployment has no push keys (no
+ // SESSION_SECRET).
+ push: pushKeys ? { publicKey: pushKeys.publicKey } : null
};
}
@@ -100,8 +110,9 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function AccountNotifications() {
- const { preferences, slackActive, emailPlanEnabled } =
+ const { preferences, slackActive, emailPlanEnabled, push } =
useLoaderData<typeof loader>();
+ const device = usePushSubscription({ publicKey: push?.publicKey ?? null });
const submit = useSubmit();
const fetchers = useFetchers();
const { t } = useLingui();
@@ -164,6 +175,68 @@ export default function AccountNotifications() {
return (
<VStack spacing={4} className="pb-6">
+ {push && (
+ <Card>
+ <CardHeader>
+ <HStack className="justify-between">
+ <div>
+ <CardTitle>
+ <Trans>Browser notifications</Trans>
+ </CardTitle>
+ <CardDescription>
+ {device.state === "off" && (
+ <Trans>Get your Carbon notifications as they happen.</Trans>
+ )}
+ {device.state === "on" && (
+ <Trans>
+ Browser notifications are on for this browser.
+ </Trans>
+ )}
+ {device.state === "denied" && (
+ <Trans>
+ Notifications are blocked for Carbon in this
+ browser&apos;s site settings.
+ </Trans>
+ )}
+ {device.state === "unsupported" && (
+ <Trans>
+ This browser does not support push notifications. On
+ iPhone or iPad, add Carbon to the Home Screen first.
+ </Trans>
+ )}
+ </CardDescription>
+ </div>
+ {device.state === "off" && (
+ <Button
+ type="button"
+ variant="primary"
+ onClick={device.turnOn}
+ isDisabled={device.busy}
+ isLoading={device.busy}
+ >
+ <Trans>Enable</Trans>
+ </Button>
+ )}
+ {device.state === "on" && (
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={async () => {
+ // Off for this browser, for everyone: the bell stops
+ // offering it too — but only once it is really off.
+ if (await device.turnOff()) {
+ dismissBrowserNotificationsPrompt({ permanently: true });
+ }
+ }}
+ isDisabled={device.busy}
+ >
+ <Trans>Disable</Trans>
+ </Button>
+ )}
+ </HStack>
+ </CardHeader>
+ </Card>
+ )}
<Card>
<CardHeader>
<CardTitle>
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index de1c57b445..b518a5f8cd 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -259,6 +259,7 @@ export const path = {
purchasesReportLines: `${api}/accounting/purchase-lines`,
purchasingKpi: (key: string) =>
generatePath(`${api}/purchasing/kpi/${key}`),
+ pushSubscription: `${api}/push-subscription`,
qualityKpi: (key: string) => generatePath(`${api}/quality/kpi/${key}`),
quoteBillOfMaterials: (
methodId: string,
diff --git a/apps/erp/app/utils/push.test.ts b/apps/erp/app/utils/push.test.ts
new file mode 100644
index 0000000000..7595e82aae
--- /dev/null
+++ b/apps/erp/app/utils/push.test.ts
@@ -0,0 +1,102 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { parseAbsolute } from "@internationalized/date";
+import { describe, expect, it } from "vitest";
+import {
+ hasApplicationServerKey,
+ isPromptSnoozed,
+ nextPromptDismissal,
+ PROMPT_SNOOZE_DAYS,
+ parsePromptDismissal,
+ restoreStep,
+ urlBase64ToUint8Array
+} from "./push";
+
+describe("urlBase64ToUint8Array", () => {
+ it("decodes an unpadded key", () => {
+ expect([...urlBase64ToUint8Array("AQID")]).toEqual([1, 2, 3]);
+ });
+
+ it("maps the url-safe alphabet and restores the padding", () => {
+ expect([...urlBase64ToUint8Array("-_8")]).toEqual([251, 255]);
+ });
+});
+
+describe("browser notifications prompt", () => {
+ const at = parseAbsolute("2026-10-08T10:00:00Z", "UTC");
+
+ it("asks when it was never dismissed", () => {
+ expect(isPromptSnoozed(parsePromptDismissal(null), at)).toBe(false);
+ });
+
+ it("hides for the snooze period after the first Not now", () => {
+ const first = nextPromptDismissal(parsePromptDismissal(null), { at });
+ expect(
+ isPromptSnoozed(first, at.add({ days: PROMPT_SNOOZE_DAYS - 1 }))
+ ).toBe(true);
+ expect(
+ isPromptSnoozed(first, at.add({ days: PROMPT_SNOOZE_DAYS + 1 }))
+ ).toBe(false);
+ });
+
+ it("hides for good after the second Not now", () => {
+ const first = nextPromptDismissal(parsePromptDismissal(null), { at });
+ const second = nextPromptDismissal(first, { at });
+ expect(isPromptSnoozed(second, at.add({ years: 2 }))).toBe(true);
+ });
+
+ it("hides for good after a Disable in settings", () => {
+ const disabled = nextPromptDismissal(parsePromptDismissal(null), {
+ at,
+ permanently: true
+ });
+ expect(isPromptSnoozed(disabled, at.add({ years: 2 }))).toBe(true);
+ });
+
+ it("treats a malformed stored value as never dismissed", () => {
+ expect(parsePromptDismissal("not json")).toEqual({ count: 0, until: null });
+ expect(parsePromptDismissal('{"count":"x"}')).toEqual({
+ count: 0,
+ until: null
+ });
+ });
+});
+
+describe("restoreStep", () => {
+ it("remembers a browser the signed-in user already owns", () => {
+ expect(
+ restoreStep({ ownedBySignedInUser: true, browserEnabled: false })
+ ).toBe("remember");
+ });
+
+ it("saves an enabled browser for the next user to sign in", () => {
+ expect(
+ restoreStep({ ownedBySignedInUser: false, browserEnabled: true })
+ ).toBe("save");
+ });
+
+ it("leaves a browser nobody enabled to the bell's prompt", () => {
+ expect(
+ restoreStep({ ownedBySignedInUser: false, browserEnabled: false })
+ ).toBe("skip");
+ });
+});
+
+describe("hasApplicationServerKey", () => {
+ const key = (bytes: number[]) => new Uint8Array(bytes).buffer;
+
+ it("matches a subscription made with the current key", () => {
+ expect(hasApplicationServerKey(key([1, 2, 3]), "AQID")).toBe(true);
+ });
+
+ it("rejects a subscription made with another key", () => {
+ expect(hasApplicationServerKey(key([1, 2, 4]), "AQID")).toBe(false);
+ expect(hasApplicationServerKey(key([1, 2]), "AQID")).toBe(false);
+ });
+
+ it("rejects a subscription with no key", () => {
+ expect(hasApplicationServerKey(null, "AQID")).toBe(false);
+ });
+});
diff --git a/apps/erp/app/utils/push.ts b/apps/erp/app/utils/push.ts
new file mode 100644
index 0000000000..938ded6b79
--- /dev/null
+++ b/apps/erp/app/utils/push.ts
@@ -0,0 +1,160 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import {
+ now,
+ parseAbsolute,
+ type ZonedDateTime
+} from "@internationalized/date";
+
+// Can this browser receive Web Push at all? (iOS only inside a Home Screen app.)
+export function supportsPush() {
+ return (
+ typeof window !== "undefined" &&
+ "serviceWorker" in navigator &&
+ "PushManager" in window &&
+ "Notification" in window
+ );
+}
+
+// localStorage throws in private mode or when storage is disabled; both
+// settings below then read as unset, which only means the bell asks again.
+function readStorage(key: string) {
+ try {
+ return window.localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+function writeStorage(key: string, value: string | null) {
+ try {
+ if (value === null) window.localStorage.removeItem(key);
+ else window.localStorage.setItem(key, value);
+ } catch {
+ // see readStorage
+ }
+}
+
+// The VAPID public key arrives base64url-encoded; pushManager.subscribe()
+// wants the raw bytes.
+export function urlBase64ToUint8Array(base64Url: string) {
+ const padding = "=".repeat((4 - (base64Url.length % 4)) % 4);
+ const base64 = (base64Url + padding).replace(/-/g, "+").replace(/_/g, "/");
+ const raw = atob(base64);
+ const bytes = new Uint8Array(raw.length);
+ for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
+ return bytes;
+}
+
+// The bell's "Enable browser notifications" row. "Not now" hides it for
+// PROMPT_SNOOZE_DAYS in this browser; the second "Not now", or disabling
+// browser notifications in settings, hides it for good. Per browser, like
+// the setting it offers.
+export const PROMPT_SNOOZE_DAYS = 30;
+const PROMPT_MAX_DISMISSALS = 2;
+
+export type PromptDismissal = { count: number; until: string | null };
+
+const NO_DISMISSAL: PromptDismissal = { count: 0, until: null };
+
+const PROMPT_STORAGE_KEY = "browserNotificationsPrompt";
+
+export function parsePromptDismissal(raw: string | null): PromptDismissal {
+ if (!raw) return NO_DISMISSAL;
+ try {
+ const value = JSON.parse(raw) as Partial<PromptDismissal>;
+ return {
+ count: typeof value.count === "number" ? value.count : 0,
+ until: typeof value.until === "string" ? value.until : null
+ };
+ } catch {
+ return NO_DISMISSAL;
+ }
+}
+
+export function isPromptSnoozed(
+ dismissal: PromptDismissal,
+ at: ZonedDateTime = now("UTC")
+) {
+ if (dismissal.count >= PROMPT_MAX_DISMISSALS) return true;
+ if (!dismissal.until) return false;
+ try {
+ return at.compare(parseAbsolute(dismissal.until, "UTC")) < 0;
+ } catch {
+ return false;
+ }
+}
+
+export function nextPromptDismissal(
+ previous: PromptDismissal,
+ { permanently = false, at = now("UTC") } = {}
+): PromptDismissal {
+ return {
+ count: permanently ? PROMPT_MAX_DISMISSALS : previous.count + 1,
+ until: at.add({ days: PROMPT_SNOOZE_DAYS }).toAbsoluteString()
+ };
+}
+
+export function readPromptDismissal(): PromptDismissal {
+ return parsePromptDismissal(readStorage(PROMPT_STORAGE_KEY));
+}
+
+export function dismissBrowserNotificationsPrompt(options?: {
+ permanently?: boolean;
+}) {
+ const next = nextPromptDismissal(readPromptDismissal(), options);
+ writeStorage(PROMPT_STORAGE_KEY, JSON.stringify(next));
+}
+
+// Browser notifications are a setting of the browser, not of a user: once
+// enabled here, whoever is signed in gets their own notifications. Signing
+// out deletes the server row (so the previous user's pushes stop at once);
+// the next sign-in saves the browser again for the new user. Disable turns
+// it off for this browser, for everyone.
+const ENABLED_STORAGE_KEY = "browserNotificationsEnabled";
+
+export function rememberBrowserNotifications(on: boolean) {
+ writeStorage(ENABLED_STORAGE_KEY, on ? "1" : null);
+}
+
+export function areBrowserNotificationsEnabled() {
+ return readStorage(ENABLED_STORAGE_KEY) === "1";
+}
+
+// What a page load does about this browser's notifications for the user
+// signed in now (useRestoreBrowserNotifications):
+// - "remember": the user already owns the row — mark the browser enabled, so
+// the next user to sign in gets theirs too, and save the row again so its
+// updatedAt shows a live session.
+// - "save": the browser is enabled but this user has no row (sign-out
+// deleted the previous one) — save it for them, with no prompt.
+// - "skip": nobody enabled notifications here; the bell row asks.
+export type RestoreStep = "remember" | "save" | "skip";
+
+export function restoreStep({
+ ownedBySignedInUser,
+ browserEnabled
+}: {
+ ownedBySignedInUser: boolean;
+ browserEnabled: boolean;
+}): RestoreStep {
+ if (ownedBySignedInUser) return "remember";
+ return browserEnabled ? "save" : "skip";
+}
+
+// Was this subscription made with the deployment's current VAPID key? A
+// subscription is bound to the key it was created with: after a key change
+// every push to it fails (403), and pushManager.subscribe() refuses a new key
+// while it exists. Such a subscription must be replaced, not re-saved.
+export function hasApplicationServerKey(
+ subscriptionKey: ArrayBuffer | null | undefined,
+ publicKey: string
+) {
+ if (!subscriptionKey) return false;
+ const current = urlBase64ToUint8Array(publicKey);
+ const stored = new Uint8Array(subscriptionKey);
+ if (stored.length !== current.length) return false;
+ return stored.every((byte, index) => byte === current[index]);
+}
diff --git a/apps/erp/public/push-worker.js b/apps/erp/public/push-worker.js
new file mode 100644
index 0000000000..8abbd1e076
--- /dev/null
+++ b/apps/erp/public/push-worker.js
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Web Push for Carbon: shows the notification, opens its link on click, and
+// re-registers a subscription the browser rotated. No fetch handler — this
+// worker caches nothing.
+
+// Nothing is cached, so a new version can take over at once instead of
+// waiting for every Carbon tab to close.
+self.addEventListener("install", () => self.skipWaiting());
+self.addEventListener("activate", (event) => {
+ event.waitUntil(self.clients.claim());
+});
+
+self.addEventListener("push", (event) => {
+ let payload = {};
+ try {
+ payload = event.data ? event.data.json() : {};
+ } catch {
+ payload = { body: event.data ? event.data.text() : "" };
+ }
+ const title = payload.title || "Carbon";
+ event.waitUntil(
+ (async () => {
+ // The browser hands `tag` to the OS as the notification's identifier,
+ // and macOS replaces a notification with the same identifier silently —
+ // no banner, `renotify` notwithstanding. So the tag never reaches
+ // showNotification: older notifications about the same thing are
+ // closed here, and the new one gets a fresh identifier and alerts.
+ if (payload.tag) {
+ const shown = await self.registration.getNotifications();
+ for (const notification of shown) {
+ if (notification.data?.tag === payload.tag) notification.close();
+ }
+ }
+ await self.registration.showNotification(title, {
+ body: payload.body || "",
+ icon: "/carbon-mark-dark.png",
+ data: { url: payload.url || "/", tag: payload.tag }
+ });
+ })()
+ );
+});
+
+self.addEventListener("notificationclick", (event) => {
+ event.notification.close();
+ const url = event.notification.data?.url || "/";
+ event.waitUntil(
+ (async () => {
+ // Only tabs this worker controls: navigate() rejects for any other (one
+ // opened before the worker was installed, or hard-reloaded), and the
+ // rejection would end the click with nothing opened.
+ const windows = await self.clients.matchAll({ type: "window" });
+ const target = new URL(url, self.location.origin);
+ const tab = windows.find(
+ (client) => new URL(client.url).origin === target.origin
+ );
+ if (tab) {
+ try {
+ // Focus first: the click allows focusing a window only briefly.
+ await tab.focus();
+ await tab.navigate(target.href);
+ return;
+ } catch {
+ // fall through to a new window
+ }
+ }
+ await self.clients.openWindow(target.href);
+ })()
+ );
+});
+
+self.addEventListener("pushsubscriptionchange", (event) => {
+ event.waitUntil(
+ (async () => {
+ // Both subscriptions are nullable (Push API): Chromium can hand over a
+ // usable newSubscription with no oldSubscription. Save whatever
+ // replacement exists; subscribe only when there is none and the old
+ // key is known.
+ const old = event.oldSubscription;
+ const key = old?.options?.applicationServerKey;
+ const next =
+ event.newSubscription ||
+ (await self.registration.pushManager.getSubscription()) ||
+ (key
+ ? await self.registration.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: key
+ })
+ : null);
+ if (!next) return;
+ await fetch("/api/push-subscription", {
+ method: "PUT",
+ credentials: "same-origin",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ ...next.toJSON(),
+ ...(old ? { oldEndpoint: old.endpoint } : {})
+ })
+ });
+ })()
+ );
+});
diff --git a/apps/erp/public/serviceWorker.js b/apps/erp/public/serviceWorker.js
deleted file mode 100644
index 1d9a5947a8..0000000000
--- a/apps/erp/public/serviceWorker.js
+++ /dev/null
@@ -1,35 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
-// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-
-self.addEventListener("fetch", (event) => {
- let url = new URL(event.request.url);
- let method = event.request.method;
-
- // any non GET request is ignored
- if (method.toLowerCase() !== "get") return;
-
- // If the request is for the favicons, fonts, or the built files (which are hashed in the name)
- if (
- url.pathname.includes("logo") ||
- url.pathname.includes("storage/v1/object/public/avatars")
- ) {
- event.respondWith(
- // we will open the assets cache
- caches.open("assets").then(async (cache) => {
- // if the request is cached we will use the cache
- let cacheResponse = await cache.match(event.request);
- if (cacheResponse) return cacheResponse;
-
- // if it's not cached we will run the fetch, cache it and return it
- // this way the next time this asset it's needed it will load from the cache
- let fetchResponse = await fetch(event.request);
- cache.put(event.request, fetchResponse.clone());
-
- return fetchResponse;
- })
- );
- }
-
- return;
-});
diff --git a/docs/content/docs/platform/self-hosting/environment-variables.mdx b/docs/content/docs/platform/self-hosting/environment-variables.mdx
index 67cd7260db..35992c0fd0 100644
--- a/docs/content/docs/platform/self-hosting/environment-variables.mdx
+++ b/docs/content/docs/platform/self-hosting/environment-variables.mdx
@@ -35,7 +35,7 @@ Carbon's single Postgres database. The first four are required and crash boot if
## Auth & sessions
<EnvVars>
-<EnvVar name="SESSION_SECRET" type="string" required>Signs the session cookie.</EnvVar>
+<EnvVar name="SESSION_SECRET" type="string" required>Signs the session cookie. Carbon also derives its Web Push keys from it, so changing it makes each user's browser notifications re-subscribe on their next visit.</EnvVar>
<EnvVar name="SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID" type="string">Google OAuth client id, when `google` is in `AUTH_PROVIDERS`.</EnvVar>
<EnvVar name="SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_SECRET" type="string">Google OAuth client secret.</EnvVar>
<EnvVar name="SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID" type="string">Azure OAuth client id, when `azure` is enabled.</EnvVar>
diff --git a/docs/content/docs/reference/account.mdx b/docs/content/docs/reference/account.mdx
index 1ecf50610f..4c711252bc 100644
--- a/docs/content/docs/reference/account.mdx
+++ b/docs/content/docs/reference/account.mdx
@@ -31,7 +31,7 @@ A passkey is tied to a device. Register a second passkey to retain access if the
## Notification preferences
-**Account → Notifications** contains topic-by-channel preferences. In-app notifications are always delivered. The toggles control email and, when connected, Slack. Each topic and channel is enabled by default; turn off a switch to opt out of that combination. See [notifications](/docs/reference/notifications) for notification triggers and channel availability.
+**Account → Notifications** contains topic-by-channel preferences. In-app notifications are always delivered. The toggles control email and, when connected, Slack. Each topic and channel is enabled by default; turn off a switch to opt out of that combination. The **Browser notifications** card enables or disables browser push for the current browser; like in-app, it has no per-topic switch. See [notifications](/docs/reference/notifications) for notification triggers and channel availability.
## Theme, language, and attributes
@@ -60,4 +60,7 @@ The per-user language preference exists in the account model, but the picker isn
### The Slack or Email notification column is missing
Slack's column needs the integration connected. Email preferences are stored regardless but only take effect when the plan includes `EMAIL_NOTIFICATIONS`.
+
+### The Browser notifications card is missing
+The deployment's Web Push keys are derived from `SESSION_SECRET` (`getVapidDetails`, `@carbon/env/push.server`), so every deployment has them and the loader returns the public key. A browser without the Push API shows "not supported" instead of the **Enable** button. The subscription is one `pushSubscription` row per browser endpoint, owned by the signed-in user (`api+/push-subscription.ts`); `clearAuthCookies` (`@carbon/auth`) deletes it on sign-out through the signed `carbon-push` cookie.
</AgentContext>
diff --git a/docs/content/docs/reference/notifications.mdx b/docs/content/docs/reference/notifications.mdx
index 6d06677c55..7b40b07b29 100644
--- a/docs/content/docs/reference/notifications.mdx
+++ b/docs/content/docs/reference/notifications.mdx
@@ -1,9 +1,9 @@
---
title: Notifications
-description: Assignments, approvals, expirations, and reminders reach the right people over in-app, email, and Slack, with per-user channel opt-outs by topic.
+description: Assignments, approvals, expirations, and reminders reach the right people over in-app, email, Slack, and browser push, with per-user opt-outs by topic for email and Slack.
---
-A <Term>notification</Term> alerts one person to an assignment, approval, expiration, or other event. Carbon can deliver it through the **in-app inbox** (the bell in the top bar), **email**, and **Slack**. In-app delivery is always enabled; users can mute email and Slack by topic. Carbon does not notify users about their own actions.
+A <Term>notification</Term> alerts one person to an assignment, approval, expiration, or other event. Carbon can deliver it through the **in-app inbox** (the bell in the top bar), **email**, **Slack**, and **browser push**. In-app delivery is always enabled, and browser push mirrors it in every browser where it is enabled; users can mute email and Slack by topic. Carbon does not notify users about their own actions.
## What raises a notification
@@ -28,20 +28,25 @@ The channels differ in what they require:
<Field name="In-app">The bell in the top bar. **Always written**, for every recipient, on every event — it cannot be turned off.</Field>
<Field name="Email">A per-notification email with a **View** button. Sent only when the company's plan includes email notifications.</Field>
<Field name="Slack">A DM in the connected workspace. Needs an active Slack integration *and* a matching Slack account for the recipient.</Field>
+ <Field name="Browser">An operating-system notification on each browser where the user enabled browser notifications, even when Carbon is closed. Clicking it opens the record. Sent for every notification, like the in-app inbox: browser push has no per-topic switch. Needs no setup: the Web Push keys are derived from the deployment's `SESSION_SECRET`.</Field>
</FieldTable>
<Callout type="warn">
-Email is **plan-gated**: companies without the `EMAIL_NOTIFICATIONS` plan feature skip the email channel entirely, regardless of the per-user switch. Slack has no plan gate — it only needs the integration. See [licensing](/docs/platform/licensing).
+Email is **plan-gated**: companies without the `EMAIL_NOTIFICATIONS` plan feature skip the email channel entirely, regardless of the per-user switch. Slack and browser push have no plan gate. See [licensing](/docs/platform/licensing).
</Callout>
## Muting a topic
-Each user controls their own email and Slack delivery under **Account → Notifications**: a grid with one row per topic, a column per channel, a switch in each cell. In-app has no switch.
+Each user controls their own email and Slack delivery under **Account → Notifications**: a grid with one row per topic, a column per channel, a switch in each cell. In-app and browser push have no switch.
<Screenshot label="Account → Notifications preferences grid: topic rows, Email and Slack columns, switches per cell" caption="Muting is per topic, per channel, per company. The in-app inbox always gets everything." />
Each channel is enabled by default. Turning off a switch mutes only that topic and channel for the current company. For example, muting Purchasing in Slack does not mute Purchasing email, other Slack topics, or notifications in another company. The Slack column appears only when Slack is connected. The email column always appears and indicates when the plan does not support delivery.
+## Browser notifications
+
+Above the grid, the **Browser notifications** card turns them on for the browser you are using. Click **Enable** and allow the browser's prompt. The bell also offers **Enable browser notifications** at the top of the inbox until you enable them or choose **Not now** (it asks once more after 30 days, then stops). Browser notifications are a setting of the browser: once enabled on a computer or phone, whoever signs in there gets their own notifications, from every company they belong to. Signing out — or being signed out — stops the previous user's notifications at once, so a shared computer never shows someone else's. **Disable** turns them off for that browser, for everyone who uses it. On iPhone or iPad, add Carbon to the Home Screen first — Safari offers push only to Home Screen apps.
+
## Who receives an expiration or reminder
Assignment events notify the assignee. Time-driven events derive recipients as follows: an expired gauge calibration notifies the user list in [calibration](/docs/reference/calibration) settings, an automatically created dispatch notifies all employees at its work center, and the weekly training reminder sends each person a digest. Carbon has no general notification-group entity; only calibration expiration uses a configured list.
@@ -70,7 +75,7 @@ The bell opens the inbox: recent notifications newest-first with an unread count
<AgentContext>
## Internals and troubleshooting
-Every notification starts as a `carbon/notify` event with a specific type; the full set is `NotificationEvent` (`packages/notifications/src/index.ts:7`), destinations are `NotificationDestination` (`index.ts:108`), and the fixed event→topic mapping is `getNotificationTopic` (`index.ts:114`). The topic string is stored on every row (`notification.topic`) and is what a user's opt-out row matches on. Preferences are opt-out rows, one per `(user, company, channel, topic)` in `notificationPreference`; no row means enabled. The fan-out always adds the in-app destination (`notify.ts:210`), drops muted recipients from email/Slack lists (`notify.ts:302`), and skips email entirely without the `EMAIL_NOTIFICATIONS` plan feature (`notify.ts:509`). Most assignments default to email + Slack; callers can override channels per dispatch.
+Every notification starts as a `carbon/notify` event with a specific type; the full set is `NotificationEvent`, destinations are `NotificationDestination`, and the fixed event→topic mapping is `getNotificationTopic` (all in `packages/notifications/src/index.ts`). The topic string is stored on every row (`notification.topic`) and is what a user's opt-out row matches on. Preferences are opt-out rows, one per `(user, company, channel, topic)` in `notificationPreference`; no row means enabled. The fan-out (`packages/jobs/src/inngest/functions/notifications/notify.ts`) always adds the in-app destination, drops muted recipients from the email and Slack lists (step `filter-recipients-by-preference`), and skips email entirely without the `EMAIL_NOTIFICATIONS` plan feature. Browser push mirrors in-app: every recipient of the in-app row gets one `carbon/send-push` per browser where notifications are enabled, with no topic filter. Most assignments default to email + Slack; callers can override channels per dispatch.
### Why am I not getting email notifications?
Email is plan-gated — check the company's plan first. Then confirm the topic isn't muted for email and that the specific event defaults to the email channel.
@@ -79,10 +84,13 @@ Email is plan-gated — check the company's plan first. Then confirm the topic i
Slack needs an active integration and a matching Slack account for the recipient; users without one are silently skipped. Also check the topic's Slack mute.
### I muted a topic but still get in-app notifications
-Expected: in-app is always written and cannot be turned off. Mutes affect only email and Slack.
+Expected: in-app is always written and cannot be turned off, and browser push follows it. Mutes affect only email and Slack.
### I turned a channel on but it still doesn't deliver
-Enabling a channel removes the mute but does not bypass its prerequisites: the plan feature for email, or the integration and account mapping for Slack.
+Enabling a channel removes the mute but does not bypass its prerequisites: the plan feature for email, the integration and account mapping for Slack. Browser push has no mute; it needs browser notifications enabled in that browser.
+
+### I enabled browser notifications but nothing arrives
+Carbon does not notify you about your own actions, so a job you assign to yourself sends nothing. Test with a second account. If the card says notifications are blocked, allow them for Carbon in the browser's site settings. If Carbon sends a notification but no banner appears, the operating system is holding it: on macOS, open **System Settings → Notifications**, set your browser's alert style to **Banners** or **Alerts**, and turn off any Focus mode (Do Not Disturb, Work). Held notifications still wait in Notification Center.
### I did something myself and got no notification
The sender is filtered out of the recipient list. Self-assignments notify nobody.
diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.md
index 579f4d4de2..752613d227 100644
--- a/packages/auth/AGENTS.md
+++ b/packages/auth/AGENTS.md
@@ -41,7 +41,7 @@ pnpm --filter @carbon/auth test
| `.` (index) | Env re-exports, Supabase client factories, `getClaims`, cookie/http/result utils, validators |
| `./auth.server` | `requirePermissions`, API key auth (30s Redis-cached `getApiKeyRecord` + `bustApiKeyCache`, from `services/api-key.server.ts`), `hashApiKey`, `hashOAuthSecret` |
| `./mfa.server` | TOTP MFA: `enrollTotpFactor`, `verifyTotpChallenge`, `unenrollTotpFactor`, `userHasVerifiedTotpFactor` (Redis-cached), `adminDeleteTotpFactors` |
-| `./session.server` | `createCookieSessionStorage`, `requireAuthSession` (incl. MFA re-check), `destroyAuthSession`, session refresh, pending-MFA session + `completeMfaChallenge` |
+| `./session.server` | `createCookieSessionStorage`, `requireAuthSession` (incl. MFA re-check), `destroyAuthSession`, session refresh, pending-MFA session + `completeMfaChallenge`; `pushEndpointCookie` (signed `carbon-push`, this browser's Web Push endpoint) — `clearAuthCookies` deletes that endpoint's `pushSubscription` rows on every same-site sign-out (a cross-site navigation skips it, per the GET-write rule) |
| `./company.server` | Company switching, `updateCompanySession`; the cached plan lookups `getCompanyPlanId` and `isCarbonOwnedCompany` (Redis 5 min, a missing plan row cached as `""`) |
| `./users.server` | `getUserClaims`, deactivation flows, cache invalidation |
| `./passkey.server` | WebAuthn/passkey registration and authentication |
diff --git a/packages/auth/src/services/session.server.ts b/packages/auth/src/services/session.server.ts
index dc40b6c905..34f98703c4 100644
--- a/packages/auth/src/services/session.server.ts
+++ b/packages/auth/src/services/session.server.ts
@@ -3,9 +3,14 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { redis } from "@carbon/kv";
+import { getLogger } from "@carbon/logger";
import { Edition, redirect } from "@carbon/utils";
import type { AuthSession as SupabaseAuthSession } from "@supabase/supabase-js";
-import { createCookieSessionStorage } from "react-router";
+import {
+ type CookieOptions,
+ createCookie,
+ createCookieSessionStorage
+} from "react-router";
import {
CarbonEdition,
@@ -18,6 +23,7 @@ import {
SESSION_MAX_AGE,
SESSION_SECRET
} from "../config/env";
+import { isCrossSiteNavigation } from "../lib/security";
import type { AuthSession, Result } from "../types";
import { getCookieDomain } from "../utils/cookie";
import { getCurrentPath, isGet, makeRedirectToFromHere } from "../utils/http";
@@ -55,18 +61,66 @@ export const isTestEdition = CarbonEdition === Edition.Test;
const cookieDomain = isTestEdition ? undefined : getCookieDomain(DOMAIN);
+// Shared by every signed cookie in this file.
+const signedCookieOptions: CookieOptions = {
+ httpOnly: true,
+ path: "/",
+ sameSite: isTestEdition ? "none" : "lax",
+ secrets: [SESSION_SECRET!],
+ secure: isTestEdition || !!cookieDomain,
+ domain: cookieDomain
+};
+
const sessionStorage = createCookieSessionStorage({
- cookie: {
- name: "carbon",
- httpOnly: true,
- path: "/",
- sameSite: isTestEdition ? "none" : "lax",
- secrets: [SESSION_SECRET!],
- secure: isTestEdition || !!cookieDomain,
- domain: cookieDomain
- }
+ cookie: { name: "carbon", ...signedCookieOptions }
+});
+
+const log = getLogger("auth", "session");
+
+// The Web Push endpoint of this browser, set when the user enables browser
+// notifications. Signing out (clearAuthCookies) deletes the endpoint's
+// subscription rows, so a browser nobody is signed into stops receiving
+// pushes — whichever path signed it out.
+export const pushEndpointCookie = createCookie("carbon-push", {
+ ...signedCookieOptions,
+ // Browsers cap a cookie's lifetime at 400 days.
+ maxAge: 60 * 60 * 24 * 400
});
+async function endBrowserPush(request: Request) {
+ const endpoint = await pushEndpointCookie.parse(
+ request.headers.get("Cookie")
+ );
+ if (typeof endpoint !== "string" || !endpoint) return null;
+ // The login loader clears a dead session's cookies on a GET. A top-level
+ // navigation from another site must not write (packages/auth/AGENTS.md), so
+ // it leaves the rows and the cookie alone: they lapse once no session
+ // refreshes them (notify skips stale rows), or the next sign-in replaces
+ // them.
+ if (isCrossSiteNavigation(request.headers)) return null;
+ // Best effort: signing out must still succeed and clear its cookies, even
+ // when the client cannot be built (missing Supabase URL) or the delete
+ // fails. The next 404/410 from the push service cleans the row up.
+ try {
+ // Loaded here, not at module load: importing the session module must not
+ // build a Supabase client.
+ const { getCarbonServiceRole } = await import(
+ "../lib/supabase/client.server"
+ );
+ // Every user's row for this browser: after sign-out nobody is signed in.
+ const { error } = await getCarbonServiceRole()
+ .from("pushSubscription")
+ .delete()
+ .eq("endpoint", endpoint);
+ if (error) {
+ log.error("Failed to delete push subscriptions on sign-out", { error });
+ }
+ } catch (error) {
+ log.error("Failed to delete push subscriptions on sign-out", { error });
+ }
+ return pushEndpointCookie.serialize("", { maxAge: 0 });
+}
+
export async function setAuthSession(
request: Request,
{
@@ -212,9 +266,11 @@ export async function clearAuthCookies(request: Request) {
const session = await getSession(request);
const sessionCookie = await sessionStorage.destroySession(session);
const companyIdCookie = setCompanyId(null);
+ const pushCookie = await endBrowserPush(request);
return [
["Set-Cookie", sessionCookie] as [string, string],
- ["Set-Cookie", companyIdCookie] as [string, string]
+ ["Set-Cookie", companyIdCookie] as [string, string],
+ ...(pushCookie ? [["Set-Cookie", pushCookie] as [string, string]] : [])
];
}
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index 2198cdc187..ac6e799f85 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -12,6 +12,13 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti
- `scriptRun` is a deliberate exception to the table conventions above: no `companyId`, no
composite PK, SELECT-only RLS. It is the per-database ledger of one-off scripts that
`ci/src/migrations.ts` runs after `supabase db push` — see `scripts/one-off/README.md`.
+- **User-owned preference rows** are the other deliberate exception: `notificationPreference`,
+ `userModulePreference` and `pushSubscription` use an `xid()` id, a single-column
+ `PRIMARY KEY ("id")` and no `createdBy`/`updatedBy`. A row belongs to one user and only that
+ user writes it, so the audit columns would always repeat `userId`. They keep `companyId`
+ (FK, `ON DELETE CASCADE`) for tenant attribution and the RLS rule `owner("userId")` +
+ `member("companyId")`. `pushSubscription` is unique per browser `endpoint`, not per company
+ (one browser, one owner); see `.ai/specs/2026-10-08-web-push-notifications.md`.
It is intentionally NOT tenant-scoped so `selectWipeableTables` (company-backup.ts) cannot
select it and a company restore cannot erase it. A migration landing in this package is
also what triggers those scripts to deploy (`.github/workflows/supabase.yml` only fires on
@@ -21,6 +28,10 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti
the first concurrently. `fetchAllRecords` is the same pager over a query FACTORY (`() => builder`)
— a factory, because supabase-js builders are mutable, so concurrent awaits on one builder all
fetch whichever `.range()` was set last.
+- Use `fetchAllByIds(ids, (batch) => query.in(col, batch).order(...))` for a read keyed by an id
+ list that can grow with the data. It sends 100 ids per request, because `.in()` writes every id
+ into the URL and the gateway rejects a long request line (HTTP 431). It pages each group with
+ `fetchAllRecords`, and one failed group fails the whole read.
## Ask First
@@ -55,7 +66,7 @@ pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/h
| Subpath | Provides |
|---------|----------|
-| `.` (index) | `Database` type, `fetchAllFromTable`, `fetchAllRecords` (takes a query factory), `fetchRecordsInBatches`, `journalReference` (`journalLine.documentLineReference` values). The `datetime` derivation API lives in `@carbon/utils` |
+| `.` (index) | `Database` type, `fetchAllFromTable`, `fetchAllRecords` (takes a query factory), `fetchAllByIds` (100 ids per `.in()` request, each group paged), `fetchRecordsInBatches`, `journalReference` (`journalLine.documentLineReference` values). The `datetime` derivation API lives in `@carbon/utils` |
| `./client` | Node-only. `Kysely`, `KyselyDatabase`, `getPostgresClient`, and `getProcessPool()` (one shared pool per process — never create another, never end it outside an exiting script); registers the NUMERIC → `Number` and DATE → `YYYY-MM-DD` type parsers at module load (see `.claude/rules/numeric-precision.md`) |
| `./methods` | Make-method helpers shared by get-method and `@carbon/planning` (`getJobMethodTree`, `getQuoteMethodTree`, `traverseJobMethod`, `calculateQuoteLinePrices`, …) |
| `./job-quantities-engine` | `computeJobQuantities` / `flattenJobQuantityTree` — the pure job-quantity cascade behind the `recalculate` server function |
diff --git a/packages/database/src/authz/manifest.ts b/packages/database/src/authz/manifest.ts
index 066625b90e..a0798f4b76 100644
--- a/packages/database/src/authz/manifest.ts
+++ b/packages/database/src/authz/manifest.ts
@@ -1137,6 +1137,15 @@ export const manifest = {
update: false,
delete: false
}),
+ pushSubscription: policies({
+ select: and(owner("userId"), member("companyId")),
+ insert: and(owner("userId"), member("companyId")),
+ update: {
+ using: owner("userId"),
+ check: and(owner("userId"), member("companyId"))
+ },
+ delete: and(owner("userId"), member("companyId"))
+ }),
qualityDocument: company("quality"),
qualityDocumentStep: company("production"),
quote: company("sales", { read: "sales_view" }),
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 69a874d437..39de922aa0 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -8439,6 +8439,177 @@ export default {
tags: ["purchaseInvoicePriceChange"]
}
},
+ "/pushSubscription": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.userId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.endpoint"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.p256dh"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.auth"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.userAgent"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/pushSubscription"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["pushSubscription"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.pushSubscription"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["pushSubscription"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.userId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.endpoint"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.p256dh"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.auth"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.userAgent"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.updatedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["pushSubscription"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.userId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.endpoint"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.p256dh"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.auth"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.userAgent"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pushSubscription.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.pushSubscription"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["pushSubscription"]
+ }
+ },
"/makeMethod": {
get: {
parameters: [
@@ -118185,6 +118356,65 @@ export default {
},
type: "object"
},
+ pushSubscription: {
+ required: [
+ "id",
+ "userId",
+ "companyId",
+ "endpoint",
+ "p256dh",
+ "auth",
+ "createdAt",
+ "updatedAt"
+ ],
+ properties: {
+ id: {
+ default: "public.xid()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ userId: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ endpoint: {
+ format: "text",
+ type: "string"
+ },
+ p256dh: {
+ format: "text",
+ type: "string"
+ },
+ auth: {
+ format: "text",
+ type: "string"
+ },
+ userAgent: {
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
makeMethod: {
required: [
"id",
@@ -167014,6 +167244,69 @@ export default {
in: "query",
type: "string"
},
+ "body.pushSubscription": {
+ name: "pushSubscription",
+ description: "pushSubscription",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/pushSubscription"
+ }
+ },
+ "rowFilter.pushSubscription.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.pushSubscription.userId": {
+ name: "userId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.pushSubscription.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.pushSubscription.endpoint": {
+ name: "endpoint",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.pushSubscription.p256dh": {
+ name: "p256dh",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.pushSubscription.auth": {
+ name: "auth",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.pushSubscription.userAgent": {
+ name: "userAgent",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.pushSubscription.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.pushSubscription.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.makeMethod": {
name: "makeMethod",
description: "makeMethod",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 8a81d9eb40..5b2ef93155 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -49117,6 +49117,106 @@ export type Database = {
}
]
}
+ pushSubscription: {
+ Row: {
+ auth: string
+ companyId: string
+ createdAt: string
+ endpoint: string
+ id: string
+ p256dh: string
+ updatedAt: string
+ userAgent: string | null
+ userId: string
+ }
+ Insert: {
+ auth: string
+ companyId: string
+ createdAt?: string
+ endpoint: string
+ id?: string
+ p256dh: string
+ updatedAt?: string
+ userAgent?: string | null
+ userId: string
+ }
+ Update: {
+ auth?: string
+ companyId?: string
+ createdAt?: string
+ endpoint?: string
+ id?: string
+ p256dh?: string
+ updatedAt?: string
+ userAgent?: string | null
+ userId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "pushSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "pushSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "pushSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "pushSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "pushSubscription_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "pushSubscription_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "pushSubscription_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "pushSubscription_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "pushSubscription_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ }
+ ]
+ }
qualityDocument: {
Row: {
assignee: string | null
diff --git a/packages/database/src/utils.test.ts b/packages/database/src/utils.test.ts
index d2b7b29740..82678ee683 100644
--- a/packages/database/src/utils.test.ts
+++ b/packages/database/src/utils.test.ts
@@ -3,7 +3,7 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { describe, expect, it } from "vitest";
-import { fetchAllRecords } from "./utils";
+import { fetchAllByIds, fetchAllRecords } from "./utils";
// `fetchAllRecords` is the only thing standing between a >1000-row read and a
// silently truncated one, and the local dev stack does not enforce `max_rows`, so
@@ -129,3 +129,64 @@ describe("fetchAllRecords", () => {
expect(result.error?.message).toContain("exceeded");
});
});
+
+// `fetchAllByIds` guards the other limit: `.in()` writes every id into the URL,
+// and the gateway rejects a request line it cannot buffer (HTTP 431). Each
+// group must stay small, every group must be paged past the row cap, and a
+// failed group must fail the read instead of dropping its rows.
+describe("fetchAllByIds", () => {
+ /** Rows per id; the factory records each group it is asked for. */
+ function fakeById(rowsPerId: number, opts: { failGroup?: number } = {}) {
+ const groups: string[][] = [];
+ const build = (batch: string[]) => {
+ groups.push(batch);
+ const group = groups.length - 1;
+ const rows = batch.flatMap((id) =>
+ Array.from({ length: rowsPerId }, (_, i) => ({ id: `${id}:${i}` }))
+ );
+ return {
+ range: (from: number, to: number) =>
+ Promise.resolve(
+ opts.failGroup === group
+ ? { data: null, error: { message: "boom" } }
+ : { data: rows.slice(from, to + 1), error: null }
+ )
+ } as any;
+ };
+ return { build, groups };
+ }
+
+ const idsOf = (n: number) => Array.from({ length: n }, (_, i) => `u${i}`);
+
+ it("sends at most 100 ids per request and returns every row", async () => {
+ const { build, groups } = fakeById(3);
+ const result = await fetchAllByIds(idsOf(250), build);
+
+ expect(groups.map((g) => g.length)).toEqual([100, 100, 50]);
+ expect(result.error).toBeNull();
+ expect(result.data).toHaveLength(750);
+ });
+
+ it("pages a group whose rows pass the row cap", async () => {
+ const { build } = fakeById(30);
+ const result = await fetchAllByIds(idsOf(100), build);
+
+ expect(result.data).toHaveLength(3000);
+ });
+
+ it("makes no request for an empty list", async () => {
+ const { build, groups } = fakeById(1);
+ const result = await fetchAllByIds([], build);
+
+ expect(groups).toEqual([]);
+ expect(result.data).toEqual([]);
+ });
+
+ it("fails the whole read when one group fails", async () => {
+ const { build } = fakeById(1, { failGroup: 1 });
+ const result = await fetchAllByIds(idsOf(250), build);
+
+ expect(result.data).toBeNull();
+ expect(result.error?.message).toBe("boom");
+ });
+});
diff --git a/packages/database/src/utils.ts b/packages/database/src/utils.ts
index 80adea7d8f..3a30fd0afe 100644
--- a/packages/database/src/utils.ts
+++ b/packages/database/src/utils.ts
@@ -152,6 +152,31 @@ export async function fetchAllRecords<T extends object>(
};
}
+// Ids per request. `.in()` writes every id into the URL, and the gateway
+// rejects a request line it cannot buffer (HTTP 431); 100 ids is about 3 kB.
+const IN_FILTER_BATCH_SIZE = 100;
+
+/**
+ * Reads every row for an id list. Walks the ids in groups of 100, so each
+ * `.in()` fits in the request URL, and pages each group past the row cap with
+ * `fetchAllRecords`. The factory gets one group and must order its query, so
+ * the pages of a group are stable. A failed group fails the whole read: a
+ * partial list would read as "no rows" for the ids it dropped.
+ */
+export async function fetchAllByIds<T extends object>(
+ ids: readonly string[],
+ buildQuery: (batch: string[]) => PageQuery<T>
+): Promise<PaginatedResult<T>> {
+ const rows: T[] = [];
+ for (let start = 0; start < ids.length; start += IN_FILTER_BATCH_SIZE) {
+ const batch = ids.slice(start, start + IN_FILTER_BATCH_SIZE);
+ const result = await fetchAllRecords(() => buildQuery(batch));
+ if (result.error) return { data: null, count: null, error: result.error };
+ rows.push(...result.data);
+ }
+ return { data: rows, count: rows.length, error: null };
+}
+
/**
* Helper function for simple table queries that need all records
*/
diff --git a/packages/database/supabase/migrations/20261008002726_push-subscription.sql b/packages/database/supabase/migrations/20261008002726_push-subscription.sql
new file mode 100644
index 0000000000..82c67495ec
--- /dev/null
+++ b/packages/database/supabase/migrations/20261008002726_push-subscription.sql
@@ -0,0 +1,29 @@
+-- One browser push subscription per endpoint, owned by the user signed into
+-- that browser. A user-owned row, shaped like "notificationPreference": xid()
+-- id, no audit columns. "companyId" is the company the user enabled it from
+-- (tenant attribution and the RLS check); the user gets the push of every
+-- company they belong to.
+CREATE TABLE IF NOT EXISTS "pushSubscription" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "userId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "endpoint" TEXT NOT NULL,
+ "p256dh" TEXT NOT NULL,
+ "auth" TEXT NOT NULL,
+ "userAgent" TEXT,
+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT now(),
+ "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT now(),
+
+ CONSTRAINT "pushSubscription_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "pushSubscription_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "pushSubscription_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "pushSubscription_endpoint_key" UNIQUE ("endpoint")
+);
+
+ALTER TABLE "pushSubscription" ENABLE ROW LEVEL SECURITY;
+
+CREATE INDEX IF NOT EXISTS "pushSubscription_userId_companyId_idx"
+ ON "pushSubscription" ("userId", "companyId");
+
+CREATE INDEX IF NOT EXISTS "pushSubscription_companyId_idx"
+ ON "pushSubscription" ("companyId");
diff --git a/packages/database/supabase/migrations/20261008002814_push-subscription.sql b/packages/database/supabase/migrations/20261008002814_push-subscription.sql
new file mode 100644
index 0000000000..06ffa0b748
--- /dev/null
+++ b/packages/database/supabase/migrations/20261008002814_push-subscription.sql
@@ -0,0 +1,18 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+-- pushSubscription
+DO $authz$
+DECLARE p record;
+BEGIN
+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'pushSubscription' LOOP
+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'pushSubscription');
+ END LOOP;
+END
+$authz$;
+ALTER TABLE public."pushSubscription" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "SELECT" ON "public"."pushSubscription" FOR SELECT USING (("userId" = ((SELECT auth.uid()))::text AND "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text)));
+CREATE POLICY "INSERT" ON "public"."pushSubscription" FOR INSERT WITH CHECK (("userId" = ((SELECT auth.uid()))::text AND "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text)));
+CREATE POLICY "UPDATE" ON "public"."pushSubscription" FOR UPDATE USING ("userId" = ((SELECT auth.uid()))::text) WITH CHECK (("userId" = ((SELECT auth.uid()))::text AND "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text)));
+CREATE POLICY "DELETE" ON "public"."pushSubscription" FOR DELETE USING (("userId" = ((SELECT auth.uid()))::text AND "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text)));
diff --git a/packages/env/AGENTS.md b/packages/env/AGENTS.md
index b3558dda52..a200aca4db 100644
--- a/packages/env/AGENTS.md
+++ b/packages/env/AGENTS.md
@@ -43,6 +43,7 @@ pnpm --filter @carbon/env test
- **URLs:** `getAppUrl()`, `getMESUrl()`, `getBrowserEnv()`
- **Logging:** `LOG_LEVEL` (optional, non-secret, browser-safe — consumed by `@carbon/logger`)
- **Integrations:** Stripe, SMTP email, Slack, Xero, Jira, OnShape, QuickBooks keys (all optional)
+- **Web Push (`@carbon/env/push.server`, server-only — imports `node:crypto`):** `getVapidDetails()`, `isPushConfigured()`, `deriveVapidDetails(secret, appUrl)`. The VAPID pair is derived from `SESSION_SECRET` by HKDF, so there are no push env vars; keep it out of `src/index.ts`, which the browser imports.
## Cross-References
diff --git a/packages/env/package.json b/packages/env/package.json
index df7d760308..f85600d12a 100644
--- a/packages/env/package.json
+++ b/packages/env/package.json
@@ -4,7 +4,8 @@
"type": "module",
"private": true,
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./push.server": "./src/push.server.ts"
},
"main": "./src/index.ts",
"types": "./src/index.ts",
diff --git a/packages/env/src/push.server.test.ts b/packages/env/src/push.server.test.ts
new file mode 100644
index 0000000000..a0d5b599e9
--- /dev/null
+++ b/packages/env/src/push.server.test.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { createPrivateKey, createPublicKey, sign, verify } from "node:crypto";
+import { describe, expect, it } from "vitest";
+import { deriveVapidDetails } from "./push.server";
+
+const APP_URL = "https://erp.example.com";
+
+describe("deriveVapidDetails", () => {
+ // Every browser subscription is bound to this public key. If this test
+ // fails, every deployment's key changed and every subscription broke — undo
+ // the change to the derivation instead of updating the expected values.
+ // (Cross-checked with `openssl kdf … HKDF` and `openssl ec -pubout`.)
+ it("derives the known pair for a fixed secret", () => {
+ expect(deriveVapidDetails("carbon-known-answer", APP_URL)).toEqual({
+ privateKey: "TzaowWiJUkggIblM6_nQG-FFOwKUK0DEMwADabYUJ8k",
+ publicKey:
+ "BOGuTBaDZtTjy6SHEsFlQYjwb-patTPU0SQrjskAyv52s5tTtSr30p_VxbsM0_WwuMF3qXQTwduI99Alk3WYEmM",
+ subject: APP_URL
+ });
+ });
+
+ it("gives the same pair for the same secret", () => {
+ expect(deriveVapidDetails("secret-a", APP_URL)).toEqual(
+ deriveVapidDetails("secret-a", APP_URL)
+ );
+ });
+
+ it("gives a different pair for a different secret", () => {
+ const a = deriveVapidDetails("secret-a", APP_URL);
+ const b = deriveVapidDetails("secret-b", APP_URL);
+ expect(a.publicKey).not.toBe(b.publicKey);
+ expect(a.privateKey).not.toBe(b.privateKey);
+ });
+
+ it("encodes the keys the way web-push and pushManager.subscribe expect", () => {
+ const { publicKey, privateKey } = deriveVapidDetails("secret-a", APP_URL);
+ const pub = Buffer.from(publicKey, "base64url");
+ expect(pub).toHaveLength(65);
+ expect(pub[0]).toBe(0x04); // uncompressed point
+ expect(Buffer.from(privateKey, "base64url")).toHaveLength(32);
+ });
+
+ it("is a working key pair: what the private key signs, the public key verifies", () => {
+ const { publicKey, privateKey } = deriveVapidDetails("secret-a", APP_URL);
+ const pub = Buffer.from(publicKey, "base64url");
+ const jwk = {
+ crv: "P-256",
+ kty: "EC",
+ x: pub.subarray(1, 33).toString("base64url"),
+ y: pub.subarray(33).toString("base64url")
+ };
+ const message = Buffer.from("vapid");
+ const signature = sign(
+ "sha256",
+ message,
+ createPrivateKey({ format: "jwk", key: { ...jwk, d: privateKey } })
+ );
+ expect(
+ verify(
+ "sha256",
+ message,
+ createPublicKey({ format: "jwk", key: jwk }),
+ signature
+ )
+ ).toBe(true);
+ });
+
+ it("uses an https app URL as the subject, else a mailto:", () => {
+ expect(deriveVapidDetails("s", APP_URL).subject).toBe(APP_URL);
+ expect(deriveVapidDetails("s", "http://localhost:3000").subject).toMatch(
+ /^mailto:/
+ );
+ });
+});
diff --git a/packages/env/src/push.server.ts b/packages/env/src/push.server.ts
new file mode 100644
index 0000000000..6e15ed3f4a
--- /dev/null
+++ b/packages/env/src/push.server.ts
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+/// <reference types="node" />
+import { createECDH, hkdfSync } from "node:crypto";
+import { SUPPORT_EMAIL } from "@carbon/utils";
+import { getAppUrl, SESSION_SECRET } from "./index";
+
+export type VapidDetails = {
+ /** base64url, the 65-byte uncompressed P-256 point the browser subscribes with */
+ publicKey: string;
+ /** base64url, the 32-byte P-256 scalar */
+ privateKey: string;
+ /** Contact for push services: a mailto: or https: URL */
+ subject: string;
+};
+
+// The order of P-256, big-endian. A private key is a scalar in [1, n − 1].
+const P256_ORDER = Buffer.from(
+ "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
+ "hex"
+);
+
+/**
+ * The deployment's Web Push (VAPID) key pair, derived from the secret so
+ * there is nothing to generate or configure. The same secret always gives the
+ * same pair, and it must: every browser subscription is bound to the public
+ * key it was made with.
+ */
+export function deriveVapidDetails(
+ secret: string,
+ appUrl: string
+): VapidDetails {
+ // Push services take an https: URL or a mailto:. A plain-http app URL is
+ // only ever a local stack.
+ const subject = appUrl.startsWith("https://")
+ ? appUrl
+ : `mailto:${SUPPORT_EMAIL}`;
+
+ for (let attempt = 0; ; attempt++) {
+ // Never change the hash, the salt "carbon" or the info label: they ARE the
+ // key. Any change gives every deployment a new pair, and every browser
+ // subscription stops working. push.server.test.ts pins a known answer.
+ const scalar = Buffer.from(
+ hkdfSync("sha256", secret, "carbon", `web-push-vapid/${attempt}`, 32)
+ );
+ // Out of range for about 1 secret in 2^32; the next attempt is just as
+ // deterministic.
+ // Both are 32 bytes big-endian, so byte order is numeric order.
+ const isZero = scalar.every((byte) => byte === 0);
+ if (isZero || Buffer.compare(scalar, P256_ORDER) >= 0) continue;
+
+ const ecdh = createECDH("prime256v1");
+ ecdh.setPrivateKey(scalar);
+ return {
+ privateKey: scalar.toString("base64url"),
+ publicKey: ecdh.getPublicKey().toString("base64url"),
+ subject
+ };
+ }
+}
+
+let cached: VapidDetails | null | undefined;
+
+/**
+ * Null only where SESSION_SECRET is unset (a script run with
+ * SKIP_ENV_VALIDATION); everywhere else push is on. Rotating SESSION_SECRET
+ * rotates the pair: each browser re-subscribes with the new key on its next
+ * visit; until then send-push logs each push the old-key row refuses.
+ */
+export function getVapidDetails(): VapidDetails | null {
+ if (cached === undefined) {
+ cached = SESSION_SECRET
+ ? deriveVapidDetails(SESSION_SECRET, getAppUrl())
+ : null;
+ }
+ return cached;
+}
+
+export function isPushConfigured(): boolean {
+ return getVapidDetails() !== null;
+}
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index c520666ef3..660f1784a2 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -64,6 +64,8 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +
| `recurring-billing` | `0 5 * * *` | The one daily job for every recurring-invoice source: rental agreements and AR contracts. One query finds every company with an Active rental agreement or Active `customerContract`. Per company, as of the company's today, `userId "system"`: a `rental-billing-<id>` step (the `create-rental-invoices` server function), then a `contract-billing-<id>` step (`create-contract-invoices`, same `asOf`); a failed source never skips the other. Then an `automation-candidates-<id>` step (`findInvoicesToAutomate`) reads back every Draft — or Pending, a crashed claim — invoice the job created (`createdBy "system"`) with no hold whose source mode is not Draft Only, so drafts from a failed or retried drafting step are still automated; the drafting steps' results only report this run's planner holds. Per candidate a `post-<id>` step (`postSalesInvoiceUnattended`), a `pdf-<id>` step once it is posted (`attachPostedInvoicePdf` — every posting mode files the invoice PDF under its opportunity, as a manual Post does; the email step reuses that file rather than recording a second), and, by the source's effective mode, an `email-<id>` step (`emailPostedInvoice`, `Post and Email`) or a `stripe-<id>` step (`sendPostedInvoiceViaStripe`, `Post and Send via Stripe`; counts as sent in the digest), all in `src/invoicing/automate-invoice.ts`. Then one "Recurring invoicing" digest per owner (agreement or contract `salesPersonId ?? createdBy`) plus the company's `invoiceNotificationGroup` (`buildRecurringInvoicingDigests`, `src/invoicing/digest.ts`) |
| `invoice-automate` | `carbon/invoice.automate` | Posts one drafted recurring invoice (rental or contract), then emails it under `Post and Email` or sends it through Stripe Connect under `Post and Send via Stripe`; mode from the event or the source's effective mode (`resolveInvoiceAutomation`: `customerContracts.effectiveInvoiceAutomation` when the invoice has a `customerContractId`, else the rental agreement's). Fired by the **Invoice** action of a rental agreement or contract, by Sell to Customer, and by the invoice's Send action (`resend: true` — Stripe when that is the resolved mode, else `Post and Email`). One run per invoice (`concurrency` on `invoiceId`, not shared with the cron's steps). Every step is safe to retry: posting claims only a Draft (a Pending claim is reported as held, never re-claimed), and a send is skipped once `sentAt` is set or a Stripe invoice is linked — but an email that went out before its `sentAt` write failed is recorded as a `sendError`, and a Send then emails it again. `sendPostedInvoiceViaStripe` stamps `sentTo: "Stripe"`, or `sendError` "Stripe is not connected" / "No Stripe customer is linked", and never sends an invoice twice (it checks `sentAt` and the existing Stripe invoice link) |
| `revenue-recognition-proposal` | `0 12 1 * *` | Per company, one step each: proposes a Draft revenue recognition run for the month that just ended on the company's calendar (the `propose-revenue-recognition-run` server function, `userId "system"`), skipped when a run for that period already exists; posting stays human |
+| `notify` | `carbon/notify` (`trigger("notify", …)` from app code) | Resolve the recipients, write the in-app rows, then fan out email, Slack and push. Built for large groups: every read keyed by the recipients goes through `fetchAllByIds`, the `.in()` writes run per `IN_FILTER_CHUNK` (100) ids, inserts per `INSERT_CHUNK` (500) rows, emails render and send per `EMAIL_CHUNK` (20, about 16.9 KB each against Inngest's 512 KB send limit), and Slack and push send per `EVENT_CHUNK` (500) events |
+| `send-push` | `carbon/send-push` (one per `pushSubscription` row, fanned out by `notify` for every notification, like in-app, when `isPushConfigured()`) | Send one Web Push with `web-push`; deletes the row on 404/410, logs a warning and keeps it on 401/403 (another VAPID key, or Apple refusing our token), retries 429/5xx, fails other 4xx (`pushDeliveryOutcome`) |
| `notification-digest` | `carbon/notification-digest.process` (sent by the `notification-digest-sweeper` pg_cron job every 15 min, only when `util.notification_digest_has_work()`) | Roll unread notifications into one digest per user, company and topic |
| `workflow-run-retention` | `carbon/workflow-run-retention.process` (sent by the `workflow-run-retention-sweeper` pg_cron job at 04:00 UTC, only when `util.workflow_run_retention_has_work()`) | Reap stale runs, compact and drop step detail, purge old run headers |
| `embedding-queue` | `carbon/embedding-queue.process` (sent by the 10 s `process-embeddings` pg_cron doorbell while visible messages wait) | Drain the pgmq `embedding_jobs` queue and write embeddings |
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index cfd4c4e056..4ace66adbc 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -7476,6 +7476,7 @@
"oauthClient",
"oauthCode",
"oauthToken",
+ "pushSubscription",
"ssoConnection",
"ssoDomain",
"tableChange",
diff --git a/packages/jobs/package.json b/packages/jobs/package.json
index 2ff6fd0969..ba27e20e20 100644
--- a/packages/jobs/package.json
+++ b/packages/jobs/package.json
@@ -10,10 +10,10 @@
"@carbon/kv": "workspace:*",
"@carbon/lib": "workspace:*",
"@carbon/logger": "workspace:*",
- "@carbon/server-functions": "workspace:*",
"@carbon/notifications": "workspace:*",
"@carbon/planning": "workspace:*",
"@carbon/printing": "workspace:*",
+ "@carbon/server-functions": "workspace:*",
"@carbon/stripe": "workspace:*",
"@carbon/utils": "workspace:*",
"@carbon/viewer": "workspace:*",
@@ -35,12 +35,14 @@
"supabase": "catalog:",
"tsup": "catalog:",
"undici": "^8.10.0",
+ "web-push": "^3.6.7",
"zod": "catalog:"
},
"devDependencies": {
"@carbon/config": "workspace:*",
"@types/pg": "8.15.6",
"@types/react": "catalog:",
+ "@types/web-push": "^3.6.4",
"pg": "8.20.0",
"tsx": "catalog:",
"typescript": "catalog:",
diff --git a/packages/jobs/src/backups/schema.ts b/packages/jobs/src/backups/schema.ts
index d18dde4f57..82c56af6ab 100644
--- a/packages/jobs/src/backups/schema.ts
+++ b/packages/jobs/src/backups/schema.ts
@@ -33,7 +33,11 @@ export const BACKUP_VERSION = 1;
* every operator's PIN. `ssoConnection` / `ssoDomain` are the company's login
* identity — `providerId` and a verified `domain` are unique across ALL
* companies, so a copy collides with the source company or hands its domain to
- * another. `oauthCode` is a live auth code, and dangles without `oauthClient`.)
+ * another. `oauthCode` is a live auth code, and dangles without `oauthClient`.
+ * `pushSubscription` holds a browser's push endpoint and its encryption keys:
+ * a device credential that means nothing in another company, and being secret
+ * keeps an in-place restore from bringing back signed-out browsers or wiping
+ * the current ones.)
*/
export const SECRET_TABLES = [
"apiKey",
@@ -46,7 +50,8 @@ export const SECRET_TABLES = [
"oauthCode",
"oauthToken",
"ssoConnection",
- "ssoDomain"
+ "ssoDomain",
+ "pushSubscription"
];
/**
diff --git a/packages/jobs/src/inngest/functions/notifications/index.ts b/packages/jobs/src/inngest/functions/notifications/index.ts
index dcae945ab1..4cb8eec531 100644
--- a/packages/jobs/src/inngest/functions/notifications/index.ts
+++ b/packages/jobs/src/inngest/functions/notifications/index.ts
@@ -4,4 +4,5 @@
export { notifyFunction } from "./notify";
export { sendEmailFunction } from "./send-email";
+export { sendPushFunction } from "./send-push";
export { sendSlackFunction } from "./send-slack";
diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.ts
index e42507675d..1a908c73ae 100644
--- a/packages/jobs/src/inngest/functions/notifications/notify.ts
+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts
@@ -3,6 +3,7 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { fetchAllByIds } from "@carbon/database";
import { resolveIntegrationSecrets } from "@carbon/ee";
import { emailNotificationsEnabled } from "@carbon/ee/email-notifications.server";
import {
@@ -10,7 +11,13 @@ import {
notifyTaskAssigned
} from "@carbon/ee/notifications";
import { getSlackUserIdByCarbonId } from "@carbon/ee/slack.server";
-import { ERP_URL } from "@carbon/env";
+import {
+ CONTROLLED_ENVIRONMENT,
+ ERP_URL,
+ SESSION_ABSOLUTE_MAX_MS,
+ SESSION_MAX_AGE
+} from "@carbon/env";
+import { isPushConfigured } from "@carbon/env/push.server";
import type { Events } from "@carbon/lib/events";
import {
escapeSlackText,
@@ -20,9 +27,11 @@ import {
isRecurringNotificationEvent,
NotificationDestination,
NotificationEvent,
+ renderInlineLinks,
renderSlackMrkdwn
} from "@carbon/notifications";
-import { datetime } from "@carbon/utils";
+import { chunkArray, datetime } from "@carbon/utils";
+import { now } from "@internationalized/date";
import { render } from "@react-email/components";
import { NonRetriableError } from "inngest";
import { inngest } from "../../client";
@@ -31,6 +40,26 @@ import {
getNotificationContent,
getNotificationEmailComponent
} from "./content";
+import { pushSessionMaxAgeMs, pushSubscriptionCutoff } from "./push-outcome";
+
+// A group notification can have hundreds of recipients. One request, insert
+// or send that carries all of them fails the whole notification, so each is
+// split into chunks of these sizes.
+
+// Ids per `.in()` write: the filter rides in the URL, and the gateway rejects
+// a request line it cannot buffer (HTTP 431). Reads use fetchAllByIds.
+const IN_FILTER_CHUNK = 100;
+
+// Rows per `notification` insert, so one request body stays small.
+const INSERT_CHUNK = 500;
+
+// Emails per render step and per send. One rendered notification email is
+// about 16.9 KB, and Inngest accepts at most 512 KB in one send: 20 × 16.9 KB
+// is about 338 KB, far under a step's 4 MB output limit too.
+const EMAIL_CHUNK = 20;
+
+// Slack and push events per send. Each event is under 1 KB.
+const EVENT_CHUNK = 500;
async function getCompanyIntegrations(
client: ReturnType<typeof getCarbonServiceRole>,
@@ -44,7 +73,8 @@ async function getCompanyIntegrations(
// Per-event default destinations. Callers can override by passing
// `destinations` in the payload; otherwise these defaults apply.
-// InApp is always added separately and cannot be opted out of.
+// InApp is always added separately and cannot be opted out of. Push is not
+// listed here: it follows in-app, so every notification pushes.
const defaultDestinations: Partial<
Record<NotificationEvent, NotificationDestination[]>
> = {
@@ -195,7 +225,9 @@ const defaultDestinations: Partial<
NotificationDestination.Email
],
// In-app only: the outbound sweep re-fires while failures persist, and an
- // email per sweep cycle would be noise.
+ // email per sweep cycle would be noise. Browser push still follows in-app,
+ // so the integration's last editor gets a push every sweep (30 min) until
+ // the failures clear — deliberate: push mirrors the bell exactly.
[NotificationEvent.IntegrationSync]: [NotificationDestination.InApp]
};
@@ -303,12 +335,18 @@ export const notifyFunction = inngest.createFunction(
if (payload.from) ids = ids.filter((id) => id !== payload.from);
ids = [...new Set(ids)];
+ // Every read keyed by the recipients goes through fetchAllByIds: a
+ // group can hold more users than one `.in()` URL or one 1000-row page
+ // carries, and a read cut short would drop recipients without an error.
if (ids.length > 0) {
- const members = await client
- .from("userToCompany")
- .select("userId")
- .eq("companyId", payload.companyId)
- .in("userId", ids);
+ const members = await fetchAllByIds(ids, (batch) =>
+ client
+ .from("userToCompany")
+ .select("userId")
+ .eq("companyId", payload.companyId)
+ .in("userId", batch)
+ .order("userId")
+ );
if (members.error) {
console.error(
"Failed to filter recipients by company membership",
@@ -330,18 +368,28 @@ export const notifyFunction = inngest.createFunction(
const wantsEmail = destinations.includes(NotificationDestination.Email);
const wantsSlack = destinations.includes(NotificationDestination.Slack);
+ // Push mirrors in-app: every notification goes to every browser with
+ // notifications enabled, with no per-topic switch. The push keys come from
+ // SESSION_SECRET, so only a deployment without one has no push channel.
+ const wantsPush = isPushConfigured();
// Per-user channel opt-outs: absence of a row = enabled; enabled=false
// mutes that (topic, channel). In-app delivery is never filtered.
const { emailRecipientIds, slackRecipientIds } =
wantsEmail || wantsSlack
? await step.run("filter-recipients-by-preference", async () => {
- const { data: prefs, error } = await client
- .from("notificationPreference")
- .select("userId, channel, enabled")
- .in("userId", userIds)
- .eq("companyId", payload.companyId)
- .eq("topic", topic);
+ const { data: prefs, error } = await fetchAllByIds(
+ userIds,
+ (batch) =>
+ client
+ .from("notificationPreference")
+ .select("userId, channel, enabled")
+ .in("userId", batch)
+ .eq("companyId", payload.companyId)
+ .eq("topic", topic)
+ .order("userId")
+ .order("channel")
+ );
if (error) {
console.error("Failed to load notification preferences", error);
throw error;
@@ -417,32 +465,35 @@ export const notifyFunction = inngest.createFunction(
if (content.digest) {
const supersededAt = datetime.timestamp();
- const [supersededDigests, supersededFlat] = await Promise.all([
- client
- .from("notification")
- .update({ readAt: supersededAt, seenAt: supersededAt })
- .eq("companyId", payload.companyId)
- .eq("event", NotificationEvent.Digest)
- .eq("payload->>sourceEvent", payload.event)
- .is("readAt", null)
- .in("userId", userIds),
- client
- .from("notification")
- .update({ readAt: supersededAt, seenAt: supersededAt })
- .eq("companyId", payload.companyId)
- .eq("event", payload.event)
- .is("digestedInto", null)
- .is("readAt", null)
- .in("userId", userIds)
- ]);
- const supersedeError =
- supersededDigests.error ?? supersededFlat.error;
- if (supersedeError) {
- console.error(
- "Failed to supersede prior reminder rows",
- supersedeError
- );
- throw supersedeError;
+ // One chunk of recipients at a time: the ids ride in the URL.
+ for (const chunk of chunkArray(userIds, IN_FILTER_CHUNK)) {
+ const [supersededDigests, supersededFlat] = await Promise.all([
+ client
+ .from("notification")
+ .update({ readAt: supersededAt, seenAt: supersededAt })
+ .eq("companyId", payload.companyId)
+ .eq("event", NotificationEvent.Digest)
+ .eq("payload->>sourceEvent", payload.event)
+ .is("readAt", null)
+ .in("userId", chunk),
+ client
+ .from("notification")
+ .update({ readAt: supersededAt, seenAt: supersededAt })
+ .eq("companyId", payload.companyId)
+ .eq("event", payload.event)
+ .is("digestedInto", null)
+ .is("readAt", null)
+ .in("userId", chunk)
+ ]);
+ const supersedeError =
+ supersededDigests.error ?? supersededFlat.error;
+ if (supersedeError) {
+ console.error(
+ "Failed to supersede prior reminder rows",
+ supersedeError
+ );
+ throw supersedeError;
+ }
}
}
@@ -451,57 +502,83 @@ export const notifyFunction = inngest.createFunction(
// DigestNotification UI renders. Single-item digests use the flat path.
if (digestItems && digestItems.length > 1) {
let inserted = 0;
- for (const userId of userIds) {
- const parent = await client
+ // One parent insert per chunk of recipients, then their children,
+ // instead of two round trips per recipient.
+ for (const chunk of chunkArray(userIds, IN_FILTER_CHUNK)) {
+ const parents = await client
.from("notification")
- .insert({
- companyId: payload.companyId,
- event: NotificationEvent.Digest,
- payload: {
- count: digestItems.length,
- description,
+ .insert(
+ chunk.map((userId) => ({
+ companyId: payload.companyId,
event: NotificationEvent.Digest,
- sourceEvent: payload.event,
- topic
- },
- title: description,
- topic,
- userId
- })
- .select("id")
- .single();
- if (parent.error || !parent.data?.id) {
- console.error("Failed to insert digest parent", parent.error);
- throw parent.error ?? new Error("Failed to insert digest parent");
+ payload: {
+ count: digestItems.length,
+ description,
+ event: NotificationEvent.Digest,
+ sourceEvent: payload.event,
+ topic
+ },
+ title: description,
+ topic,
+ userId
+ }))
+ )
+ .select("id, userId");
+ if (parents.error) {
+ console.error("Failed to insert digest parents", parents.error);
+ throw parents.error;
}
+ inserted += parents.data.length;
- const childRows = digestItems.map((item) => ({
- companyId: payload.companyId,
- digestedInto: parent.data.id,
- documentId: item.documentId,
- documentType: payload.documentType ?? null,
- event: payload.event,
- from: payload.from ?? null,
- payload: {
- description: item.description,
+ // Keyed by user, so the order the rows come back in never matters.
+ const parentIdByUser = new Map(
+ parents.data.map((parent) => [parent.userId, parent.id])
+ );
+ const childRows = chunk.flatMap((userId) => {
+ const parentId = parentIdByUser.get(userId);
+ if (!parentId) {
+ const error = new Error(
+ `Failed to insert digest parent for ${userId}`
+ );
+ console.error("Failed to insert digest parent", {
+ companyId: payload.companyId,
+ userId
+ });
+ throw error;
+ }
+ return digestItems.map((item) => ({
+ companyId: payload.companyId,
+ digestedInto: parentId,
documentId: item.documentId,
+ documentType: payload.documentType ?? null,
event: payload.event,
- from: payload.from
- },
- title: item.description,
- topic,
- userId
- }));
-
- const children = await client
- .from("notification")
- .insert(childRows)
- .select("id");
- if (children.error) {
- console.error("Failed to insert digest children", children.error);
- throw children.error;
+ from: payload.from ?? null,
+ payload: {
+ description: item.description,
+ documentId: item.documentId,
+ event: payload.event,
+ from: payload.from
+ },
+ title: item.description,
+ topic,
+ userId
+ }));
+ });
+
+ for (const rows of chunkArray(childRows, INSERT_CHUNK)) {
+ const children = await client
+ .from("notification")
+ .insert(rows)
+ .select("id");
+ if (children.error) {
+ console.error(
+ "Failed to insert digest children",
+ children.error
+ );
+ throw children.error;
+ }
+ inserted += children.data?.length ?? 0;
}
- inserted += 1 + (children.data?.length ?? 0);
}
return { inserted, userIds };
}
@@ -525,15 +602,19 @@ export const notifyFunction = inngest.createFunction(
userId
}));
- const { data, error } = await client
- .from("notification")
- .insert(rows)
- .select("id");
- if (error) {
- console.error("Failed to insert notification rows", error);
- throw error;
+ let inserted = 0;
+ for (const chunk of chunkArray(rows, INSERT_CHUNK)) {
+ const { data, error } = await client
+ .from("notification")
+ .insert(chunk)
+ .select("id");
+ if (error) {
+ console.error("Failed to insert notification rows", error);
+ throw error;
+ }
+ inserted += data?.length ?? 0;
}
- return { inserted: data?.length ?? 0, userIds };
+ return { inserted, userIds };
});
}
@@ -553,48 +634,59 @@ export const notifyFunction = inngest.createFunction(
}
if (emailAllowed && emailRecipientIds.length > 0) {
- const emailEvents = await step.run(
- "resolve-email-recipients",
- async () => {
- const { data: users, error } = await client
- .from("user")
- .select("id, email, fullName")
- .in("id", emailRecipientIds);
- if (error) {
- console.error("Failed to resolve email recipients", error);
- throw error;
- }
+ // The read is its own step, and each chunk of EMAIL_CHUNK recipients is
+ // rendered and sent in steps of its own: one step holding every
+ // recipient's HTML outgrows a step's output and a send's size limit.
+ // These step ids are new on purpose: the single step they replace
+ // stored its output in another shape, and a replay must not read it.
+ const recipients = await step.run("load-email-recipients", async () => {
+ const { data: users, error } = await fetchAllByIds(
+ emailRecipientIds,
+ (batch) =>
+ client
+ .from("user")
+ .select("id, email, fullName")
+ .in("id", batch)
+ .order("id")
+ );
+ if (error) {
+ console.error("Failed to resolve email recipients", error);
+ throw error;
+ }
+ return (users ?? []).filter((u) => u.email);
+ });
- const subject = description;
- const heading = getNotificationEmailHeading(payload.event);
- const ctaLabel = getNotificationEmailCtaLabel(payload.event);
- const ctaUrl = buildNotificationLink(
- payload.event,
- primaryDocumentId,
- payload.companyId,
- payload.documentType
- );
+ const subject = description;
+ const heading = getNotificationEmailHeading(payload.event);
+ const ctaLabel = getNotificationEmailCtaLabel(payload.event);
+ const ctaUrl = buildNotificationLink(
+ payload.event,
+ primaryDocumentId,
+ payload.companyId,
+ payload.documentType
+ );
- const recipients = (users ?? []).filter((u) => u.email);
-
- // Recurring reminders carry delivery tracking; the recurrence
- // period is folded into the tracked id ("ta_1:2026") so each period
- // gets a fresh MAX_NOTIFICATION_DELIVERIES budget, while a plain id
- // (no period) caps permanently.
- const trackedDocumentIds = isRecurringNotificationEvent(payload.event)
- ? (digestItems?.map((item) =>
- item.period
- ? `${item.documentId}:${item.period}`
- : item.documentId
- ) ?? [primaryDocumentId])
- : null;
-
- // Render the template once per recipient because the greeting bakes
- // in the user's name. The template itself is small so this is cheap;
- // if it ever becomes hot we can split into a shared body + per-user
- // greeting Section.
- const events = await Promise.all(
- recipients.map(async (u) => {
+ // Recurring reminders carry delivery tracking; the recurrence
+ // period is folded into the tracked id ("ta_1:2026") so each period
+ // gets a fresh MAX_NOTIFICATION_DELIVERIES budget, while a plain id
+ // (no period) caps permanently.
+ const trackedDocumentIds = isRecurringNotificationEvent(payload.event)
+ ? (digestItems?.map((item) =>
+ item.period ? `${item.documentId}:${item.period}` : item.documentId
+ ) ?? [primaryDocumentId])
+ : null;
+
+ for (const [index, chunk] of chunkArray(
+ recipients,
+ EMAIL_CHUNK
+ ).entries()) {
+ // Render the template once per recipient because the greeting bakes
+ // in the user's name. The template itself is small so this is cheap;
+ // if it ever becomes hot we can split into a shared body + per-user
+ // greeting Section.
+ const emailEvents = await step.run(`render-emails-${index}`, () =>
+ Promise.all(
+ chunk.map(async (u) => {
const html = await render(
getNotificationEmailComponent({
companyId: payload.companyId,
@@ -641,12 +733,9 @@ export const notifyFunction = inngest.createFunction(
name: "carbon/send-email" as const
};
})
- );
- return events;
- }
- );
- if (emailEvents.length > 0) {
- await step.sendEvent("fan-out-emails", emailEvents);
+ )
+ );
+ await step.sendEvent(`fan-out-emails-${index}`, emailEvents);
}
}
@@ -729,8 +818,86 @@ export const notifyFunction = inngest.createFunction(
}
);
- if (slackEvents.length > 0) {
- await step.sendEvent("fan-out-slack", slackEvents);
+ for (const [index, chunk] of chunkArray(
+ slackEvents,
+ EVENT_CHUNK
+ ).entries()) {
+ await step.sendEvent(`fan-out-slack-${index}`, chunk);
+ }
+ }
+
+ // ---- Push fan-out ----
+ // Every recipient of the in-app row, one carbon/send-push per browser row,
+ // so each browser retries on its own. A row belongs to the user, not a
+ // company: recipients are already limited to members of this
+ // notification's company (resolve-recipients), so each user gets the push
+ // of every company they belong to.
+ if (wantsPush) {
+ const pushEvents = await step.run(
+ "resolve-push-subscriptions",
+ async () => {
+ // Skip browsers no session has saved within a session's lifetime:
+ // their session ended without a sign-out.
+ const liveSince = pushSubscriptionCutoff(
+ now("UTC"),
+ pushSessionMaxAgeMs({
+ controlledEnvironment: CONTROLLED_ENVIRONMENT,
+ absoluteMaxMs: SESSION_ABSOLUTE_MAX_MS,
+ cookieMaxAgeSeconds: SESSION_MAX_AGE
+ })
+ );
+ const { data: subscriptions, error } = await fetchAllByIds(
+ userIds,
+ (batch) =>
+ client
+ .from("pushSubscription")
+ .select("id, userId")
+ .in("userId", batch)
+ .gte("updatedAt", liveSince)
+ .order("id")
+ );
+ if (error) {
+ console.error("Failed to load push subscriptions", error);
+ throw error;
+ }
+ const url = buildNotificationLink(
+ payload.event,
+ primaryDocumentId,
+ payload.companyId,
+ payload.documentType
+ );
+ // A workflow notification carries its author's subject as the
+ // description and their message as the "Message" detail; the
+ // generic heading would title every one "Workflow". A system
+ // notification shows no links, so [label](url) keeps its label.
+ const isWorkflow = payload.event === NotificationEvent.Workflow;
+ const title = isWorkflow
+ ? description
+ : getNotificationEmailHeading(payload.event);
+ const body = isWorkflow
+ ? renderInlineLinks(details[0]?.value ?? "", ERP_URL)
+ .map((segment) => segment.text)
+ .join("")
+ : description;
+ return (subscriptions ?? []).map((subscription) => ({
+ data: {
+ body,
+ companyId: payload.companyId,
+ subscriptionId: subscription.id,
+ userId: subscription.userId,
+ tag: `${payload.event}:${primaryDocumentId}`,
+ title,
+ url
+ },
+ name: "carbon/send-push" as const
+ }));
+ }
+ );
+ for (const [index, chunk] of chunkArray(
+ pushEvents,
+ EVENT_CHUNK
+ ).entries()) {
+ await step.sendEvent(`fan-out-push-${index}`, chunk);
}
}
}
diff --git a/packages/jobs/src/inngest/functions/notifications/push-outcome.test.ts b/packages/jobs/src/inngest/functions/notifications/push-outcome.test.ts
new file mode 100644
index 0000000000..92a16daac2
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/notifications/push-outcome.test.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { parseAbsolute } from "@internationalized/date";
+import { describe, expect, it } from "vitest";
+import {
+ pushDeliveryOutcome,
+ pushSessionMaxAgeMs,
+ pushSubscriptionCutoff
+} from "./push-outcome";
+
+describe("pushDeliveryOutcome", () => {
+ it.each([
+ // Refused signature: kept and logged, never deleted (Apple's 403 can mean
+ // our own token, for every Safari row).
+ [401, "rejected"],
+ [403, "rejected"],
+ [404, "gone"],
+ [410, "gone"],
+ [413, "fail"],
+ [429, "retry"],
+ [503, "retry"]
+ ] as const)("maps %i to %s", (status, outcome) => {
+ expect(pushDeliveryOutcome(status)).toBe(outcome);
+ });
+});
+
+describe("pushSessionMaxAgeMs", () => {
+ const limits = {
+ absoluteMaxMs: 12 * 60 * 60 * 1000,
+ cookieMaxAgeSeconds: 7 * 24 * 60 * 60
+ };
+
+ it("uses the absolute session cap in a controlled environment", () => {
+ expect(
+ pushSessionMaxAgeMs({ controlledEnvironment: true, ...limits })
+ ).toBe(12 * 60 * 60 * 1000);
+ });
+
+ it("uses the session cookie's lifetime elsewhere", () => {
+ expect(
+ pushSessionMaxAgeMs({ controlledEnvironment: false, ...limits })
+ ).toBe(7 * 24 * 60 * 60 * 1000);
+ });
+});
+
+describe("pushSubscriptionCutoff", () => {
+ it("is the instant one session lifetime before now", () => {
+ const at = parseAbsolute("2026-10-08T12:00:00Z", "UTC");
+ expect(pushSubscriptionCutoff(at, 12 * 60 * 60 * 1000)).toBe(
+ "2026-10-08T00:00:00.000Z"
+ );
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/notifications/push-outcome.ts b/packages/jobs/src/inngest/functions/notifications/push-outcome.ts
new file mode 100644
index 0000000000..5cb009f60b
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/notifications/push-outcome.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { ZonedDateTime } from "@internationalized/date";
+
+export type PushOutcome = "gone" | "rejected" | "retry" | "fail";
+
+// What a push service's error status means for the subscription row. web-push
+// throws a WebPushError only for a non-2xx response, so a 2xx never gets here.
+// 404 / 410: the subscription is gone for good, so the caller deletes it.
+// 401 / 403: the push service refused our signature. Usually the subscription
+// was made with another VAPID key (WNS answers 401, FCM 403), and the browser
+// replaces it on its next page load. But Apple answers 403 when it rejects the
+// token itself, which hits every Safari row at once, so the caller only logs:
+// deleting would wipe every Safari browser over a problem on our side.
+// 429 / 5xx: transient, so the caller throws and Inngest retries.
+// Any other non-2xx: a bad request that a retry would repeat.
+export function pushDeliveryOutcome(statusCode: number): PushOutcome {
+ if (statusCode === 404 || statusCode === 410) return "gone";
+ if (statusCode === 401 || statusCode === 403) return "rejected";
+ if (statusCode === 429 || statusCode >= 500) return "retry";
+ return "fail";
+}
+
+// A pushSubscription row is live only while a session could still be signed
+// in to its browser. Every page load saves the row again (updatedAt), so a row
+// older than the longest session — 12 h in a controlled environment, the 7-day
+// session cookie elsewhere — belongs to a browser whose session has ended
+// without a sign-out. notify skips it; the next sign-in saves it again.
+export function pushSessionMaxAgeMs({
+ controlledEnvironment,
+ absoluteMaxMs,
+ cookieMaxAgeSeconds
+}: {
+ controlledEnvironment: boolean;
+ absoluteMaxMs: number;
+ cookieMaxAgeSeconds: number;
+}) {
+ return controlledEnvironment ? absoluteMaxMs : cookieMaxAgeSeconds * 1000;
+}
+
+export function pushSubscriptionCutoff(at: ZonedDateTime, maxAgeMs: number) {
+ return at.subtract({ milliseconds: maxAgeMs }).toAbsoluteString();
+}
diff --git a/packages/jobs/src/inngest/functions/notifications/send-push.ts b/packages/jobs/src/inngest/functions/notifications/send-push.ts
new file mode 100644
index 0000000000..7274585627
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/notifications/send-push.ts
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getVapidDetails } from "@carbon/env/push.server";
+import { getLogger } from "@carbon/logger";
+import { NonRetriableError } from "inngest";
+import webpush from "web-push";
+import { inngest } from "../../client";
+import { pushDeliveryOutcome } from "./push-outcome";
+
+const log = getLogger("jobs", "send-push");
+
+// A notification older than a day is old news; the bell still has it.
+const PUSH_TTL_SECONDS = 86400;
+
+export const sendPushFunction = inngest.createFunction(
+ {
+ id: "send-push",
+ retries: 3
+ },
+ { event: "carbon/send-push" },
+ async ({ event, step }) => {
+ const { subscriptionId, userId, title, body, url, tag } = event.data;
+
+ const vapidDetails = getVapidDetails();
+ if (!vapidDetails) {
+ return { skipped: "push not configured" };
+ }
+
+ const subscription = await step.run("load-subscription", async () => {
+ const { data, error } = await getCarbonServiceRole()
+ .from("pushSubscription")
+ .select("id, endpoint, p256dh, auth")
+ .eq("id", subscriptionId)
+ // Only the recipient's browser: a row that changed hands since the
+ // fan-out (sign-out, another user enabled it) is skipped.
+ .eq("userId", userId)
+ .maybeSingle();
+ if (error) {
+ log.error("Failed to load push subscription", {
+ error,
+ subscriptionId
+ });
+ throw error;
+ }
+ return data;
+ });
+
+ // Disabled, signed out or handed to another user between the fan-out and
+ // this run. companyId on the event is the notification's company, not the
+ // row's, so the row is matched on id and recipient only.
+ if (!subscription) {
+ return { skipped: "subscription not found" };
+ }
+
+ const sent = await step.run("send-push", async () => {
+ try {
+ const result = await webpush.sendNotification(
+ {
+ endpoint: subscription.endpoint,
+ keys: { auth: subscription.auth, p256dh: subscription.p256dh }
+ },
+ JSON.stringify({ body, tag, title, url }),
+ {
+ TTL: PUSH_TTL_SECONDS,
+ urgency: "normal",
+ vapidDetails
+ }
+ );
+ return { gone: false, status: result.statusCode };
+ } catch (err) {
+ // No status code: the request never reached the push service (DNS,
+ // reset), so let Inngest retry.
+ if (!(err instanceof webpush.WebPushError)) throw err;
+ const status = err.statusCode;
+ switch (pushDeliveryOutcome(status)) {
+ case "gone":
+ return { gone: true, status };
+ case "rejected":
+ // Kept: the browser replaces an old-key subscription on its next
+ // page load, and the row ages out after a session's lifetime. The
+ // body says which (e.g. Apple's "BadJwtToken" is our token).
+ log.warn("Push service refused the signature", {
+ body: err.body,
+ host: new URL(subscription.endpoint).host,
+ status,
+ subscriptionId: subscription.id
+ });
+ return { gone: false, rejected: true, status };
+ case "retry":
+ throw new Error(`Push service returned ${status}; retrying`);
+ default:
+ throw new NonRetriableError(
+ `Push service refused the request (${status}): ${err.body}`
+ );
+ }
+ }
+ });
+
+ // 404 / 410: the browser dropped the subscription (permission revoked,
+ // site data cleared, signed out) — it never comes back.
+ if (sent.gone) {
+ await step.run("delete-subscription", async () => {
+ const { error } = await getCarbonServiceRole()
+ .from("pushSubscription")
+ .delete()
+ .eq("id", subscription.id);
+ if (error) {
+ log.error("Failed to delete a gone push subscription", {
+ error,
+ subscriptionId: subscription.id
+ });
+ throw error;
+ }
+ });
+ }
+
+ return sent;
+ }
+);
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index 4a2ecdd50b..454362f1c1 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -62,6 +62,7 @@ import {
import {
notifyFunction,
sendEmailFunction,
+ sendPushFunction,
sendSlackFunction
} from "./functions/notifications";
import {
@@ -117,6 +118,7 @@ export const functions = [
// Notifications
notifyFunction,
sendEmailFunction,
+ sendPushFunction,
sendSlackFunction,
// Event handlers
auditFunction,
diff --git a/packages/lib/AGENTS.md b/packages/lib/AGENTS.md
index 0188c4eb3e..5ca4870af9 100644
--- a/packages/lib/AGENTS.md
+++ b/packages/lib/AGENTS.md
@@ -7,6 +7,7 @@ Shared server utilities — event system, Inngest client, trigger dispatch, SMTP
- **Use `trigger(taskId, payload)` for dispatching background jobs** — typed helper that maps task IDs to Inngest event names; drop-in replacement for old `tasks.trigger()`
- **Add new events to the `Events` type in `events.ts`** — every Inngest event needs a typed payload here
- **Add new task mappings to `taskToEvent` in `trigger.ts`** — maps human-readable task IDs to `carbon/*` event names
+- **`carbon/send-push` has no task on purpose** — only the `notify` job sends it (`step.sendEvent`), because browser push mirrors the in-app row; app code never pushes directly
- **Guard external calls** — `email.server.ts` no-ops when no SMTP config is set (`SMTP_*`, with a legacy `RESEND_API_KEY` fallback via smtp.resend.com); `slack.server.ts` skips sends on localhost
- **Add new work events to `src/telemetry/events.ts`** — the `WorkEvents` type map is the contract; `captureWorkEvent` is typed off it, so an unlisted name will not compile
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 6c2f13858a..967224b2ce 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -52,6 +52,20 @@ export type Events = {
};
};
+ // Web Push events: one per pushSubscription row. userId is the recipient:
+ // send-push only sends when the row still belongs to them.
+ "carbon/send-push": {
+ data: {
+ subscriptionId: string;
+ userId: string;
+ companyId: string;
+ title: string;
+ body: string;
+ url: string;
+ tag: string;
+ };
+ };
+
// Email events
"carbon/send-email": {
data: {
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index b131ce871f..e003d4fa2e 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -3825,6 +3825,12 @@ msgstr "Bibliothek durchsuchen"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "Durchsuchen Sie die veröffentlichte Version schreibgeschützt. Sie können die Schritte weiterhin neu anordnen, um das Layout zu ordnen."
+msgid "Browser notifications"
+msgstr "Browser-Benachrichtigungen"
+
+msgid "Browser notifications are on for this browser."
+msgstr "Browser-Benachrichtigungen sind für diesen Browser aktiviert."
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "Richtung"
msgid "Directions"
msgstr "Richtungen"
+msgid "Disable"
+msgstr "Deaktivieren"
+
msgid "Disabled"
msgstr "Deaktiviert"
@@ -8151,9 +8160,15 @@ msgstr "Leere Liste"
msgid "Empty work centers"
msgstr "Leere Arbeitsplätze"
+msgid "Enable"
+msgstr "Aktivieren"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "Aktivieren Sie die Audit-Protokollierung in den Einstellungen, um Änderungen an Ihren Daten zu verfolgen."
+msgid "Enable browser notifications"
+msgstr "Browser-Benachrichtigungen aktivieren"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "Aktivieren Sie digitale Angebote für Ihr Unternehmen. Dies ermöglicht es Ihnen, digitale Angebote an Ihre Kunden zu senden und ihnen, diese online anzunehmen."
@@ -9000,9 +9015,15 @@ msgstr "Arbeitsplatz konnte nicht erstellt werden: {0}"
msgid "Failed to delete file from old location"
msgstr "Fehler beim Löschen der Datei vom alten Speicherort"
+msgid "Failed to disable browser notifications"
+msgstr "Browser-Benachrichtigungen konnten nicht deaktiviert werden"
+
msgid "Failed to download file for moving"
msgstr "Fehler beim Herunterladen der Datei zum Verschieben"
+msgid "Failed to enable browser notifications"
+msgstr "Browser-Benachrichtigungen konnten nicht aktiviert werden"
+
msgid "Failed to fetch item costs"
msgstr "Fehler beim Abrufen der Artikelkosten"
@@ -9717,6 +9738,9 @@ msgstr "Erste Schritte"
msgid "Get Started"
msgstr "Erste Schritte"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Erhalten Sie Ihre Carbon-Benachrichtigungen sofort, wenn sie eintreffen."
+
msgid "Gets the summary for every agreement"
msgstr "Erhält die Zusammenfassung für jede Vereinbarung"
@@ -13875,6 +13899,9 @@ msgstr "Nicht genug Einheitendaten"
msgid "Not feasible"
msgstr "Nicht machbar"
+msgid "Not now"
+msgstr "Jetzt nicht"
+
msgid "Not reached"
msgstr "Nicht erreicht"
@@ -13975,6 +14002,9 @@ msgstr "Benachrichtigungstyp"
msgid "Notifications"
msgstr "Benachrichtigungen"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "Benachrichtigungen sind für Carbon in den Site-Einstellungen dieses Browsers blockiert."
+
msgid "Notify"
msgstr "Benachrichtigen"
@@ -21451,6 +21481,9 @@ msgstr "Diese Sicherung konnte nicht abgeschlossen werden."
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "Diese Sicherung wurde noch nicht überprüft. Alle Unterschiede werden beim Ausführen der Wiederherstellung gefunden."
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "Dieser Browser unterstützt keine Push-Benachrichtigungen. Fügen Sie Carbon zuerst auf dem iPhone oder iPad zum Startbildschirm hinzu."
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "Dies kann später nicht mehr geändert werden — {integrationName} erlaubt nur ein verbundenes Buchhaltungssystem, daher bestimmt die Wahl, was Carbon tun darf. Um zu wechseln, müssten Sie die Anwendung deinstallieren und erneut verbinden."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index b24f08fdc5..b931a83bb3 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -3825,6 +3825,12 @@ msgstr "Browse library"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "Browse the published version read-only. You can still rearrange steps to tidy the layout."
+msgid "Browser notifications"
+msgstr "Browser notifications"
+
+msgid "Browser notifications are on for this browser."
+msgstr "Browser notifications are on for this browser."
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "Direction"
msgid "Directions"
msgstr "Directions"
+msgid "Disable"
+msgstr "Disable"
+
msgid "Disabled"
msgstr "Disabled"
@@ -8151,9 +8160,15 @@ msgstr "Empty list"
msgid "Empty work centers"
msgstr "Empty work centers"
+msgid "Enable"
+msgstr "Enable"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "Enable audit logging in settings to start tracking changes to your data."
+msgid "Enable browser notifications"
+msgstr "Enable browser notifications"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
@@ -9000,9 +9015,15 @@ msgstr "Failed to create work center: {0}"
msgid "Failed to delete file from old location"
msgstr "Failed to delete file from old location"
+msgid "Failed to disable browser notifications"
+msgstr "Failed to disable browser notifications"
+
msgid "Failed to download file for moving"
msgstr "Failed to download file for moving"
+msgid "Failed to enable browser notifications"
+msgstr "Failed to enable browser notifications"
+
msgid "Failed to fetch item costs"
msgstr "Failed to fetch item costs"
@@ -9717,6 +9738,9 @@ msgstr "Get started"
msgid "Get Started"
msgstr "Get Started"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Get your Carbon notifications as they happen."
+
msgid "Gets the summary for every agreement"
msgstr "Gets the summary for every agreement"
@@ -13875,6 +13899,9 @@ msgstr "Not enough unit data"
msgid "Not feasible"
msgstr "Not feasible"
+msgid "Not now"
+msgstr "Not now"
+
msgid "Not reached"
msgstr "Not reached"
@@ -13975,6 +14002,9 @@ msgstr "Notification Type"
msgid "Notifications"
msgstr "Notifications"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "Notifications are blocked for Carbon in this browser's site settings."
+
msgid "Notify"
msgstr "Notify"
@@ -21451,6 +21481,9 @@ msgstr "This backup could not be completed."
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "This backup hasn't been checked yet. Any differences are found when the restore runs."
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index e1dab29e2d..d488deb31b 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -3825,6 +3825,12 @@ msgstr "Examinar biblioteca"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "Explore la versión publicada de solo lectura. Aún puede reorganizar pasos para ordenar el diseño."
+msgid "Browser notifications"
+msgstr "Notificaciones del navegador"
+
+msgid "Browser notifications are on for this browser."
+msgstr "Las notificaciones del navegador están activadas para este navegador."
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "Dirección"
msgid "Directions"
msgstr "Direcciones"
+msgid "Disable"
+msgstr "Desactivar"
+
msgid "Disabled"
msgstr "Deshabilitado"
@@ -8151,9 +8160,15 @@ msgstr "Lista vacía"
msgid "Empty work centers"
msgstr "Centros de trabajo vacíos"
+msgid "Enable"
+msgstr "Activar"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "Habilita el registro de auditoría en la configuración para comenzar a rastrear cambios en tus datos."
+msgid "Enable browser notifications"
+msgstr "Activar notificaciones del navegador"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "Habilita cotizaciones digitales para tu empresa. Esto te permitirá enviar cotizaciones digitales a tus clientes y permitirles aceptarlas en línea."
@@ -9000,9 +9015,15 @@ msgstr "Error al crear el centro de trabajo: {0}"
msgid "Failed to delete file from old location"
msgstr "Error al eliminar el archivo de la ubicación anterior"
+msgid "Failed to disable browser notifications"
+msgstr "Error al desactivar las notificaciones del navegador"
+
msgid "Failed to download file for moving"
msgstr "Error al descargar el archivo para mover"
+msgid "Failed to enable browser notifications"
+msgstr "Error al activar las notificaciones del navegador"
+
msgid "Failed to fetch item costs"
msgstr "Error al obtener costos de artículos"
@@ -9717,6 +9738,9 @@ msgstr "Comenzar"
msgid "Get Started"
msgstr "Comenzar"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Recibe tus notificaciones de Carbon en tiempo real."
+
msgid "Gets the summary for every agreement"
msgstr "Obtiene el resumen de cada acuerdo"
@@ -13875,6 +13899,9 @@ msgstr "Datos de unidad insuficientes"
msgid "Not feasible"
msgstr "No es viable"
+msgid "Not now"
+msgstr "Ahora no"
+
msgid "Not reached"
msgstr "No alcanzado"
@@ -13975,6 +14002,9 @@ msgstr "Tipo de Notificación"
msgid "Notifications"
msgstr "Notificaciones"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "Las notificaciones están bloqueadas para Carbon en la configuración de sitios de este navegador."
+
msgid "Notify"
msgstr "Notificar"
@@ -21451,6 +21481,9 @@ msgstr "Esta copia de seguridad no se pudo completar."
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "Esta copia de seguridad aún no ha sido verificada. Se encontrarán diferencias cuando se ejecute la restauración."
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "Este navegador no es compatible con notificaciones push. En iPhone o iPad, agrega primero Carbon a la pantalla de inicio."
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "Esto no se puede cambiar más tarde — {integrationName} permite solo un sistema contable conectado, por lo que la opción decide qué puede hacer Carbon. Para cambiar, tendrías que desinstalar y reconectar."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index b723e5ec66..40e5c191b1 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -3825,6 +3825,12 @@ msgstr "Parcourir la bibliothèque"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "Parcourez la version publiée en lecture seule. Vous pouvez toujours réarranger les étapes pour nettoyer la mise en page."
+msgid "Browser notifications"
+msgstr "Notifications du navigateur"
+
+msgid "Browser notifications are on for this browser."
+msgstr "Les notifications du navigateur sont activées pour ce navigateur."
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "Direction"
msgid "Directions"
msgstr "Directions"
+msgid "Disable"
+msgstr "Désactiver"
+
msgid "Disabled"
msgstr "Désactivé"
@@ -8151,9 +8160,15 @@ msgstr "Liste vide"
msgid "Empty work centers"
msgstr "Postes de travail vides"
+msgid "Enable"
+msgstr "Activer"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "Activez la journalisation d'audit dans les paramètres pour commencer à suivre les modifications apportées à vos données."
+msgid "Enable browser notifications"
+msgstr "Activer les notifications du navigateur"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "Activez les devis numériques pour votre société. Cela vous permettra d'envoyer des devis numériques à vos clients et leur permettra de les accepter en ligne."
@@ -9000,9 +9015,15 @@ msgstr "Échec de la création du poste de travail : {0}"
msgid "Failed to delete file from old location"
msgstr "Impossible de supprimer le fichier de l'ancien emplacement"
+msgid "Failed to disable browser notifications"
+msgstr "Impossible de désactiver les notifications du navigateur"
+
msgid "Failed to download file for moving"
msgstr "Échec du téléchargement du fichier pour le déplacement"
+msgid "Failed to enable browser notifications"
+msgstr "Impossible d'activer les notifications du navigateur"
+
msgid "Failed to fetch item costs"
msgstr "Échec de la récupération des coûts des articles"
@@ -9717,6 +9738,9 @@ msgstr "Commencer"
msgid "Get Started"
msgstr "Commencer"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Recevez vos notifications Carbon au fur et à mesure."
+
msgid "Gets the summary for every agreement"
msgstr "Obtient le résumé pour chaque accord"
@@ -13875,6 +13899,9 @@ msgstr "Pas assez de données sur l'unité"
msgid "Not feasible"
msgstr "Non réalisable"
+msgid "Not now"
+msgstr "Pas maintenant"
+
msgid "Not reached"
msgstr "Non atteint"
@@ -13975,6 +14002,9 @@ msgstr "Type de notification"
msgid "Notifications"
msgstr "Notifications"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "Les notifications sont bloquées pour Carbon dans les paramètres du site de ce navigateur."
+
msgid "Notify"
msgstr "Notifier"
@@ -21451,6 +21481,9 @@ msgstr "Cette sauvegarde n'a pas pu être complétée."
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "Cette sauvegarde n'a pas encore été vérifiée. Toute différence est trouvée lors de l'exécution de la restauration."
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "Ce navigateur ne supporte pas les notifications push. Sur iPhone ou iPad, ajoutez d'abord Carbon à l'écran d'accueil."
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "Cela ne peut pas être modifié ultérieurement — {integrationName} n'autorise qu'un seul système comptable connecté, donc le choix détermine ce que Carbon est autorisé à faire. Pour changer, vous devriez désinstaller et reconnecter."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index eb404045be..20e24f91c3 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -3825,6 +3825,12 @@ msgstr "लाइब्रेरी ब्राउज़ करें"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "प्रकाशित संस्करण को केवल पढ़ने के लिए ब्राउज़ करें। आप अभी भी लेआउट को साफ करने के लिए चरणों को पुनर्व्यवस्थित कर सकते हैं।"
+msgid "Browser notifications"
+msgstr "ब्राउज़र सूचनाएँ"
+
+msgid "Browser notifications are on for this browser."
+msgstr "इस ब्राउज़र के लिए ब्राउज़र सूचनाएँ चालू हैं।"
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "दिशा"
msgid "Directions"
msgstr "दिशाएं"
+msgid "Disable"
+msgstr "अक्षम करें"
+
msgid "Disabled"
msgstr "अक्षम"
@@ -8151,9 +8160,15 @@ msgstr "खाली सूची"
msgid "Empty work centers"
msgstr "खाली वर्क सेंटर"
+msgid "Enable"
+msgstr "सक्षम करें"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "अपने डेटा में परिवर्तनों को ट्रैक करना शुरू करने के लिए सेटिंग्स में ऑडिट लॉगिंग सक्षम करें।"
+msgid "Enable browser notifications"
+msgstr "ब्राउज़र सूचनाएँ सक्षम करें"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "अपनी कंपनी के लिए डिजिटल उद्धरण सक्षम करें। यह आपको अपने ग्राहकों को डिजिटल उद्धरण भेजने की अनुमति देगा, और उन्हें ऑनलाइन स्वीकार करने की अनुमति देगा।"
@@ -9000,9 +9015,15 @@ msgstr "वर्क सेंटर बनाने में विफल: {0}
msgid "Failed to delete file from old location"
msgstr "पुराने स्थान से फ़ाइल हटाने में विफल"
+msgid "Failed to disable browser notifications"
+msgstr "ब्राउज़र सूचनाओं को अक्षम करने में विफल रहा"
+
msgid "Failed to download file for moving"
msgstr "स्थानांतरण के लिए फ़ाइल डाउनलोड करने में विफल"
+msgid "Failed to enable browser notifications"
+msgstr "ब्राउज़र सूचनाओं को सक्षम करने में विफल रहा"
+
msgid "Failed to fetch item costs"
msgstr "आइटम लागत प्राप्त करने में विफल"
@@ -9717,6 +9738,9 @@ msgstr "शुरुआत करें"
msgid "Get Started"
msgstr "शुरुआत करें"
+msgid "Get your Carbon notifications as they happen."
+msgstr "अपनी Carbon सूचनाएँ तुरंत प्राप्त करें।"
+
msgid "Gets the summary for every agreement"
msgstr "प्रत्येक समझौते के लिए सारांश प्राप्त करता है"
@@ -13875,6 +13899,9 @@ msgstr "पर्याप्त यूनिट डेटा नहीं"
msgid "Not feasible"
msgstr "संभव नहीं"
+msgid "Not now"
+msgstr "अभी नहीं"
+
msgid "Not reached"
msgstr "प्राप्त नहीं"
@@ -13975,6 +14002,9 @@ msgstr "सूचना प्रकार"
msgid "Notifications"
msgstr "सूचनाएं"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "इस ब्राउज़र की साइट सेटिंग्स में Carbon के लिए सूचनाएं अवरुद्ध हैं।"
+
msgid "Notify"
msgstr "सूचित करें"
@@ -21451,6 +21481,9 @@ msgstr "यह बैकअप पूर्ण नहीं किया जा
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "इस बैकअप की अभी जांच नहीं की गई है। कोई भी अंतर पुनः स्थापित करने के समय पाया जाता है।"
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "यह ब्राउज़र पुश सूचनाओं का समर्थन नहीं करता। iPhone या iPad पर, पहले Carbon को होम स्क्रीन में जोड़ें।"
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "यह बाद में नहीं बदला जा सकता — {integrationName} केवल एक जुड़े हुए लेखांकन प्रणाली की अनुमति देता है, इसलिए यह विकल्प तय करता है कि Carbon क्या करने के लिए अनुमत है। स्विच करने के लिए, आप अनइंस्टॉल करेंगे और फिर से कनेक्ट करेंगे।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 494ba8a03f..4b3a16cc74 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -3825,6 +3825,12 @@ msgstr "Sfoglia libreria"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "Visualizza la versione pubblicata in sola lettura. Puoi comunque riorganizzare i passi per ordinare il layout."
+msgid "Browser notifications"
+msgstr "Notifiche del browser"
+
+msgid "Browser notifications are on for this browser."
+msgstr "Le notifiche del browser sono attive per questo browser."
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "Direzione"
msgid "Directions"
msgstr "Direzioni"
+msgid "Disable"
+msgstr "Disattiva"
+
msgid "Disabled"
msgstr "Disabilitato"
@@ -8151,9 +8160,15 @@ msgstr "Elenco vuoto"
msgid "Empty work centers"
msgstr "Centri di lavoro vuoti"
+msgid "Enable"
+msgstr "Attiva"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "Abilita la registrazione di audit nelle impostazioni per iniziare a tracciare le modifiche ai tuoi dati."
+msgid "Enable browser notifications"
+msgstr "Attiva notifiche del browser"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "Abilita le quotazioni digitali per la tua azienda. Questo ti permetterà di inviare quotazioni digitali ai tuoi clienti e consentire loro di accettarle online."
@@ -9000,9 +9015,15 @@ msgstr "Impossibile creare il centro di lavoro: {0}"
msgid "Failed to delete file from old location"
msgstr "Impossibile eliminare il file dalla posizione precedente"
+msgid "Failed to disable browser notifications"
+msgstr "Impossibile disattivare le notifiche del browser"
+
msgid "Failed to download file for moving"
msgstr "Impossibile scaricare il file per lo spostamento"
+msgid "Failed to enable browser notifications"
+msgstr "Impossibile attivare le notifiche del browser"
+
msgid "Failed to fetch item costs"
msgstr "Impossibile recuperare i costi degli articoli"
@@ -9717,6 +9738,9 @@ msgstr "Inizia"
msgid "Get Started"
msgstr "Inizia"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Ricevi le tue notifiche di Carbon quando si verificano."
+
msgid "Gets the summary for every agreement"
msgstr "Ottiene il riepilogo per ogni accordo"
@@ -13875,6 +13899,9 @@ msgstr "Non ci sono dati sufficienti sull'unità"
msgid "Not feasible"
msgstr "Non fattibile"
+msgid "Not now"
+msgstr "Non ora"
+
msgid "Not reached"
msgstr "Non raggiunto"
@@ -13975,6 +14002,9 @@ msgstr "Tipo di notifica"
msgid "Notifications"
msgstr "Notifiche"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "Le notifiche sono bloccate per Carbon nelle impostazioni del sito di questo browser."
+
msgid "Notify"
msgstr "Notifica"
@@ -21451,6 +21481,9 @@ msgstr "Non è stato possibile completare questo backup."
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "Questo backup non è stato ancora verificato. Le eventuali differenze vengono rilevate quando il ripristino viene eseguito."
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "Questo browser non supporta le notifiche push. Su iPhone o iPad, aggiungi prima Carbon alla schermata Home."
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "Non può essere modificato in seguito — {integrationName} consente un solo sistema contabile connesso, quindi la scelta determina cosa Carbon è autorizzato a fare. Per cambiare, dovresti disinstallare e riconnettere."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 7d3ec52ffd..58ad931d00 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -3825,6 +3825,12 @@ msgstr "ライブラリを参照"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "公開済バージョンを読み取り専用で閲覧できます。レイアウトを整理するためにステップを並び替えることもできます。"
+msgid "Browser notifications"
+msgstr "ブラウザー通知"
+
+msgid "Browser notifications are on for this browser."
+msgstr "このブラウザーではブラウザー通知が有効です。"
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "方向"
msgid "Directions"
msgstr "方向"
+msgid "Disable"
+msgstr "無効にする"
+
msgid "Disabled"
msgstr "無効"
@@ -8151,9 +8160,15 @@ msgstr "空のリスト"
msgid "Empty work centers"
msgstr "作業区がありません"
+msgid "Enable"
+msgstr "有効にする"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "設定で監査ログを有効にして、データへの変更の追跡を開始します。"
+msgid "Enable browser notifications"
+msgstr "ブラウザー通知を有効にする"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "会社のデジタル見積を有効にします。これにより、デジタル見積を得意先に送信し、オンラインで承諾させることができます。"
@@ -9000,9 +9015,15 @@ msgstr "作業区を作成できませんでした: {0}"
msgid "Failed to delete file from old location"
msgstr "古い場所からファイルを削除できませんでした"
+msgid "Failed to disable browser notifications"
+msgstr "ブラウザー通知を無効にできませんでした"
+
msgid "Failed to download file for moving"
msgstr "ファイルの移動用ダウンロードに失敗しました"
+msgid "Failed to enable browser notifications"
+msgstr "ブラウザー通知を有効にできませんでした"
+
msgid "Failed to fetch item costs"
msgstr "品目の原価を取得できませんでした"
@@ -9717,6 +9738,9 @@ msgstr "始めましょう"
msgid "Get Started"
msgstr "はじめる"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Carbonからの通知がリアルタイムで届きます。"
+
msgid "Gets the summary for every agreement"
msgstr "すべての協定のサマリーを取得します"
@@ -13875,6 +13899,9 @@ msgstr "個データが不足しています"
msgid "Not feasible"
msgstr "実現不可能"
+msgid "Not now"
+msgstr "後で"
+
msgid "Not reached"
msgstr "未到達"
@@ -13975,6 +14002,9 @@ msgstr "通知タイプ"
msgid "Notifications"
msgstr "通知"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "このブラウザのサイト設定でCarbonの通知がブロックされています。"
+
msgid "Notify"
msgstr "通知"
@@ -21451,6 +21481,9 @@ msgstr "このバックアップを完了できませんでした。"
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "このバックアップはまだチェックされていません。違いは復元の実行時に見つかります。"
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "このブラウザはプッシュ通知に対応していません。iPhoneまたはiPadの場合は、まずCarbonをホーム画面に追加してください。"
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "これは後で変更することはできません — {integrationName}は接続できる会計システムが1つだけに限定されているため、この選択はCarbonが実行できることを決定します。切り替えるには、アンインストールして再度接続する必要があります。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 75ee1c5a45..0e96134ae3 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -3825,6 +3825,12 @@ msgstr "라이브러리 둘러보기"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "게시됨 버전을 읽기 전용으로 탐색합니다. 단계를 다시 정렬하여 레이아웃을 정리할 수 있습니다."
+msgid "Browser notifications"
+msgstr "브라우저 알림"
+
+msgid "Browser notifications are on for this browser."
+msgstr "이 브라우저에서 브라우저 알림이 켜져 있습니다."
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "방향"
msgid "Directions"
msgstr "방향"
+msgid "Disable"
+msgstr "비활성화"
+
msgid "Disabled"
msgstr "비활성화됨"
@@ -8151,9 +8160,15 @@ msgstr "빈 목록"
msgid "Empty work centers"
msgstr "빈 작업장"
+msgid "Enable"
+msgstr "활성화"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "데이터 변경 사항 추적을 시작하려면 설정에서 감사 로깅을 활성화하세요."
+msgid "Enable browser notifications"
+msgstr "브라우저 알림 활성화"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "회사의 디지털 견적서를 활성화하세요. 이렇게 하면 고객에게 디지털 견적서를 보낼 수 있으며, 고객이 온라인에서 수락할 수 있습니다."
@@ -9000,9 +9015,15 @@ msgstr "작업장 생성 실패: {0}"
msgid "Failed to delete file from old location"
msgstr "이전 위치에서 파일 삭제 실패"
+msgid "Failed to disable browser notifications"
+msgstr "브라우저 알림 비활성화 실패"
+
msgid "Failed to download file for moving"
msgstr "이동을 위한 파일 다운로드 실패"
+msgid "Failed to enable browser notifications"
+msgstr "브라우저 알림 활성화 실패"
+
msgid "Failed to fetch item costs"
msgstr "품목 원가 조회 실패"
@@ -9717,6 +9738,9 @@ msgstr "시작하기"
msgid "Get Started"
msgstr "시작하기"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Carbon 알림을 발생 시점에 받으세요."
+
msgid "Gets the summary for every agreement"
msgstr "모든 계약에 대한 요약을 받습니다."
@@ -13875,6 +13899,9 @@ msgstr "개에 대한 데이터가 부족합니다."
msgid "Not feasible"
msgstr "불가능"
+msgid "Not now"
+msgstr "나중에"
+
msgid "Not reached"
msgstr "도달하지 않음"
@@ -13975,6 +14002,9 @@ msgstr "알림 유형"
msgid "Notifications"
msgstr "알림"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "이 브라우저의 사이트 설정에서 Carbon의 알림이 차단되었습니다."
+
msgid "Notify"
msgstr "알림"
@@ -21451,6 +21481,9 @@ msgstr "이 백업을 완료할 수 없습니다."
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "이 백업은 아직 확인되지 않았습니다. 복원이 실행될 때 차이점이 발견됩니다."
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "이 브라우저는 푸시 알림을 지원하지 않습니다. iPhone 또는 iPad의 경우 먼저 Carbon을 홈 화면에 추가하세요."
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "이후에는 변경할 수 없습니다 — {integrationName}은(는) 연결된 회계 시스템을 하나만 허용하므로, 선택에 따라 Carbon이 수행할 수 있는 작업이 결정됩니다. 전환하려면 제거한 후 다시 연결해야 합니다."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index ecb142cff6..e1074a62b3 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -3825,6 +3825,12 @@ msgstr "Przeglądaj bibliotekę"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "Przeglądaj opublikowaną wersję w trybie tylko do odczytu. Nadal możesz zmienić kolejność kroków, aby uporządkować układ."
+msgid "Browser notifications"
+msgstr "Powiadomienia przeglądarki"
+
+msgid "Browser notifications are on for this browser."
+msgstr "Powiadomienia przeglądarki są włączone w tej przeglądarce."
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "Kierunek"
msgid "Directions"
msgstr "Kierunki"
+msgid "Disable"
+msgstr "Wyłącz"
+
msgid "Disabled"
msgstr "Wyłączone"
@@ -8151,9 +8160,15 @@ msgstr "Pusta lista"
msgid "Empty work centers"
msgstr "Puste stanowiska robocze"
+msgid "Enable"
+msgstr "Włącz"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "Włącz rejestrowanie audytu w ustawieniach, aby rozpocząć śledzenie zmian w Twoich danych."
+msgid "Enable browser notifications"
+msgstr "Włącz powiadomienia przeglądarki"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "Włącz cyfrowe oferty dla swojej firmy. Umożliwi to wysyłanie cyfrowych ofert do klientów i pozwoli im zaakceptować je online."
@@ -9000,9 +9015,15 @@ msgstr "Nie udało się utworzyć stanowiska roboczego: {0}"
msgid "Failed to delete file from old location"
msgstr "Nie udało się usunąć pliku ze starej lokalizacji"
+msgid "Failed to disable browser notifications"
+msgstr "Nie udało się wyłączyć powiadomień przeglądarki"
+
msgid "Failed to download file for moving"
msgstr "Nie udało się pobrać pliku do przeniesienia."
+msgid "Failed to enable browser notifications"
+msgstr "Nie udało się włączyć powiadomień przeglądarki"
+
msgid "Failed to fetch item costs"
msgstr "Nie udało się pobrać kosztów pozycji"
@@ -9717,6 +9738,9 @@ msgstr "Zacznij"
msgid "Get Started"
msgstr "Rozpocznij"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Otrzymuj powiadomienia Carbon w miarę ich pojawiania się."
+
msgid "Gets the summary for every agreement"
msgstr "Otrzymuje podsumowanie dla każdej umowy"
@@ -13875,6 +13899,9 @@ msgstr "Niewystarczająco danych sztuki"
msgid "Not feasible"
msgstr "Niemożliwe do wykonania"
+msgid "Not now"
+msgstr "Nie teraz"
+
msgid "Not reached"
msgstr "Nieosiągnięty"
@@ -13975,6 +14002,9 @@ msgstr "Typ powiadomienia"
msgid "Notifications"
msgstr "Powiadomienia"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "Powiadomienia są zablokowane dla Carbon w ustawieniach witryny tej przeglądarki."
+
msgid "Notify"
msgstr "Powiadom"
@@ -21451,6 +21481,9 @@ msgstr "Nie można było ukończyć tej kopii zapasowej."
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "Ta kopia zapasowa nie została jeszcze sprawdzona. Wszelkie różnice są znaleziane po uruchomieniu przywracania."
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "Ta przeglądarka nie obsługuje powiadomień push. Na iPhone'ie lub iPad najpierw dodaj Carbon do ekranu głównego."
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "Nie można tego zmienić później — {integrationName} pozwala na połączenie tylko jednego systemu księgowego, więc wybór decyduje o tym, co Carbon może robić. Aby przełączyć się, musisz odinstalować i ponownie połączyć."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index e3a063f040..afff8a02ff 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -3825,6 +3825,12 @@ msgstr "Procurar biblioteca"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "Navegue pela versão publicada somente leitura. Você ainda pode reorganizar etapas para limpar o layout."
+msgid "Browser notifications"
+msgstr "Notificações do navegador"
+
+msgid "Browser notifications are on for this browser."
+msgstr "As notificações do navegador estão ativadas para este navegador."
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "Direção"
msgid "Directions"
msgstr "Direções"
+msgid "Disable"
+msgstr "Desativar"
+
msgid "Disabled"
msgstr "Desativado"
@@ -8151,9 +8160,15 @@ msgstr "Lista vazia"
msgid "Empty work centers"
msgstr "Centros de trabalho vazios"
+msgid "Enable"
+msgstr "Ativar"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "Ative o registro de auditoria nas configurações para começar a rastrear alterações nos seus dados."
+msgid "Enable browser notifications"
+msgstr "Ativar notificações do navegador"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "Ative cotações digitais para sua empresa. Isso permitirá que você envie cotações digitais para seus clientes e permita que eles as aceitem online."
@@ -9000,9 +9015,15 @@ msgstr "Falha ao criar centro de trabalho: {0}"
msgid "Failed to delete file from old location"
msgstr "Falha ao excluir arquivo do local anterior"
+msgid "Failed to disable browser notifications"
+msgstr "Falha ao desativar notificações do navegador"
+
msgid "Failed to download file for moving"
msgstr "Falha ao baixar arquivo para mover"
+msgid "Failed to enable browser notifications"
+msgstr "Falha ao ativar notificações do navegador"
+
msgid "Failed to fetch item costs"
msgstr "Falha ao buscar custos de itens"
@@ -9717,6 +9738,9 @@ msgstr "Começar"
msgid "Get Started"
msgstr "Começar"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Receba suas notificações do Carbon assim que acontecerem."
+
msgid "Gets the summary for every agreement"
msgstr "Obtém o resumo de cada acordo"
@@ -13875,6 +13899,9 @@ msgstr "Dados de unidade insuficientes"
msgid "Not feasible"
msgstr "Não é viável"
+msgid "Not now"
+msgstr "Não agora"
+
msgid "Not reached"
msgstr "Não atingido"
@@ -13975,6 +14002,9 @@ msgstr "Tipo de Notificação"
msgid "Notifications"
msgstr "Notificações"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "As notificações estão bloqueadas para Carbon nas configurações de site deste navegador."
+
msgid "Notify"
msgstr "Notificar"
@@ -21451,6 +21481,9 @@ msgstr "Este backup não pôde ser concluído."
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "Este backup ainda não foi verificado. As diferenças são encontradas quando a restauração é executada."
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "Este navegador não suporta notificações push. No iPhone ou iPad, adicione o Carbon à Tela de Início primeiro."
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "Isto não pode ser alterado depois — {integrationName} permite apenas um sistema contábil conectado, portanto a escolha decide o que o Carbon tem permissão para fazer. Para mudar, você desinstalaria e reconectaria."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 82f88677b3..266fec624b 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -3825,6 +3825,12 @@ msgstr "Обзор библиотеки"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "Просмотрите опубликованную версию в режиме только для чтения. Вы все еще можете переставлять шаги для очистки макета."
+msgid "Browser notifications"
+msgstr "Уведомления браузера"
+
+msgid "Browser notifications are on for this browser."
+msgstr "Уведомления браузера включены для этого браузера."
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "Направление"
msgid "Directions"
msgstr "Направления"
+msgid "Disable"
+msgstr "Отключить"
+
msgid "Disabled"
msgstr "Отключено"
@@ -8151,9 +8160,15 @@ msgstr "Пустой список"
msgid "Empty work centers"
msgstr "Пустые рабочие центры"
+msgid "Enable"
+msgstr "Включить"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "Включите аудит в настройках, чтобы начать отслеживать изменения ваших данных."
+msgid "Enable browser notifications"
+msgstr "Включить уведомления браузера"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "Включить цифровые коммерческие предложения для вашей организации. Это позволит вам отправлять цифровые коммерческие предложения вашим покупателям и позволит им принимать их онлайн."
@@ -9000,9 +9015,15 @@ msgstr "Ошибка при создании рабочего центра: {0}"
msgid "Failed to delete file from old location"
msgstr "Не удалось удалить файл из старого местоположения"
+msgid "Failed to disable browser notifications"
+msgstr "Не удалось отключить уведомления браузера"
+
msgid "Failed to download file for moving"
msgstr "Не удалось скачать файл для перемещения"
+msgid "Failed to enable browser notifications"
+msgstr "Не удалось включить уведомления браузера"
+
msgid "Failed to fetch item costs"
msgstr "Ошибка при получении себестоимости номенклатуры"
@@ -9717,6 +9738,9 @@ msgstr "Начать"
msgid "Get Started"
msgstr "Начало работы"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Получайте уведомления Carbon по мере их поступления."
+
msgid "Gets the summary for every agreement"
msgstr "Получает резюме по каждому договору"
@@ -13875,6 +13899,9 @@ msgstr "Недостаточно данных единицы"
msgid "Not feasible"
msgstr "Невозможно выполнить"
+msgid "Not now"
+msgstr "Не сейчас"
+
msgid "Not reached"
msgstr "Не достигнуто"
@@ -13975,6 +14002,9 @@ msgstr "Тип уведомления"
msgid "Notifications"
msgstr "Уведомления"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "Уведомления заблокированы для Carbon в параметрах этого браузера."
+
msgid "Notify"
msgstr "Уведомить"
@@ -21451,6 +21481,9 @@ msgstr "Эта резервная копия не может быть завер
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "Эта резервная копия еще не была проверена. Любые различия будут обнаружены при запуске восстановления."
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "Этот браузер не поддерживает push-уведомления. На iPhone или iPad сначала добавьте Carbon на главный экран."
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "Это нельзя изменить позже — {integrationName} позволяет подключить только одну систему учета, поэтому выбор определяет, что Carbon может делать. Чтобы переключиться, вам нужно удалить и переподключить интеграцию."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index bb82a3dbbe..c3fb011884 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -3825,6 +3825,12 @@ msgstr "Kütüphaneyi göz at"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "Yayınlanan sürümü salt okunur şekilde inceleyin. Düzeni düzenlemek için adımları yine de yeniden düzenleyebilirsiniz."
+msgid "Browser notifications"
+msgstr "Tarayıcı Bildirimleri"
+
+msgid "Browser notifications are on for this browser."
+msgstr "Tarayıcı bildirimleri bu tarayıcı için açık."
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "Yön"
msgid "Directions"
msgstr "Yönler"
+msgid "Disable"
+msgstr "Devre Dışı Bırak"
+
msgid "Disabled"
msgstr "Devre Dışı"
@@ -8151,9 +8160,15 @@ msgstr "Boş liste"
msgid "Empty work centers"
msgstr "Boş iş merkezleri"
+msgid "Enable"
+msgstr "Etkinleştir"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "Verilerinizi izlemeye başlamak için ayarlar'dan denetim günlüklemesini etkinleştirin."
+msgid "Enable browser notifications"
+msgstr "Tarayıcı bildirimlerini etkinleştir"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "Şirketiniz için dijital teklifleri etkinleştirin. Bu, müşterilerinize dijital teklifler göndermenizi ve onların bunları çevrimiçi olarak kabul etmesine olanak tanır."
@@ -9000,9 +9015,15 @@ msgstr "İş merkezi oluşturulamadı: {0}"
msgid "Failed to delete file from old location"
msgstr "Eski konumdan dosya silinemedi"
+msgid "Failed to disable browser notifications"
+msgstr "Tarayıcı bildirimleri devre dışı bırakılamadı"
+
msgid "Failed to download file for moving"
msgstr "Taşınacak dosya indirilemedi"
+msgid "Failed to enable browser notifications"
+msgstr "Tarayıcı bildirimleri etkinleştirilemedi"
+
msgid "Failed to fetch item costs"
msgstr "Ürün maliyetleri alınamadı"
@@ -9717,6 +9738,9 @@ msgstr "Başlayın"
msgid "Get Started"
msgstr "Başlayın"
+msgid "Get your Carbon notifications as they happen."
+msgstr "Carbon bildirimlerinizi gerçekleştikleri anda alın."
+
msgid "Gets the summary for every agreement"
msgstr "Her anlaşmanın özetini alır"
@@ -13875,6 +13899,9 @@ msgstr "Yetersiz adet verisi"
msgid "Not feasible"
msgstr "Gerçekleştirilemez"
+msgid "Not now"
+msgstr "Şimdi değil"
+
msgid "Not reached"
msgstr "Ulaşılmadı"
@@ -13975,6 +14002,9 @@ msgstr "Bildirim Türü"
msgid "Notifications"
msgstr "Bildirimler"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "Bu tarayıcının site ayarlarında Carbon için bildirimler engellendi."
+
msgid "Notify"
msgstr "Bildir"
@@ -21451,6 +21481,9 @@ msgstr "Bu yedekleme tamamlanamadı."
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "Bu yedek henüz kontrol edilmedi. Herhangi bir fark, geri yükleme çalıştığında bulunur."
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "Bu tarayıcı push bildirimleri desteklemez. iPhone veya iPad'de, Carbon'u önce Ana Ekrana ekleyin."
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "Bu daha sonra değiştirilemez — {integrationName} yalnızca bir bağlı muhasebe sistemine izin verir, bu nedenle seçim Carbon'un ne yapmasına izin verildiğini belirler. Geçiş yapmak için kaldırıp yeniden bağlanmanız gerekir."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index d4e8292f3c..a4be709b33 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -3825,6 +3825,12 @@ msgstr "浏览库"
msgid "Browse the published version read-only. You can still rearrange steps to tidy the layout."
msgstr "浏览已发布版本(只读)。您仍然可以重新排列步骤来整理布局。"
+msgid "Browser notifications"
+msgstr "浏览器通知"
+
+msgid "Browser notifications are on for this browser."
+msgstr "此浏览器的浏览器通知已启用。"
+
msgid "BSB"
msgstr "BSB"
@@ -7194,6 +7200,9 @@ msgstr "方向"
msgid "Directions"
msgstr "方向"
+msgid "Disable"
+msgstr "禁用"
+
msgid "Disabled"
msgstr "已禁用"
@@ -8151,9 +8160,15 @@ msgstr "空列表"
msgid "Empty work centers"
msgstr "空的工作中心"
+msgid "Enable"
+msgstr "启用"
+
msgid "Enable audit logging in settings to start tracking changes to your data."
msgstr "在设置中启用审计日志以开始跟踪数据的更改。"
+msgid "Enable browser notifications"
+msgstr "启用浏览器通知"
+
msgid "Enable digital quotes for your company. This will allow you to send digital quotes to your customers, and allow them to accept them online."
msgstr "为您的公司启用数字报价。这将允许您向客户发送数字报价,并允许他们在线接受。"
@@ -9000,9 +9015,15 @@ msgstr "创建工作中心失败:{0}"
msgid "Failed to delete file from old location"
msgstr "删除旧位置的文件失败"
+msgid "Failed to disable browser notifications"
+msgstr "禁用浏览器通知失败"
+
msgid "Failed to download file for moving"
msgstr "无法下载文件以进行移动"
+msgid "Failed to enable browser notifications"
+msgstr "启用浏览器通知失败"
+
msgid "Failed to fetch item costs"
msgstr "获取物料成本失败"
@@ -9717,6 +9738,9 @@ msgstr "开始使用"
msgid "Get Started"
msgstr "开始使用"
+msgid "Get your Carbon notifications as they happen."
+msgstr "实时获取您的 Carbon 通知。"
+
msgid "Gets the summary for every agreement"
msgstr "获取每个协议的汇总"
@@ -13875,6 +13899,9 @@ msgstr "单位数据不足"
msgid "Not feasible"
msgstr "不可行"
+msgid "Not now"
+msgstr "暂不"
+
msgid "Not reached"
msgstr "未到达"
@@ -13975,6 +14002,9 @@ msgstr "通知类型"
msgid "Notifications"
msgstr "通知"
+msgid "Notifications are blocked for Carbon in this browser's site settings."
+msgstr "在此浏览器的网站设置中,Carbon 的通知被阻止。"
+
msgid "Notify"
msgstr "通知"
@@ -21451,6 +21481,9 @@ msgstr "无法完成此备份。"
msgid "This backup hasn't been checked yet. Any differences are found when the restore runs."
msgstr "此备份尚未检查。还原运行时将发现任何差异。"
+msgid "This browser does not support push notifications. On iPhone or iPad, add Carbon to the Home Screen first."
+msgstr "此浏览器不支持推送通知。在 iPhone 或 iPad 上,请先将 Carbon 添加到主屏幕。"
+
msgid "This cannot be changed later — {integrationName} allows only one connected accounting system, so the choice decides what Carbon is permitted to do. To switch, you would uninstall and reconnect."
msgstr "这无法在之后更改 — {integrationName} 仅允许一个连接的会计系统,因此您的选择决定了 Carbon 被允许执行的操作。要切换,您需要卸载并重新连接。"
diff --git a/packages/notifications/AGENTS.md b/packages/notifications/AGENTS.md
index b73cc8403b..ffe2c4dbf4 100644
--- a/packages/notifications/AGENTS.md
+++ b/packages/notifications/AGENTS.md
@@ -7,7 +7,7 @@ Notification event taxonomy — enums and topic mapping shared across app routes
- **Import `NotificationEvent` from `@carbon/notifications`** — this is the single source of truth for event types
- **Map new events to a `NotificationTopic` in `getNotificationTopic()`** — every event must belong to exactly one topic
- **Remember topic strings are persisted** — `NotificationTopic` values are stored in the `notification.topic` DB column; renaming is a migration
-- **Dispatch via `trigger("notify", payload)` from `@carbon/lib`** — the `carbon/notify` Inngest function handles fan-out (inApp / email / Slack)
+- **Dispatch via `trigger("notify", payload)` from `@carbon/lib`** — the `carbon/notify` Inngest function handles fan-out (inApp / email / Slack; browser push mirrors inApp)
## Ask First
@@ -31,6 +31,7 @@ pnpm --filter @carbon/notifications typecheck # tsgo --noEmit
- **Body rendering lives here, all three renditions together** — `renderInlineLinks` (the strict `[label](https://origin/…)` matcher; a security boundary, since a workflow's message body is customer-authored) plus `renderSlackMrkdwn` / `escapeSlackText` for the Slack rendition. The in-app topbar and `NotificationEmail.tsx` consume the segments directly. A fourth channel adds its rendition beside these, not in the fan-out job
- **`NotificationEvent.Workflow` is the payload-text kind** — every other event's content is read from its source document; this one carries `title` / `body` on the `carbon/notify` payload and reads nothing. Raised by the workflows notify action (`packages/jobs/src/workflows/actions/notify.ts`), topic `General`
- **inApp is always included** — regardless of caller-specified destinations
+- **Browser push mirrors inApp** — it is neither a `NotificationDestination` nor a `NotificationPreferenceChannel`: `notify` pushes every notification to every recipient's enabled browsers, with no per-topic switch
- **Single export**: `@carbon/notifications` barrel from `src/index.ts`
## Cross-References
diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.ts
index 10face956e..03d6066da8 100644
--- a/packages/notifications/src/index.ts
+++ b/packages/notifications/src/index.ts
@@ -100,7 +100,9 @@ export const USER_FACING_NOTIFICATION_TOPICS = [
NotificationTopic.Changelog
] as const satisfies readonly NotificationTopic[];
-// In-app is always delivered, so it is not a preference channel.
+// In-app is always delivered, so it is not a preference channel. Neither is
+// browser push: it mirrors in-app, every notification to every browser with
+// notifications enabled.
export type NotificationPreferenceChannel = "email" | "slack";
export function getNotificationTopicChannels(
@@ -154,7 +156,8 @@ export function isRecurringNotificationEvent(
// Fan-out targets understood by the notify Inngest function. inApp is
// always included regardless of what the caller passes — the topbar reflects
-// every notification. email and slack are opt-in extras.
+// every notification. email and slack are opt-in extras. Browser push is not
+// a destination: it follows in-app, so every notification pushes too.
export enum NotificationDestination {
InApp = "inApp",
Email = "email",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 07b3f623cf..910c0c1a04 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2853,6 +2853,9 @@ importers:
undici:
specifier: ^8.10.0
version: 8.10.0
+ web-push:
+ specifier: ^3.6.7
+ version: 3.6.7
zod:
specifier: 'catalog:'
version: 4.5.4
@@ -2866,6 +2869,9 @@ importers:
'@types/react':
specifier: 18.3.28
version: 18.3.28
+ '@types/web-push':
+ specifier: ^3.6.4
+ version: 3.6.4
pg:
specifier: 8.20.0
version: 8.20.0
@@ -10958,6 +10964,9 @@ packages:
resolution: {integrity: sha512-c/I8ZRb51j+pYGAu5CrFMRxqZ2ke4y2grEBO5AUjgSkSk+qT2Ea+OdWElz/OiMf5MNpn2b17kuVBwZLQJXzihw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-GnJmSr40H3RAnj0s34FNTcJi1hmWFV5KXugE0mYWnYhgTAHLJ/dJKAwDmvPJYMke0RplY2XE9LnM4hqSqKIjhQ==}
+
resolution: {integrity: sha512-wR87cgvxj3p6D0Crt1r5avwqffqPXUkNlnQ1mjU93G7gCuFjufZR4I6j8cz5g1F1tTYpfOOFvly+cmIQwL9wvw==}
@@ -11522,6 +11531,9 @@ packages:
resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==}
+
resolution: {integrity: sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==}
engines: {node: '>=12.0.0'}
@@ -11688,6 +11700,9 @@ packages:
resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}
+ resolution: {integrity: sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ==}
+
resolution: {integrity: sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==}
engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
@@ -13423,6 +13438,10 @@ packages:
resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}
engines: {node: '>= 0.8'}
+ resolution: {integrity: sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==}
+ engines: {node: '>=16'}
+
resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}
engines: {node: '>= 14'}
@@ -17424,6 +17443,11 @@ packages:
resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==}
+ resolution: {integrity: sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==}
+ engines: {node: '>= 16'}
+ hasBin: true
+
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
@@ -25745,6 +25769,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.19.7
+
dependencies:
'@types/node': 22.19.7
@@ -26412,6 +26440,13 @@ snapshots:
get-intrinsic: 1.3.0
is-array-buffer: 3.0.5
+ dependencies:
+ bn.js: 4.12.5
+ inherits: 2.0.4
+ minimalistic-assert: 1.0.1
+ safer-buffer: 2.1.2
+
dependencies:
pvtsutils: 1.3.6
@@ -26564,6 +26599,8 @@ snapshots:
inherits: 2.0.4
readable-stream: 3.6.2
+
dependencies:
bytes: 3.1.2
@@ -28662,6 +28699,8 @@ snapshots:
statuses: 2.0.2
toidentifier: 1.0.1
+
dependencies:
agent-base: 7.1.4
@@ -33558,6 +33597,16 @@ snapshots:
+ dependencies:
+ asn1.js: 5.4.1
+ http_ece: 1.2.0
+ https-proxy-agent: 7.0.6
+ jws: 4.0.1
+ minimist: 1.2.8
+ transitivePeerDependencies:
+ - supports-color
+