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.
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
- Task 1: Add the
pushSubscriptiontable and widen the preference channel - Task 2: Add the push channel to
@carbon/notifications - Task 3: Add the VAPID env vars to
@carbon/env - Task 4: Add the
carbon/send-pushevent to@carbon/lib - Task 5: Add the
send-pushjob - Task 6: Fan out push from
notify - Task 7: Add the ERP models and service functions
- Task 8: Add the
/api/push-subscriptionroute - Task 9: Add the service worker
push-worker.js - Task 10: Add the
usePushSubscriptionhook - Task 11: Add the device card and the Browser column to Account → Notifications
- Task 12: Unsubscribe on Sign Out
- Task 13: Extract and translate the new strings
- Task 14: Update the docs, the rules and the AGENTS.md files
- Task 15: Run the final gates
Dependencies
- Task 1 comes first. Every later task that reads
pushSubscriptionneeds 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-headersafter you create it. All new files in this plan are AGPL: none is underpackages/ee/and none has.ee.in its name. - Do not use JavaScript
Datefor arithmetic or formatting. For a timestamp to store, usedatetime.timestamp()from@carbon/utils, asnotify.tsdoes. - Do not use
Math.round,Math.ceil,Math.flooror.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(frompnpm db:migrate:new) - Modify:
packages/database/src/authz/manifest.ts— add thepushSubscriptionrule - Create:
packages/database/supabase/migrations/<timestamp>_authz-push-subscription.sql(fromauthz migration) - Copy from (precedent):
packages/database/supabase/migrations/20260714095112_notification-preferences.sqland thenotificationPreferencerule inmanifest.ts(line 1026)
Steps:
- Run
pnpm db:migrate:new push-subscription. - Write this SQL into the new file. It has no
CREATE POLICY, because the manifest owns the policies.
-- 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'));
- In
manifest.ts, add this rule in alphabetical order (after thepurchase*keys, beforequote*):
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"))
}),
- Run
pnpm db:migrate. It applies the migration and runsauthz sync. - Run
pnpm --filter @carbon/database authz migration push-subscription. - Run
pnpm run generate:types. - Run
pnpm --filter @carbon/database test -- migration.test. - 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:
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:
- Add
Push = "push"toenum NotificationDestination. Update the enum comment: push, email and slack are opt-in extras. - Change
NotificationPreferenceChannelto"email" | "slack" | "push". - In
getNotificationTopicChannels, make thedefaultarm return["email", "slack", "push"]. LeaveChangelogas["email"]. - Add this exported function below
getNotificationTopicChannels:
// 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
);
}
- Move the
NotificationDestinationenum abovewantsPushDeliveryif the compiler reports a use before definition. - In
push.test.ts, test 4 cases ofwantsPushDelivery:[InApp]→ false;[InApp, Email]→ true;[Slack]→ true;[Push]→ true. - Add 1 test:
getNotificationTopicChannels(NotificationTopic.Job)contains"push", andgetNotificationTopicChannels(NotificationTopic.Changelog)does not.
Verify:
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()inpackages/env/src/push.server.ts(@carbon/env/push.server) derives the pair fromSESSION_SECRET. See the spec's changelog.
Depends on: none Files:
- Modify:
packages/env/src/schema.ts— new grouppush, 3 vars - Modify:
packages/env/src/index.ts— export the 3 values andisPushConfigured() - Modify:
.env.example— a commented push block - Copy from (precedent): the
slackgroup inschema.ts(lines 308–338)
Steps:
- Add
"push"to theGroupunion inschema.ts. - Add
push: "Push notifications"toFEATURES. - Add this block after the
slackblock inschema:
// ── 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
},
- In
index.ts, nearERP_URL, add:
// 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);
}
- Do not add the vars to
getBrowserEnv(). The settings loader sends the public key (spec, Design Decisions). - 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:
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"inevents.ts(line 46)
Steps:
- In
events.ts, after"carbon/send-slack", add:
// Web Push events: one per pushSubscription row
"carbon/send-push": {
data: {
subscriptionId: string;
companyId: string;
title: string;
body: string;
url: string;
tag: string;
};
};
- In
trigger.ts, add"send-push": "carbon/send-push",after"send-slack".
Verify:
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— addweb-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.tsanddelivery-failure.ts/delivery-failure.test.tsin the same folder
Steps:
- Run
pnpm --filter @carbon/jobs add web-push. - Run
pnpm --filter @carbon/jobs add -D @types/web-push. - Create
push-outcome.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";
}
- In
push-outcome.test.ts, test 6 statuses: 201 → delivered, 404 → gone, 410 → gone, 413 → fail, 429 → retry, 503 → retry. - Create
send-push.ts. Copy the shape ofsend-slack.ts. The function:inngest.createFunction({ id: "send-push", retries: 3 }, { event: "carbon/send-push" }, …).- If
isPushConfigured()is false, return{ skipped: "push not configured" }. - In
step.run("load-subscription"), readid, endpoint, p256dh, authfrompushSubscriptionbyidandcompanyIdwithgetCarbonServiceRole(). If the read returns an error, throw it. - If no row exists, return
{ skipped: "subscription not found" }. - In
step.run("send-push"), callwebpush.sendNotification(...):
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!
}
}
);
- Catch the error. Read
statusCodefrom it:web-pushthrows aWebPushErrorwithstatusCode. If the error has nostatusCode, throw it again (a network error, so Inngest retries). - Map the status with
pushDeliveryOutcome. - If the outcome is
gone, return{ status: statusCode, gone: true }from the step. - If the outcome is
retry, throw anErrorthat names the status. - If the outcome is
fail, thrownew NonRetriableError(...)with the status and the response body. - On success, return
{ status: result.statusCode }. - If the send step returned
gone: true, runstep.run("delete-subscription"). It deletes the row byidandcompanyIdwith the service role. If the delete returns an error, throw it. - Import the VAPID values and
isPushConfiguredfrom@carbon/env. - Export
sendPushFunctionfromnotifications/index.ts. - Import
sendPushFunctioninpackages/jobs/src/inngest/index.ts. Add it to the functions list next tosendSlackFunction(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:
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:
- Import
isPushConfiguredfrom@carbon/envandwantsPushDeliveryfrom@carbon/notifications. - After
const wantsSlack = …, add:
// 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);
- Change the condition of the step
filter-recipients-by-preferencetowantsEmail || wantsSlack || wantsPush. - In that step, change
mutedFor's parameter type toNotificationPreferenceChannel(import it from@carbon/notifications). - In that step, compute
const pushMuted = mutedFor("push");. - In that step, also return
pushRecipientIds: userIds.filter((id) => !pushMuted.has(id)). - In the fallback object, add
pushRecipientIds: userIds. DestructurepushRecipientIdswith the other 2. - 🛑 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. - After the Slack fan-out block, add the push fan-out:
// ---- 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);
}
}
- Update the comment above
defaultDestinations: push also goes to every event that has Email or Slack.
Verify:
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):
notificationPreferenceValidatorandupsertNotificationPreferencein the same files
Steps:
- In
account.models.ts, changenotificationPreferenceValidator.channeltoz.enum(["email", "slack", "push"]). - In
account.models.ts, add:
// 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()
});
- In
account.service.ts, change thechanneltype ofupsertNotificationPreferencetoNotificationPreferenceChannel(from@carbon/notifications). - In
account.service.ts, add 3 functions with a one-line doc comment and NO@mcptag:
/** 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);
}
- Import
datetimefrom@carbon/utilsif the file does not already import it.
Verify:
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— addpushSubscription: \${api}/push-subscription`next tomessagingNotify` (line 217) - Copy from (precedent):
apps/erp/app/routes/api+/messaging.notify.ts
Steps:
- Export only an
action. The route has no loader and no default export. - Call
requirePermissions(request, {}). Readclient,userIdandcompanyId. - If
isPushConfigured()is false, returndata({ error: "Push is not configured" }, { status: 404 }). - If
request.method === "PUT":- Parse
await request.json()withpushSubscriptionValidator.safeParse. If it fails, return status 400. - If
oldEndpointis set, calldeletePushSubscription(client, { userId, companyId, endpoint: oldEndpoint }). - With
getCarbonServiceRole(), delete thepushSubscriptionrows whereendpointequals the new endpoint anduserIdis not this user. This step stops a shared browser from getting the previous user's notifications. - Call
upsertPushSubscription(client, { userId, companyId, endpoint, p256dh: keys.p256dh, auth: keys.auth, userAgent: request.headers.get("user-agent") }). - If any call returns an error, return status 500 with
{ error: message }. - Return
{ id }.
- Parse
- If
request.method === "DELETE":- Parse the body with
pushSubscriptionEndpointValidator. If it fails, return status 400. - Call
deletePushSubscription. If it returns an error, return status 500. - Return
{ ok: true }.
- Parse the body with
- If
request.method === "POST":- Parse the body with
pushSubscriptionEndpointValidator.extend({ intent: z.literal("test") }). If it fails, return status 400. - Call
getPushSubscription. If no row exists, return status 404. - Set
titleto "Carbon" andbodyto "Push notifications work on this device." - Set
urlto`${getAppUrl()}${path.to.notificationSettings}`. ImportgetAppUrlfrom@carbon/env. - Call
trigger("send-push", { subscriptionId: row.id, companyId, title, body, url, tag: "carbon-test" }). - Return
{ ok: true }.
- Parse the body with
- For any other method, return status 405.
- Import
triggerfrom@carbon/jobs, asmessaging.notify.tsdoes.
Verify:
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; usepnpm --filter @carbon/checks license-headers)
Steps:
- Write the file with 3 listeners and no
fetchlistener:
// 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 })
});
})()
);
});
- Run
pnpm --filter @carbon/checks license-headers.
Verify:
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:
- In
push.ts, exporturlBase64ToUint8Array(base64Url: string): Uint8Array:- Pad the string with
=to a length that is a multiple of 4. - Replace
-with+and_with/. - Decode with
atob, then copy each char code into aUint8Array.
- Pad the string with
- In
push.test.ts, test 2 cases:"AQID"→[1, 2, 3], and"-_8"→[251, 255]. - In
usePushSubscription.ts, exporttype PushState = "loading" | "unsupported" | "denied" | "off" | "on". - Export
usePushSubscription({ publicKey }: { publicKey: string | null }). It returns{ state, busy, turnOn, turnOff, sendTest }. - On mount (
useEffect), compute the state:- If
publicKeyis null, setunsupported. - If
"serviceWorker" in navigator,"PushManager" in windowor"Notification" in windowis false, setunsupported. - If
Notification.permission === "denied", setdenied. - Call
navigator.serviceWorker.getRegistration("/"). Readregistration?.pushManager.getSubscription(). - If no subscription exists, set
off. - If a subscription exists,
PUTit topath.to.api.pushSubscription. This step re-syncs the row for the current company. If the response is OK, seton. Else setoff.
- If
turnOn():- Call
Notification.requestPermission(). If the result isdenied, setdeniedand return. If it isdefault, return. - Call
navigator.serviceWorker.register("/push-worker.js", { scope: "/" }). - Await
navigator.serviceWorker.ready. - Call
pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(publicKey) }). PUTsubscription.toJSON()as JSON.- If the response is OK, set
on. Else callsubscription.unsubscribe(), setoff, and showtoast.error.
- Call
turnOff():- Read the current subscription. If none exists, set
offand return. - Send
DELETEwith{ endpoint }. - Call
subscription.unsubscribe(). - Set
off.
- Read the current subscription. If none exists, set
sendTest(): sendPOSTwith{ endpoint, intent: "test" }. If the response is OK, showtoast.success. Else showtoast.error.- Set
busyto true whileturnOn,turnOfforsendTestruns. - Wrap each action in
try/catch. Log withlogger.errorand showtoast.erroron failure. - Use
toastfrom@carbon/react. UseuseLinguifor the toast text. - Also export
unsubscribeThisDevice(): Promise<void>(not a hook). It reads the current subscription, sendsDELETE, and callsunsubscribe(). It never throws. Task 12 uses it.
Verify:
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
CardandSwitchcells;Buttonfrom@carbon/react
Steps:
- In the loader, add
push: isPushConfigured() ? { publicKey: VAPID_PUBLIC_KEY as string } : nullto the returned object. - In the component, read
pushfromuseLoaderData. - Call
usePushSubscription({ publicKey: push?.publicKey ?? null }). - If
pushis not null, render a secondCardabove the topic card:CardTitle: "This device".CardDescriptionand 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 |
- Set
isDisabled={busy}on each button. - Change the
Channelcells:- If
pushis not null, add a header cell Browser after Slack. - If
pushis not null, addcell("push", t\browser`)` after the Slack cell.
- If
- If
pushis 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. - Keep the existing
isEnabled,isPendingandtogglecode. It already works for any channel.
Verify:
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:
- Import
useSubmitfromreact-routerandunsubscribeThisDevicefrom~/hooks/usePushSubscription. - Add an
onSubmithandler to the Sign Out<Form>:- Call
event.preventDefault(). - Read the form element from
event.currentTarget. await Promise.race([unsubscribeThisDevice(), wait(1000)]).waitis a local promise that resolves after 1 000 ms withsetTimeout.- Call
submit(form).
- Call
- Keep the
method="post"andaction={path.to.logout}attributes, so the form still works if the script fails.
Verify:
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:
- Run
pnpm run lingui:extractfrom the repo root. - Run the
/translateskill to fill the emptymsgstrentries.
Verify:
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— asend-pushrow next to the other notification functions - Modify:
packages/notifications/AGENTS.md— thePushdestination andwantsPushDelivery - Modify:
.claude/rules/environment-configuration.md— thepushgroup
Steps:
- Use the
carbon-docsskill for the 3 docs pages. Ground each claim in the code from Tasks 1–12. - 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. - In
notifications.mdx, add push as a channel. Say that push follows email and Slack, and that push needs the VAPID env vars. - In
environment-variables.mdx, add the 3<EnvVar>entries next to the SMTP or Slack entries. Copy the descriptions fromschema.ts. - In
packages/jobs/AGENTS.md, addsend-pushwith the triggercarbon/send-pushand the 404/410 delete rule.
Verify:
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:
- Run each command below. Fix each failure before you continue.
- Update the spec status to
in-progressand add a changelog line for each divergence from the spec. - Write the manual browser checklist into the run record (the run skipped
/test):- 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.) - Open Account → Notifications, click Turn on, and allow the prompt.
- Click Send a test notification. Expect an OS notification. Click it and expect Account → Notifications.
- Close every Carbon tab. Assign a job to the user from a second account. Expect "Job assigned to you".
- Turn off the Jobs Browser switch. Assign another job. Expect no push and a new bell row.
- Click Turn off. Expect 0
pushSubscriptionrows for the user.
- Restart the ERP and the Inngest dev server. (Originally: set the 3 VAPID vars. Since 2026-10-09 the pair is derived from
Verify:
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.