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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: maintenance mode, announcement bar, and deploy chained on image builds (#1919)
Sida437b9cf62e9
diff --git a/.ai/plans/2026-10-13-maintenance-mode-and-announcements.md b/.ai/plans/2026-10-13-maintenance-mode-and-announcements.mdnew file mode 100644index 0000000000..9b90cff730--- /dev/null+++ b/.ai/plans/2026-10-13-maintenance-mode-and-announcements.md@@ -0,0 +1,144 @@+# Maintenance mode + announcement bar++## Context++Carbon has no way to take the apps offline cleanly (a deploy or database+migration just produces errors) and no way to tell signed-in users something+("maintenance at 22:00 UTC", "new release"). Nothing like either exists in the+repo today — no banner in either shell, no version check, no phone-home.++Two features, deliberately independent:++1. **Maintenance mode** — an env flag that makes every app answer 503 with a+ maintenance screen.+2. **System status + announcement** — the app fetches a remote JSON document+ (latest version, announcement, …) and shows the announcement as a bar at the+ top of the shell.++Decisions already made with the user:++- Remote payload is hosted by us elsewhere; this work builds only the consumer and the contract.+- No phone-home by default: the fetch happens only when the URL variable is set. Cloud sets it; self-hosters may opt in.+- Maintenance blocks everything except `/health` (API, MCP, webhooks, Inngest all get 503 so providers retry).+- Dismissal is per browser (localStorage), keyed by announcement id and user.++On execution, copy this plan to `.ai/plans/2026-10-13-maintenance-mode-and-announcements.md` (repo convention).++## Part 1 — Maintenance mode++**Env:** `MAINTENANCE_MODE` (boolean, server-only, default false). Same shape as+the existing `CONTROLLED_ENVIRONMENT = parseBoolean(getEnv(...), false)` in+`packages/env/src/index.ts:116`. Server-only keeps it out of `getBrowserEnv()`+and the four root-loader `env` objects.++**Gate:** new `packages/auth/src/middleware/maintenance.server.ts`, next to+`security.server.ts`, exporting `maintenanceMiddleware`:++- flag off → `next()`+- `/health` → `Response.json({ status: "maintenance" })` with 200, without probing the database. The ALB and the Swarm healthcheck need a 2xx; the normal health route returns 503 when the database is down, which would make ECS kill tasks in a loop during a migration.+- anything else → `throw data({ message: "maintenance" }, { status: 503, headers: { "Retry-After": "300" } })`++Throwing (not returning) gives three behaviours from one line: a document+request renders the root `ErrorBoundary`, a client navigation (`.data`) surfaces+the same boundary in an already-open tab, and a resource route (`api+`,+webhooks, Inngest) returns the bare 503.++**Wire it** after `security` in each root `middleware` (so the CSP nonce and+security headers still apply): `apps/erp/app/root.tsx:75`,+`apps/mes/app/root.tsx:74`, `apps/academy/app/root.tsx:50`,+`apps/starter/app/root.tsx`.++**Screen:** add a 503 case to `resolveConfig` in+`packages/react/src/ErrorBoundary/RootErrorBoundary.tsx` (it already maps 404 /+other / 500 to `ErrorScreen` props): "Carbon is down for maintenance", a single+`retry` action, no "return home". Reuses the existing design; assets are served+ahead of the React Router catch-all (`packages/serve/src/index.ts:166`, Vercel+CDN), so the page styles load.++**Logging:** `handleError` in `apps/{erp,mes}/app/entry.server.tsx` logs every+5xx; return early when `MAINTENANCE_MODE` is on so a maintenance window does not+log an error per request.++**First execution step is a spike:** confirm a Response thrown from root+middleware renders the root ErrorBoundary with status 503 for documents and+`.data` requests. If React Router does not do that, fall back to *returning* a+small self-contained HTML 503 for `Accept: text/html` and JSON otherwise — same+file, nothing else in the plan changes.++**Operational note:** an env change only takes effect on restart — a redeploy on+Vercel, a service update on ECS, a `docker service update` on self-host. That is+minutes, not instant.++## Part 2 — System status and announcement bar++**Env:** `SYSTEM_STATUS_URL` (string, server-only, optional). Unset → no fetch,+endpoint returns `null`, no bar. No URL is hardcoded for Cloud, because the host+does not exist yet; Cloud sets the variable in its deployment env.++**Contract** (the remote must return this; zod schema in a client-safe file):++```ts+{+ latestVersion?: string,+ announcement?: {+ id: string, // changes → bar reappears for everyone+ message: string, // plain text, rendered as text+ severity?: "info" | "warning" | "critical", // default "info"+ href?: string, // http(s) only+ linkLabel?: string,+ dismissible?: boolean // default true+ } | null+}+```++`latestVersion` is parsed and returned but drives no UI: Carbon has no app+version to compare it against (no `version` field anywhere, only commit SHAs).++**Server:** `packages/lib/src/system-status.server.ts` → `getSystemStatus()`+(`@carbon/lib` already depends on `@carbon/kv` and both apps import it):++- no URL → `null`+- Redis `system-status`, TTL 300 s — same get/parse/`set EX` pattern as `getCachedChangelogPanelEntry` (`apps/erp/app/modules/account/account.server.ts:12`)+- `fetch(url, { signal: AbortSignal.timeout(3000) })`, `safeParse`; any failure logs a warning, caches `null` for 60 s and returns `null`. A dead remote must never slow or break the app.++**Endpoint:** `apps/erp/app/routes/api+/system-status.ts` and the same file in+`apps/mes`: require a session, return `getSystemStatus()`, export+`clientLoader = cachedClientLoader<typeof loader>({ staleTime: 5 min })`. Add+`path.to.api.systemStatus` to each app's `path.ts`.++**UI:**++- `packages/react/src/AnnouncementBar.tsx` — presentational (`announcement`, `onDismiss`), severity mapped to the existing `Alert` variants (`info` / `warning` / `destructive`), `IconButton` with `aria-label` for dismiss, link opens in a new tab. Exported from the barrel (an added export; `packages/react/AGENTS.md` lists barrel changes as ask-first — covered by approving this plan).+- Per app, a small `useAnnouncement()` hook: `useLoaderQuery(path.to.api.systemStatus)` + `useLocalStorage` (`packages/react/src/hooks/useLocalStorage.ts`) under `announcement-dismissed:<userId>` holding the dismissed id.+- Placement (changed during the build): the bar sits inside each shell's content card — under the Topbar / mobile app bar in the ERP, above the page in MES — not above the whole shell. The nav rail and ~118 ERP pages size themselves from `100dvh`; while shown the bar sets `--announcement-height` on `<html>`, the ERP's `--content-inset` includes it, and the four MES viewport-sized pages subtract it.++## Env registration (both variables)++Traced from `CARBON_EDITION`; server-only variables skip the browser sites.++- `packages/env/src/schema.ts`, `packages/env/src/index.ts`+- `.env.example`, `contrib/deploying/simple-docker-caddy/{.env.example,docker-compose.prod.yml}` (ERP + MES)+- `sst.config.ts` (ERP ~:58, MES ~:171). `ci/src/deploy.ts` is not changed: its values come from `workspaces` columns, and neither variable has one+- Docs: `.claude/rules/environment-configuration.md`, `.claude/rules/sst-deployment-infrastructure.md` (also fix its stale claim that ERP's health route is under `_public+/`), `packages/env/AGENTS.md`, `packages/react/AGENTS.md` (503 case + `AnnouncementBar`)++## Left out on purpose++- Announcement scheduling (`startsAt`/`endsAt`), per-company targeting, rich text — the host decides what it serves; add fields when there is a need.+- "Update available" UI — needs an app version first.+- Staff bypass during maintenance, custom maintenance message env.+- Announcements on login / public share pages — shell only.+- Driving maintenance from the remote payload (would make it instant with no redeploy, but adds a Redis read to every request). Worth revisiting if redeploy latency hurts.++## Verification++1. Tests: one for `maintenanceMiddleware` (off → passes through; on → `/health` 200, other path throws 503 with `Retry-After`), one for the schema + `getSystemStatus` (bad JSON / timeout → `null`; `javascript:` href rejected).+2. `pnpm --filter @carbon/checks license-headers` for new files; `pnpm run lint`; typecheck one package at a time with `--concurrency=1`: `@carbon/env`, `@carbon/auth`, `@carbon/lib`, `@carbon/react`, `erp`, `mes`.+3. Maintenance, against the running dev stack with `MAINTENANCE_MODE=true`: `command curl -i` on `/` (503 HTML + `Retry-After`), `/api/v1/...` and `/api/inngest` (503), `/health` (200); in the browser, the maintenance screen on a fresh load and on a client navigation from an already-open tab; then flag off → app normal.+4. Announcement: serve a JSON file locally, set `SYSTEM_STATUS_URL`, check the bar in ERP and MES at each severity, dismiss → gone after reload, change `id` → back, `dismissible: false` → no close button; stop the JSON server → no bar, no errors, page load not slowed. Screenshot desktop + phone widths with the bar on and off to confirm nothing in the shell clips or double-scrolls.++## Status (2026-10-13)++- [x] Maintenance mode: built; tests, typecheck and a live ERP dev server with the flag on (503 page, 503 `.data`, 503 API with `Retry-After`, 200 `/health`)+- [x] System status fetch, endpoint, bar: built; tests and typecheck+- [ ] Announcement bar in the browser, ERP and MES, desktop and phone — needs the dev stack and a `SYSTEM_STATUS_URL`+- [ ] `Retry-After` is on resource-route 503s only; React Router drops the thrown headers on the document and `.data` responsesdiff --git a/.claude/rules/agent-knowledge-base.md b/.claude/rules/agent-knowledge-base.mdindex bd23beb5ea..5dcaf6c1b3 100644--- a/.claude/rules/agent-knowledge-base.md+++ b/.claude/rules/agent-knowledge-base.md@@ -25,8 +25,8 @@ renamed) so ERP's `^build` never runs the Next docs build.There is no generator and no committed copy: a docs edit reaches the agent at the next ERPbuild, and in dev immediately (Vite watches the glob). The ERP Docker image copies-`docs/content` into its build stage (`.dockerignore` re-includes it), and `deploy.yml` fires on-`docs/content/**`, so a glossary or docs change redeploys ERP/MES.+`docs/content` into its build stage (`.dockerignore` re-includes it), and `build-images.yml`+deploys when a push touches `docs/content/**`, so a glossary or docs change redeploys ERP/MES.All three machine-readable consumers strip MDX through the one `stripComponents` in`src/corpus.ts`, so the agent, llms.txt and anything else can never disagree about a page.diff --git a/.claude/rules/environment-configuration.md b/.claude/rules/environment-configuration.mdindex 6e63e2dd90..cc5fa1900c 100644--- a/.claude/rules/environment-configuration.md+++ b/.claude/rules/environment-configuration.md@@ -152,6 +152,24 @@ vars through `ci/src/deploy.ts` → `sst.config.ts` → the ERP service only.`CarbonEdition`), `CONTROLLED_ENVIRONMENT` (ITAR flag), `DEFAULT_LANGUAGE`(default `en`), `GTM_URL`, `GTM_EVENTS_API_SECRET_KEY`.+**Maintenance and status (both optional, server-only)** — `MAINTENANCE_MODE=true`+makes `maintenanceMiddleware` (`@carbon/auth/middleware/maintenance.server`, in+every app's root `middleware`, after `security`) answer every request with a 503:+a page renders the root ErrorBoundary's 503 screen, an open tab gets the same+screen on its next navigation, and a resource route (API, MCP, webhooks,+`/api/inngest`) returns a bare 503 with `Retry-After: 300` so the caller retries.+`/health` answers 200 `{ status: "maintenance" }` without probing the database,+so the load balancer keeps the tasks. The flag is read at start: changing it+needs a restart or redeploy. `SYSTEM_STATUS_URL` is a JSON document the app+reads for `{ latestVersion?, announcement? }` (`systemStatusValidator`,+`@carbon/lib/system-status`); unset means no request is made, on any edition.+`getSystemStatus()` caches it in Redis for 5 minutes (a failure for 1), each+app serves it at `api+/system-status`, and the shell shows the announcement+with `AnnouncementBar` (`@carbon/react`). `latestVersion` is returned but not+shown — Carbon has no version to compare it with. Neither variable is on the+`workspaces` row, so `ci/src/deploy.ts` does not set them; `sst.config.ts`+forwards them from the deploying process's environment.+**Tracing (all optional)** — the standard OpenTelemetry variables, read raw bythe OTel SDK (not `@carbon/env`): `OTEL_EXPORTER_OTLP_ENDPOINT` (or`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) turns server tracing on,diff --git a/.claude/rules/sst-deployment-infrastructure.md b/.claude/rules/sst-deployment-infrastructure.mdindex f73c04f648..4e8ad1e55d 100644--- a/.claude/rules/sst-deployment-infrastructure.md+++ b/.claude/rules/sst-deployment-infrastructure.md@@ -4,6 +4,7 @@ paths:- "sst.config.ts"- "ci/**"- ".github/workflows/deploy.yml"+ - ".github/workflows/build-images.yml"- ".github/workflows/inngest.yml"- "Dockerfile"- "apps/erp/app/utils/inngest-self-sync.server.ts"@@ -47,19 +48,30 @@ alternative deployment, not a replacement. Both build from the same root `Docker- `sst-env.d.ts` files (repo root, `ci/`, per app/package) are SST-generated typestubs; do not hand-edit.-## Images (`.github/workflows/deploy.yml`, job `images`)-Triggers on push to `main` touching `apps/erp/**`, `apps/mes/**`, `packages/**`,-`docs/content/**` (or manual `workflow_dispatch`).-- `deploy.yml` builds nothing. `build-images.yml` runs on the same push and- publishes `carbon/erp` and `carbon/mes` tagged with the commit sha to- `vars.IMAGE_REGISTRY`; the `images` job polls until both tags exist (30 minute- limit), so a failed image build fails the deploy.+## Images, then deploy (`.github/workflows/build-images.yml`)+Every push to `main` runs `build-images.yml`, which builds or re-tags every image+for the commit (`carbon/<image>:<sha>` in `vars.IMAGE_REGISTRY`). The deploy is a+job of that same run, chained with `needs:` — there is no polling:+- `apps` builds `carbon/erp` and `carbon/mes`; `services` builds `bootstrap`,+ `edge-functions` and `assembler` with the same steps (a YAML anchor). Split so+ the deploy needs only the app images: a failed assembler build does not hold+ back a release.+- `changes` diffs `github.event.before..sha` over `apps/erp`, `apps/mes`,+ `packages`, `docs/content`; a new branch or force-push (no usable `before`)+ counts as changed. A manual run of `build-images.yml` never deploys.+- `deploy` (`needs: [apps, changes]`) calls `deploy.yml` (`workflow_call`,+ `secrets: inherit`). A failed or cancelled app image skips it at once.+- Image concurrency is per image and per job (`build-images-<image>`), not per+ workflow, so a deploy still running does not hold up the next commit's builds.- The services pull `${IMAGE_REGISTRY}/carbon/<app>:${IMAGE_TAG}`. With`IMAGE_REGISTRY` unset `sst.config.ts` falls back to the workspace account'sprivate ECR (`${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com`), which iswhat a deployment that builds its own images uses.-## Deploy (job `deploy`, needs `images`)+## Deploy (`deploy.yml`, `workflow_call` + `workflow_dispatch`)+- Run by hand, it deploys the commit it is run on, whose images must already exist.+- One deploy at a time (`concurrency: deploy-apps`); a newer commit waiting+ replaces an older one that had not started.- Sets `IMAGE_TAG: ${{ github.sha }}` (this is what `sst.config.ts` interpolatesinto the ECR image ref — so prod runs the exact SHA, not `:latest`).- Installs Pulumi `3.212.0` (SST v3 uses Pulumi under the hood), `pnpm install@@ -102,7 +114,8 @@ registration handshake, not Carbon-specific. Two independent triggers exist:path (`server/app.ts`, `@vercel/react-router` in `entry.server.tsx`) isstill live, so this stays inert there rather than retrying uselessly.- **CI-triggered sync** (`.github/workflows/inngest.yml`, `ci/src/jobs.ts`):- runs after "Deploy Apps" succeeds on `main`. Reads every row in the+ called by `deploy.yml` (job `sync`) after its deploy job succeeds; also+ runnable by hand. Reads every row in the`workspaces` table and does the same `PUT .../api/inngest` against each`url_erp`. Redundant with boot self-sync today, but kept as anexternally-triggered backstop (e.g. if a task's own retries were exhausted@@ -140,8 +153,10 @@ OAuth state uses the already-required `SESSION_SECRET`, so there is no extra Ramsecret to provision.## /health-`apps/{erp,mes}/app/routes/_public+/health.tsx` — used by the ECS/ALB health checks-(`/health`, HTTP). Same endpoint the compose stack uses.+`apps/erp/app/routes/health.ts` and `apps/mes/app/routes/_public+/health.tsx` — used+by the ECS/ALB health checks (`/health`, HTTP). Same endpoint the compose stack uses.+With `MAINTENANCE_MODE=true` the route is not reached: `maintenanceMiddleware`+answers `/health` with 200 so tasks are not replaced during the maintenance.## Notes / gotchas- `npm run deploy` (root) = `turbo run deploy`; real prod deploy goes through CI →diff --git a/.env.example b/.env.exampleindex 9f2766b874..79b900b05e 100644--- a/.env.example+++ b/.env.example@@ -11,6 +11,8 @@ AUTH_PROVIDERS="email,google,passkey" # "email" | "google" | "azure" | "passkey"CARBON_EDITION="community" # "community" | "cloud" | "enterprise"SESSION_SECRET="************************"RATE_LIMIT="5"+# MAINTENANCE_MODE="true" # every request except /health answers 503 with a maintenance screen; needs a restart+# SYSTEM_STATUS_URL="https://example.com/status.json" # optional; { latestVersion?, announcement? } shown as a bar in the app# LOG_LEVEL="debug" # trace|debug|info|warning|error|fatal — optional; default dev=debug, prod=info, browser prod=warning# Server tracing (OpenTelemetry) — optional; off unless an OTLP endpoint is set. Any OTLP backend works; Axiom shown.# OTEL_EXPORTER_OTLP_ENDPOINT="https://api.axiom.co"diff --git a/.github/workflows/build-images.yml b/.github/workflows/build-images.ymlindex d4d0eedacc..7c7c1006d8 100644--- a/.github/workflows/build-images.yml+++ b/.github/workflows/build-images.yml@@ -18,11 +18,6 @@ on:branches: [main]workflow_dispatch:-# Serial, so each run finds the previous commit's tags already written.-concurrency:- group: build-images- cancel-in-progress: false-permissions:contents: readid-token: write@@ -32,15 +27,24 @@ env:REGISTRY: ${{ vars.IMAGE_REGISTRY }}jobs:- image:+ # erp and mes are their own job so the deploy can need exactly them: a+ # failed assembler image does not hold back an app release. Both jobs run+ # the same steps (the anchor below).+ apps:name: carbon/${{ matrix.image }}if: vars.IMAGE_REGISTRY != ''runs-on: ubuntu-24.04+ # Serial per image, so each run finds the previous commit's tag already+ # written. Per job rather than per workflow, so a deploy still running in+ # this run does not hold up the next commit's images.+ concurrency:+ group: build-images-${{ matrix.image }}+ cancel-in-progress: falsestrategy:fail-fast: falsematrix:- image: [erp, mes, bootstrap, edge-functions, assembler]- steps:+ image: [erp, mes]+ steps: &image-steps- uses: actions/checkout@v7with:fetch-depth: 2@@ -127,3 +131,54 @@ jobs:# No layer cache. An image is only built when its files changed,# which invalidates every layer after the base; exporting one took# about 95 seconds a build and one trivial layer was ever reused.++ services:+ name: carbon/${{ matrix.image }}+ if: vars.IMAGE_REGISTRY != ''+ runs-on: ubuntu-24.04+ concurrency:+ group: build-images-${{ matrix.image }}+ cancel-in-progress: false+ strategy:+ fail-fast: false+ matrix:+ image: [bootstrap, edge-functions, assembler]+ steps: *image-steps++ # Whether this push changed anything the apps are built from. Runs beside+ # the builds; a manual run of this workflow never deploys.+ changes:+ name: Deployable changes+ if: github.event_name == 'push' && vars.IMAGE_REGISTRY != ''+ runs-on: ubuntu-24.04+ outputs:+ deploy: ${{ steps.diff.outputs.deploy }}+ steps:+ - uses: actions/checkout@v7+ - id: diff+ env:+ BEFORE: ${{ github.event.before }}+ SHA: ${{ github.sha }}+ run: |+ # A new branch or a force-push leaves no usable BEFORE: deploy.+ if [[ $BEFORE =~ ^0+$ ]] || ! git fetch --quiet --depth=1 origin "$BEFORE"; then+ echo "deploy=true" >> "$GITHUB_OUTPUT"+ # The erp/mes inputs of .github/scripts/build-images.sh, plus the+ # docs the ERP bundles: a lockfile-only push rebuilds the images too.+ elif git diff --quiet "$BEFORE" "$SHA" -- Dockerfile .dockerignore \+ package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc turbo.json \+ lingui.config.js apps/erp apps/mes packages patches scripts docs/content; then+ echo "deploy=false" >> "$GITHUB_OUTPUT"+ else+ echo "deploy=true" >> "$GITHUB_OUTPUT"+ fi++ # Starts only once carbon/erp and carbon/mes exist for this commit, and is+ # skipped outright when either failed or was cancelled — a dependency, not+ # a poll, so it can never sit waiting for images that will not come.+ deploy:+ name: Deploy+ needs: [apps, changes]+ if: needs.changes.outputs.deploy == 'true'+ uses: ./.github/workflows/deploy.yml+ secrets: inheritdiff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.ymlindex edb5df15ed..a55e60ff50 100644--- a/.github/workflows/deploy.yml+++ b/.github/workflows/deploy.yml@@ -1,55 +1,21 @@name: Deploy Apps+# Called by build-images.yml once this commit's carbon/erp and carbon/mes+# images are pushed. Run by hand, it deploys the images of the commit it is+# run on, which must already exist.on:- push:- branches:- - main- paths:- - "apps/erp/**"- - "apps/mes/**"- - "packages/**"- - "docs/content/**"+ workflow_call:workflow_dispatch:-jobs:- # The images come from build-images.yml, which runs on the same push. This- # waits for that run rather than building them a second time. It watches the- # run, not the registry: polling public.ecr.aws anonymously from a shared- # runner IP can be refused for the life of the runner, which looked exactly- # like an image that never arrived, and a build that failed or was cancelled- # left this waiting out its whole timeout.- images:- name: Wait for images- runs-on: ubuntu-latest- timeout-minutes: 30- permissions:- actions: read- steps:- - name: Wait for carbon/erp and carbon/mes- env:- GH_TOKEN: ${{ github.token }}- GH_REPO: ${{ github.repository }}- REGISTRY: ${{ vars.IMAGE_REGISTRY }}- SHA: ${{ github.sha }}- run: |- [ -n "$REGISTRY" ] || { echo "vars.IMAGE_REGISTRY is not set" >&2; exit 1; }- until run=$(gh run list --workflow build-images.yml --commit "$SHA" --limit 1 \- --json databaseId --jq '.[0].databaseId // empty') && [ -n "$run" ]; do- echo "waiting for Build images to start on $SHA"- sleep 15- done- echo "Build images run: $GITHUB_SERVER_URL/$GH_REPO/actions/runs/$run"- gh run watch "$run" --interval 15 > /dev/null- for app in erp mes; do- conclusion=$(gh run view "$run" --json jobs \- --jq ".jobs[] | select(.name == \"carbon/$app\") | .conclusion")- echo "carbon/$app: ${conclusion:-missing}"- [ "$conclusion" = success ] || exit 1- done+jobs:deploy:name: Deployruns-on: ubuntu-latest- needs: images+ # One deploy at a time. A newer commit waiting replaces an older one that+ # had not started yet: it deploys the newer images anyway.+ concurrency:+ group: deploy-apps+ cancel-in-progress: falseenv:IMAGE_REGISTRY: ${{ vars.IMAGE_REGISTRY }}@@ -84,3 +50,10 @@ jobs:- name: Run deploymentrun: pnpm --filter ci ci:deploy++ # Inngest learns the new function list once the new tasks serve it.+ sync:+ name: Sync Inngest+ needs: deploy+ uses: ./.github/workflows/inngest.yml+ secrets: inheritdiff --git a/.github/workflows/inngest.yml b/.github/workflows/inngest.ymlindex aabaa0ede7..b29764d8b8 100644--- a/.github/workflows/inngest.yml+++ b/.github/workflows/inngest.yml@@ -1,21 +1,14 @@name: Sync Inngest Functionson:- # Run after the Deploy Apps workflow completes- workflow_run:- workflows: ["Deploy Apps"]- types:- - completed- branches:- - main+ # Called by deploy.yml after a successful deploy.+ workflow_call:workflow_dispatch:jobs:sync:name: Sync Inngestruns-on: ubuntu-latest- # Only run if the triggering workflow succeeded (or if manually/push triggered)- if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}steps:- name: Checkout codediff --git a/apps/academy/app/root.tsx b/apps/academy/app/root.tsxindex 3e376137a0..ae397d73e8 100644--- a/apps/academy/app/root.tsx+++ b/apps/academy/app/root.tsx@@ -11,6 +11,7 @@ import {flashResultContext} from "@carbon/auth/middleware/flash.server";import { formBodyMiddleware } from "@carbon/auth/middleware/form-body.server";+import { maintenanceMiddleware } from "@carbon/auth/middleware/maintenance.server";import { securityMiddleware } from "@carbon/auth/middleware/security.server";import { getOrRefreshAuthSession } from "@carbon/auth/session.server";import { requestIdMiddleware } from "@carbon/logger/middleware.server";@@ -50,6 +51,7 @@ import { path } from "./utils/path";export const middleware = [requestIdMiddleware,securityMiddleware,+ maintenanceMiddleware,formBodyMiddleware,flashMiddleware];diff --git a/apps/erp/app/entry.server.tsx b/apps/erp/app/entry.server.tsxindex cf6d19955d..db7d3d483d 100644--- a/apps/erp/app/entry.server.tsx+++ b/apps/erp/app/entry.server.tsx@@ -2,7 +2,7 @@// 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 { POSTHOG_API_HOST, SUPABASE_URL } from "@carbon/auth";+import { MAINTENANCE_MODE, POSTHOG_API_HOST, SUPABASE_URL } from "@carbon/auth";import { installFormBodyGuard } from "@carbon/auth/middleware/form-body.server";import {getNonce,@@ -147,6 +147,8 @@ export function handleError() {// Client navigated away / cancelled mid-flight — not a real failure.if (request.signal.aborted) return;+ // Every request is a 503 during maintenance; that is not a failure to log.+ if (MAINTENANCE_MODE) return;// Redirects and intentional Response throws are control flow, not errors.if (error instanceof Response && error.status < 500) return;if (isRouteErrorResponse(error) && error.status < 500) return;diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsxindex 87485d0c8e..b2d8c2cf8f 100644--- a/apps/erp/app/root.tsx+++ b/apps/erp/app/root.tsx@@ -11,6 +11,7 @@ import {flashResultContext} from "@carbon/auth/middleware/flash.server";import { formBodyMiddleware } from "@carbon/auth/middleware/form-body.server";+import { maintenanceMiddleware } from "@carbon/auth/middleware/maintenance.server";import { securityMiddleware } from "@carbon/auth/middleware/security.server";import { validator } from "@carbon/form";import { LocaleProvider, resolveLanguage } from "@carbon/locale";@@ -76,6 +77,8 @@ export const middleware = timedMiddleware({// First: the request scope (context, request id, access log).request: requestMiddleware,security: securityMiddleware,+ // After security, so the 503 still carries the nonce and security headers.+ maintenance: maintenanceMiddleware,formBody: formBodyMiddleware,flash: flashMiddleware,prefetchCache: prefetchCacheMiddlewarediff --git a/apps/erp/app/routes/api+/system-status.ts b/apps/erp/app/routes/api+/system-status.tsnew file mode 100644index 0000000000..975a713a1e--- /dev/null+++ b/apps/erp/app/routes/api+/system-status.ts@@ -0,0 +1,19 @@+// 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 { getSystemStatus } from "@carbon/lib/system-status.server";+import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";++// The deployment's status document (latest version, announcement), or null+// when SYSTEM_STATUS_URL is unset. The same for every company.+export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, {});+ return await getSystemStatus();+}++export const clientLoader = cachedClientLoader<typeof loader>({+ staleTime: RefreshRate.High+});diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex c770205cf3..0c6c693b75 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -28,9 +28,10 @@ import { getLogger } from "@carbon/logger";import { getImplementationCheckStates } from "@carbon/onboarding/server";import type { PrintingSettings } from "@carbon/printing";import { PrintingProvider } from "@carbon/printing/ui";-import { RouteRealtime } from "@carbon/query";+import { RouteRealtime, useLoaderQuery } from "@carbon/query";import { setClientCompanyId } from "@carbon/query/cache";import {+ AnnouncementBar,ItarEntityCertification,ItarEntityPendingBlock,ItarUserCertification,@@ -48,6 +49,7 @@ import {requiresItarEntityCertification,SHELL_MAX_AGE_MS} from "@carbon/utils";+import { useLingui } from "@lingui/react/macro";import posthog from "posthog-js";import type { ReactNode } from "react";import { Suspense, useEffect } from "react";@@ -88,6 +90,7 @@ import {} from "~/modules/shared/shared.server";import { getItarCertificationStatus } from "~/modules/users";import { getUserClaims } from "~/modules/users/users.server";+import type { loader as systemStatusLoader } from "~/routes/api+/system-status";import { ERP_URL, MES_URL, path } from "~/utils/path";const log = getLogger("erp", "auth");@@ -389,6 +392,10 @@ export default function AuthenticatedRoute() {} = loaderData;// During render, not in an effect: clientLoaders and the first child read it.setClientCompanyId(company?.id ?? null, user?.id ?? null);+ const { t } = useLingui();+ const systemStatus = useLoaderQuery<typeof systemStatusLoader>(+ path.to.api.systemStatus+ );// biome-ignore lint/correctness/useExhaustiveDependencies: runs each time the loader doesuseEffect(() => {shellLoadedAt = Date.now();@@ -543,6 +550,12 @@ export default function AuthenticatedRoute() {(notifications, sheets) never run on desktop. */}{isPhone && <MobileAppBar />}<Topbar />+ <AnnouncementBar+ announcement={systemStatus.data?.announcement}+ userId={user?.id ?? ""}+ dismissLabel={t`Dismiss`}+ defaultLinkLabel={t`Learn more`}+ /><main className="flex-1 overflow-y-auto scrollbar-hide relative"><ModuleSidebarLayout>{/* A company switch stays on the same page. Without the key the pagediff --git a/apps/erp/app/styles/tailwind.css b/apps/erp/app/styles/tailwind.cssindex e13fac18c0..1f43e94e82 100644--- a/apps/erp/app/styles/tailwind.css+++ b/apps/erp/app/styles/tailwind.css@@ -53,8 +53,10 @@ html.mode-transitioning *::after {/* Vertical space the inset app-shell panel gives up to its gutters(md:mt-2 + md:mb-2 in x+/_layout.tsx). Full-bleed below md → 0.Full-screen pages subtract this from their 100dvh height calcs so- bottom-pinned content isn't clipped by the panel. */- --content-inset: 0px;+ bottom-pinned content isn't clipped by the panel. The announcement+ bar (AnnouncementBar sets --announcement-height on <html>) takes+ height from the same pages, so it is counted here. */+ --content-inset: var(--announcement-height, 0px);--sidebar-background: 0 0% 98%;--sidebar-foreground: 240 5.3% 26.1%;@@ -138,7 +140,7 @@ html.mode-transitioning *::after {/* The inset app-shell panel gains 8px top + 8px bottom gutters at md+. */@media (min-width: 768px) {:root {- --content-inset: 1rem;+ --content-inset: calc(1rem + var(--announcement-height, 0px));}}}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 2ac1aeef02..800d2dc1cb 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -374,6 +374,7 @@ export const path = {supplierProcesses: (id: string) =>generatePath(`${api}/purchasing/supplier-processes/${id}`),supplierTypes: `${api}/purchasing/supplier-types`,+ systemStatus: `${api}/system-status`,tags: (table?: string) =>generatePath(`${api}/shared/tags?table=${table}`),timecard: `${api}/people/timecard`,diff --git a/apps/mes/app/components/Kanban/components/ColumnCard.tsx b/apps/mes/app/components/Kanban/components/ColumnCard.tsxindex ebff2906c4..e654477e9b 100644--- a/apps/mes/app/components/Kanban/components/ColumnCard.tsx+++ b/apps/mes/app/components/Kanban/components/ColumnCard.tsx@@ -104,8 +104,8 @@ export function ColumnCard({dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined})} flex flex-col p-[1px] pt-0`,currentFilters.length > 0- ? `h-[calc(100dvh-var(--header-height)*2-var(--filters-height))]`- : `h-[calc(100dvh-var(--header-height)*2)]`,+ ? `h-[calc(100dvh-var(--header-height)*2-var(--filters-height)-var(--announcement-height,0px))]`+ : `h-[calc(100dvh-var(--header-height)*2-var(--announcement-height,0px))]`,// Phones: the column fills the board, so its header stays put while// its cards scroll under it, as on desktop."max-md:h-full"diff --git a/apps/mes/app/entry.server.tsx b/apps/mes/app/entry.server.tsxindex b8afd08def..9b96448879 100644--- a/apps/mes/app/entry.server.tsx+++ b/apps/mes/app/entry.server.tsx@@ -2,7 +2,7 @@// 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 { POSTHOG_API_HOST, SUPABASE_URL } from "@carbon/auth";+import { MAINTENANCE_MODE, POSTHOG_API_HOST, SUPABASE_URL } from "@carbon/auth";import { installFormBodyGuard } from "@carbon/auth/middleware/form-body.server";import {getNonce,@@ -136,6 +136,8 @@ export function handleError() {// Client navigated away / cancelled mid-flight — not a real failure.if (request.signal.aborted) return;+ // Every request is a 503 during maintenance; that is not a failure to log.+ if (MAINTENANCE_MODE) return;// Redirects and intentional Response throws are control flow, not errors.if (error instanceof Response && error.status < 500) return;if (isRouteErrorResponse(error) && error.status < 500) return;diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsxindex b817a5bbf4..4da73f0b7d 100644--- a/apps/mes/app/root.tsx+++ b/apps/mes/app/root.tsx@@ -11,6 +11,7 @@ import {flashResultContext} from "@carbon/auth/middleware/flash.server";import { formBodyMiddleware } from "@carbon/auth/middleware/form-body.server";+import { maintenanceMiddleware } from "@carbon/auth/middleware/maintenance.server";import { securityMiddleware } from "@carbon/auth/middleware/security.server";import { validator } from "@carbon/form";import { LocaleProvider, resolveLanguage } from "@carbon/locale";@@ -75,6 +76,8 @@ export const middleware = timedMiddleware({// First: the request scope (context, request id, access log).request: requestMiddleware,security: securityMiddleware,+ // After security, so the 503 still carries the nonce and security headers.+ maintenance: maintenanceMiddleware,formBody: formBodyMiddleware,flash: flashMiddleware,prefetchCache: prefetchCacheMiddlewarediff --git a/apps/mes/app/routes/api+/system-status.ts b/apps/mes/app/routes/api+/system-status.tsnew file mode 100644index 0000000000..975a713a1e--- /dev/null+++ b/apps/mes/app/routes/api+/system-status.ts@@ -0,0 +1,19 @@+// 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 { getSystemStatus } from "@carbon/lib/system-status.server";+import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";++// The deployment's status document (latest version, announcement), or null+// when SYSTEM_STATUS_URL is unset. The same for every company.+export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, {});+ return await getSystemStatus();+}++export const clientLoader = cachedClientLoader<typeof loader>({+ staleTime: RefreshRate.High+});diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsxindex b4147946e8..b72cefa2af 100644--- a/apps/mes/app/routes/x+/_layout.tsx+++ b/apps/mes/app/routes/x+/_layout.tsx@@ -28,9 +28,10 @@ import { isConsoleModeEnabledForCompany } from "@carbon/ee/console.server";import type { PrintingSettings } from "@carbon/printing";import { getPrinterRoutes } from "@carbon/printing";import { PrintingProvider } from "@carbon/printing/ui";-import { RouteRealtime } from "@carbon/query";+import { RouteRealtime, useLoaderQuery } from "@carbon/query";import { setClientCompanyId } from "@carbon/query/cache";import {+ AnnouncementBar,Button,cn,Heading,@@ -50,7 +51,7 @@ import {requiresItarEntityCertification,SHELL_MAX_AGE_MS} from "@carbon/utils";-import { Trans } from "@lingui/react/macro";+import { Trans, useLingui } from "@lingui/react/macro";import posthog from "posthog-js";import type { ReactNode } from "react";import { Suspense, useEffect, useState } from "react";@@ -79,6 +80,7 @@ import { TimeCardWarning } from "~/components/TimeCardWarning";import { userContext } from "~/context";import { useIdle } from "~/hooks";import { userMiddleware } from "~/middleware/user";+import type { loader as systemStatusLoader } from "~/routes/api+/system-status";import { getItarCertificationStatus } from "~/services/itar.service";import { getActiveMaintenanceEventsCount } from "~/services/maintenance.service";import {@@ -403,6 +405,10 @@ export default function AuthenticatedRoute() {});const userId = user?.id;+ const { t } = useLingui();+ const systemStatus = useLoaderQuery<typeof systemStatusLoader>(+ path.to.api.systemStatus+ );const userEmail = user?.email;const userFullName = user ? `${user.firstName} ${user.lastName}` : undefined;const companyId = company?.companyId;@@ -546,6 +552,14 @@ export default function AuthenticatedRoute() {{/* A company switch stays on the same page. Without the key the pagekeeps its state, so a form still held the previous company'svalues and saving wrote them to the new one. */}+ <AnnouncementBar+ announcement={systemStatus.data?.announcement}+ // The pinned-in operator on a console, so one+ // operator's dismissal is not everyone's.+ userId={loaderData.effectiveUserId ?? user?.id ?? ""}+ dismissLabel={t`Dismiss`}+ defaultLinkLabel={t`Learn more`}+ /><Outlet key={companyId} /></div><MesTabBardiff --git a/apps/mes/app/routes/x+/assigned.tsx b/apps/mes/app/routes/x+/assigned.tsxindex 48784a222f..41b9f88e42 100644--- a/apps/mes/app/routes/x+/assigned.tsx+++ b/apps/mes/app/routes/x+/assigned.tsx@@ -296,7 +296,7 @@ export default function AssignedRoute() {return (// Phones: the page takes the screen above the tab bar, so the list and// the board scroll inside it (see Schedule).- <div className="flex flex-col flex-1 min-h-0 min-w-0 max-md:h-[calc(100dvh-var(--mes-tab-bar-h))] max-md:flex-none">+ <div className="flex flex-col flex-1 min-h-0 min-w-0 max-md:h-[calc(100dvh-var(--mes-tab-bar-h)-var(--announcement-height,0px))] max-md:flex-none"><MesAppBartitle={<Trans>Assigned</Trans>}actions={diff --git a/apps/mes/app/routes/x+/maintenance.tsx b/apps/mes/app/routes/x+/maintenance.tsxindex c91f805065..62f9cc6fde 100644--- a/apps/mes/app/routes/x+/maintenance.tsx+++ b/apps/mes/app/routes/x+/maintenance.tsx@@ -298,7 +298,7 @@ function EmptyState({}) {return (<MesEmptyState- className="flex-1 w-full h-[calc(100dvh-var(--header-height)*2-40px)]"+ className="flex-1 w-full h-[calc(100dvh-var(--header-height)*2-40px-var(--announcement-height,0px))]"title={message}action={onClear ? (diff --git a/apps/mes/app/routes/x+/operations.tsx b/apps/mes/app/routes/x+/operations.tsxindex e27048a37f..bd7a9f0f48 100644--- a/apps/mes/app/routes/x+/operations.tsx+++ b/apps/mes/app/routes/x+/operations.tsx@@ -686,7 +686,7 @@ function KanbanSchedule() {return (// Phones: the shell grows with its content, so the page takes the screen// above the tab bar itself; each column then scrolls under its header.- <div className="flex flex-col flex-1 min-h-0 w-full max-md:h-[calc(100dvh-var(--mes-tab-bar-h))] max-md:flex-none">+ <div className="flex flex-col flex-1 min-h-0 w-full max-md:h-[calc(100dvh-var(--mes-tab-bar-h)-var(--announcement-height,0px))] max-md:flex-none"><MesAppBartitle={<Trans>Schedule</Trans>}actions={diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.tsindex 794f46edb5..17060b46ef 100644--- a/apps/mes/app/utils/path.ts+++ b/apps/mes/app/utils/path.ts@@ -45,7 +45,8 @@ export const path = {) =>generatePath(`${api}/suggested-allocation?itemId=${itemId}&locationId=${locationId}&quantity=${quantity}`- )+ ),+ systemStatus: `${api}/system-status`},assembly: (id: string) => generatePath(`${x}/assembly/${id}`),assigned: `${x}/assigned`,diff --git a/apps/starter/app/root.tsx b/apps/starter/app/root.tsxindex ce6f66fd14..c156662d39 100644--- a/apps/starter/app/root.tsx+++ b/apps/starter/app/root.tsx@@ -11,6 +11,7 @@ import {flashResultContext} from "@carbon/auth/middleware/flash.server";import { formBodyMiddleware } from "@carbon/auth/middleware/form-body.server";+import { maintenanceMiddleware } from "@carbon/auth/middleware/maintenance.server";import { securityMiddleware } from "@carbon/auth/middleware/security.server";import { validator } from "@carbon/form";import { LocaleProvider, resolveLanguage } from "@carbon/locale";@@ -66,6 +67,7 @@ import { getTheme, setTheme } from "./services/theme.server";export const middleware = [requestIdMiddleware,securityMiddleware,+ maintenanceMiddleware,formBodyMiddleware,flashMiddleware,prefetchCacheMiddlewarediff --git a/contrib/deploying/simple-docker-caddy/.env.example b/contrib/deploying/simple-docker-caddy/.env.exampleindex 29f2a8ee24..eaf55c424c 100644--- a/contrib/deploying/simple-docker-caddy/.env.example+++ b/contrib/deploying/simple-docker-caddy/.env.example@@ -32,6 +32,11 @@ [email protected]# ── App config ───────────────────────────────────────────────────────────────CARBON_EDITION=community+# true answers every request except /health with a 503 maintenance screen.+# Apply with `deploy.sh deploy`; the apps read it at start.+# MAINTENANCE_MODE=true+# Optional JSON document ({ latestVersion?, announcement? }) shown as a bar in the app.+# SYSTEM_STATUS_URL=https://example.com/status.json# From-address for app email (envelope sender). The apps share the GOTRUE_SMTP_*# host/port/user below and the `smtp_password` Docker secret.SMTP_FROM="Carbon <[email protected]>"diff --git a/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml b/contrib/deploying/simple-docker-caddy/docker-compose.prod.ymlindex d45ad9b840..27b289c8c6 100644--- a/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml+++ b/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml@@ -67,6 +67,8 @@ services:PORT: "3000"TZ: UTCCARBON_EDITION: ${CARBON_EDITION:-community}+ MAINTENANCE_MODE: ${MAINTENANCE_MODE:-}+ SYSTEM_STATUS_URL: ${SYSTEM_STATUS_URL:-}AUTH_PROVIDERS: ${AUTH_PROVIDERS:-email,google,azure}DOMAIN: ${DOMAIN}ERP_URL: ${ERP_URL}@@ -114,6 +116,8 @@ services:PORT: "3000"TZ: UTCCARBON_EDITION: ${CARBON_EDITION:-community}+ MAINTENANCE_MODE: ${MAINTENANCE_MODE:-}+ SYSTEM_STATUS_URL: ${SYSTEM_STATUS_URL:-}AUTH_PROVIDERS: ${AUTH_PROVIDERS:-email,google,azure}DOMAIN: ${DOMAIN}ERP_URL: ${ERP_URL}diff --git a/docs/content/docs/building/architecture.mdx b/docs/content/docs/building/architecture.mdxindex 7fdd00f0e7..a115bafa20 100644--- a/docs/content/docs/building/architecture.mdx+++ b/docs/content/docs/building/architecture.mdx@@ -660,14 +660,15 @@ sets `enterprise`.### 7.4 How a merge becomes production-Pushing to `main` triggers each Vercel project's Git-integrated build. AWS deployment uses four independent GitHub Actions workflows:+Pushing to `main` triggers each Vercel project's Git-integrated build. AWS deployment uses these GitHub Actions workflows:| Workflow | Fires when | What it does || -------------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- || `check.yml` | every pull request | Biome, typecheck, tests, translation and workflow-catalog checks; an edge-functions job fails any `../` import out of a function's directory, then runs `deno check` |-| `deploy.yml` | merge to `main` touching `apps/erp`, `apps/mes` or `packages` | builds both images from the one root `Dockerfile`, pushes them to Amazon's image registry tagged with the commit, then fans out `sst deploy` per workspace |+| `build-images.yml` | every merge to `main` | builds or re-tags every image, tagged with the commit; when the merge touched `apps/erp`, `apps/mes`, `packages` or `docs/content` and both app images succeeded, it calls `deploy.yml` |+| `deploy.yml` | called by `build-images.yml`, or run by hand | fans out `sst deploy` per workspace, then calls `inngest.yml` || `supabase.yml` | merge touching `packages/database/supabase` | applies migrations and deploys edge functions, per workspace |-| `inngest.yml` | after `deploy.yml` succeeds | calls `PUT /api/inngest` on each app so Inngest learns the current list of jobs |+| `inngest.yml` | called by `deploy.yml` after it succeeds | calls `PUT /api/inngest` on each app so Inngest learns the current list of jobs |`check.yml` does not build application images, so a successful pull request can still fail during image build.Database and application deployments run without ordering, so migrations must remain compatible with the previous application version.diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.mdindex 752613d227..0c2d40e908 100644--- a/packages/auth/AGENTS.md+++ b/packages/auth/AGENTS.md@@ -48,6 +48,7 @@ pnpm --filter @carbon/auth test| `./console-pin.server` | MES console pin-in cookie (signed, bound to company + terminal session user): `setConsolePinIn`, `clearConsolePinIn`, `resolveConsolePinIn` (re-validated against the DB, memoized per read), `ConsolePinIn`; `requirePermissions` uses it to derive `userId` in console mode || `./self-signup.server` | Cloud self-signup blocklist: `isSelfSignupBlockedForEmail`, `SELF_SIGNUP_BLOCKED_MESSAGE` (free/disposable email domains; used by ERP login/verify/callback + MES callback) || `./middleware/flash.server` | Flash message middleware |+| `./middleware/maintenance.server` | `maintenanceMiddleware` (with `MAINTENANCE_MODE` on: 503 for every request, 200 for `/health`); keep it after `securityMiddleware` in each root `middleware`. The decision is the pure `maintenanceVerdict` || `./middleware/security.server` | `securityMiddleware` (CSRF check + CSP nonce + baseline headers), `rejectCrossSiteNavigation`, `getNonce`, `setStrictContentSecurityPolicy` (report-only for now; `entry.server` calls it), `cspReportAction` + `CSP_REPORT_PATH`. The decisions are pure and tested in `lib/security.ts` |SAML SSO lives in `@carbon/ee/sso.server` (Enterprise-gated), NOT here — authdiff --git a/packages/auth/package.json b/packages/auth/package.jsonindex 01aac0ec2d..0bd473b5cb 100644--- a/packages/auth/package.json+++ b/packages/auth/package.json@@ -29,6 +29,7 @@"./middleware/flash.server": "./src/middleware/flash.server.ts","./middleware/form-body.server": "./src/middleware/form-body.server.ts","./middleware/security.server": "./src/middleware/security.server.ts",+ "./middleware/maintenance.server": "./src/middleware/maintenance.server.ts","./middleware/flash.client": "./src/middleware/flash.client.ts"},"main": "./src/index.ts",diff --git a/packages/auth/src/middleware/maintenance.server.test.ts b/packages/auth/src/middleware/maintenance.server.test.tsnew file mode 100644index 0000000000..cd2b36e921--- /dev/null+++ b/packages/auth/src/middleware/maintenance.server.test.ts@@ -0,0 +1,30 @@+// 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 { describe, expect, it } from "vitest";+import { maintenanceVerdict } from "./maintenance.server";++describe("maintenanceVerdict", () => {+ it("lets every request through when maintenance is off", () => {+ expect(maintenanceVerdict(false, "/x/sales")).toBeNull();+ expect(maintenanceVerdict(false, "/health")).toBeNull();+ });++ it("keeps the health check passing during maintenance", () => {+ expect(maintenanceVerdict(true, "/health")).toBe("healthy");+ });++ it("refuses pages, the API, webhooks and job callbacks", () => {+ for (const pathname of [+ "/",+ "/x/sales",+ "/api/v1/items",+ "/api/webhook/stripe",+ "/api/inngest",+ "/health/deep"+ ]) {+ expect(maintenanceVerdict(true, pathname)).toBe("refuse");+ }+ });+});diff --git a/packages/auth/src/middleware/maintenance.server.ts b/packages/auth/src/middleware/maintenance.server.tsnew file mode 100644index 0000000000..b43b880a92--- /dev/null+++ b/packages/auth/src/middleware/maintenance.server.ts@@ -0,0 +1,46 @@+// 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 { MAINTENANCE_MODE } from "@carbon/env";+import { data, type MiddlewareFunction } from "react-router";++const RETRY_AFTER_SECONDS = "300";++/**+ * What a request gets while the deployment is in maintenance: `null` lets it+ * through, a `Response` is returned as is, and `"refuse"` is the 503.+ *+ * `/health` answers 200 without probing anything. The load balancer and the+ * Swarm healthcheck replace a task that fails it, and the usual probe fails+ * while the database is down for the maintenance itself.+ */+export function maintenanceVerdict(+ enabled: boolean,+ pathname: string+): null | "healthy" | "refuse" {+ if (!enabled) return null;+ return pathname === "/health" ? "healthy" : "refuse";+}++/**+ * Root middleware for every app. With `MAINTENANCE_MODE` on, a page request+ * renders the root ErrorBoundary's 503 screen, an open tab's next navigation+ * does the same, and a resource route (API, webhooks, Inngest) answers a bare+ * 503 so the caller retries.+ */+export const maintenanceMiddleware: MiddlewareFunction<Response> = async (+ { request },+ next+) => {+ const verdict = maintenanceVerdict(+ MAINTENANCE_MODE,+ new URL(request.url).pathname+ );+ if (verdict === null) return next();+ if (verdict === "healthy") return Response.json({ status: "maintenance" });+ throw data(+ { message: "maintenance" },+ { status: 503, headers: { "Retry-After": RETRY_AFTER_SECONDS } }+ );+};diff --git a/packages/env/AGENTS.md b/packages/env/AGENTS.mdindex a200aca4db..99dc10dabb 100644--- a/packages/env/AGENTS.md+++ b/packages/env/AGENTS.md@@ -40,6 +40,7 @@ pnpm --filter @carbon/env test- **Redis/Jobs:** `REDIS_URL`, `INNGEST_SIGNING_KEY`, `INNGEST_EVENT_KEY`- **Auth:** `SESSION_SECRET`, `SESSION_MAX_AGE`, `RATE_LIMIT`, `AUTH_PROVIDERS`, `isAuthProviderEnabled()`- **Edition:** `CarbonEdition` (Community/Cloud/Enterprise/Test), `CONTROLLED_ENVIRONMENT` (ITAR flag)+- **Maintenance and status:** `MAINTENANCE_MODE` (every request but `/health` answers 503), `SYSTEM_STATUS_URL` (optional status/announcement document)- **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)diff --git a/packages/env/src/index.ts b/packages/env/src/index.tsindex 5a57168207..71f0956260 100644--- a/packages/env/src/index.ts+++ b/packages/env/src/index.ts@@ -117,6 +117,10 @@ const itarEnvironment = getEnv("CONTROLLED_ENVIRONMENT");export const CONTROLLED_ENVIRONMENT = parseBoolean(itarEnvironment, false);+export const MAINTENANCE_MODE = parseBoolean(getEnv("MAINTENANCE_MODE"), false);++export const SYSTEM_STATUS_URL = getEnv("SYSTEM_STATUS_URL");+// Carbon GovCloud Rider metadata. These are the authoritative `docVersion` /// `docHash` stamped onto every ITAR certification, and the target of the// "View the full Rider" link. `ITAR_RIDER_SHA256` is the sha256 of the Rider PDFdiff --git a/packages/env/src/schema.ts b/packages/env/src/schema.tsindex 7e26b84c0d..eeab31e37d 100644--- a/packages/env/src/schema.ts+++ b/packages/env/src/schema.ts@@ -116,6 +116,16 @@ export const schema = define({description: "true for an ITAR / controlled deployment",browser: true},+ MAINTENANCE_MODE: {+ group: "core",+ description: "true answers every request except /health with a 503"+ },+ SYSTEM_STATUS_URL: {+ group: "core",+ description:+ "URL of a JSON document with the latest version and an announcement",+ type: url+ },DEFAULT_LANGUAGE: {group: "core",description: "Default UI language (en)",diff --git a/packages/lib/package.json b/packages/lib/package.jsonindex 98f43ce73e..93bf029b9c 100644--- a/packages/lib/package.json+++ b/packages/lib/package.json@@ -43,6 +43,8 @@"./sales-invoice-document.server": "./src/sales-invoice-document.server.tsx","./shims": "./src/shims.ts","./slack.server": "./src/slack.server.ts",+ "./system-status": "./src/system-status.ts",+ "./system-status.server": "./src/system-status.server.ts","./telemetry": "./src/telemetry/capture.ts","./trigger": "./src/trigger.ts","./twenty.server": "./src/twenty.server.ts",diff --git a/packages/lib/src/system-status.server.ts b/packages/lib/src/system-status.server.tsnew file mode 100644index 0000000000..0820d6869d--- /dev/null+++ b/packages/lib/src/system-status.server.ts@@ -0,0 +1,33 @@+// 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 { SYSTEM_STATUS_URL } from "@carbon/env";+import { redis } from "@carbon/kv";+import { fetchSystemStatus, type SystemStatus } from "./system-status";++const CACHE_KEY = "system-status";+const CACHE_TTL_SECONDS = 300;+// A failed fetch is cached too, briefly, so a dead host costs one request a+// minute instead of one per page.+const FAILURE_TTL_SECONDS = 60;++/**+ * The deployment's status document, or null when `SYSTEM_STATUS_URL` is unset+ * (no request is made) or the host is unreachable.+ */+export async function getSystemStatus(): Promise<SystemStatus | null> {+ if (!SYSTEM_STATUS_URL) return null;++ const cached = await redis.get(CACHE_KEY);+ if (cached !== null) return JSON.parse(cached) as SystemStatus | null;++ const status = await fetchSystemStatus(SYSTEM_STATUS_URL);+ await redis.set(+ CACHE_KEY,+ JSON.stringify(status),+ "EX",+ status ? CACHE_TTL_SECONDS : FAILURE_TTL_SECONDS+ );+ return status;+}diff --git a/packages/lib/src/system-status.test.ts b/packages/lib/src/system-status.test.tsnew file mode 100644index 0000000000..6514a30a73--- /dev/null+++ b/packages/lib/src/system-status.test.ts@@ -0,0 +1,62 @@+// 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 { afterEach, describe, expect, it, vi } from "vitest";+import { fetchSystemStatus } from "./system-status";++const respond = (body: unknown, status = 200) =>+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(JSON.stringify(body), { status }))+ );++afterEach(() => vi.unstubAllGlobals());++describe("fetchSystemStatus", () => {+ it("fills in the announcement defaults", async () => {+ respond({+ latestVersion: "2026.10.1",+ announcement: { id: "a1", message: "Maintenance at 22:00 UTC" }+ });+ expect(await fetchSystemStatus("https://status.test")).toEqual({+ latestVersion: "2026.10.1",+ announcement: {+ id: "a1",+ message: "Maintenance at 22:00 UTC",+ severity: "info",+ dismissible: true+ }+ });+ });++ it("accepts a document with no announcement", async () => {+ respond({ announcement: null });+ expect(await fetchSystemStatus("https://status.test")).toEqual({+ announcement: null+ });+ });++ it("rejects a link that is not http(s)", async () => {+ respond({+ announcement: { id: "a1", message: "Hi", href: "javascript:alert(1)" }+ });+ expect(await fetchSystemStatus("https://status.test")).toBeNull();+ });++ it("returns null for an error status, a bad document or a dead host", async () => {+ respond({}, 500);+ expect(await fetchSystemStatus("https://status.test")).toBeNull();++ respond({ announcement: { message: "no id" } });+ expect(await fetchSystemStatus("https://status.test")).toBeNull();++ vi.stubGlobal(+ "fetch",+ vi.fn(async () => {+ throw new TypeError("fetch failed");+ })+ );+ expect(await fetchSystemStatus("https://status.test")).toBeNull();+ });+});diff --git a/packages/lib/src/system-status.ts b/packages/lib/src/system-status.tsnew file mode 100644index 0000000000..9d2f214cd5--- /dev/null+++ b/packages/lib/src/system-status.ts@@ -0,0 +1,64 @@+// 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 { z } from "zod";++const log = getLogger("lib", "system-status");++const FETCH_TIMEOUT_MS = 3000;++/**+ * The document `SYSTEM_STATUS_URL` must return. It comes from another host, so+ * every field is validated and `message` is only ever rendered as text.+ */+export const announcementValidator = z.object({+ // A new id shows the bar again to everyone who dismissed the previous one.+ id: z.string().min(1).max(100),+ message: z.string().min(1).max(500),+ severity: z.enum(["info", "warning", "critical"]).default("info"),+ href: z+ .url()+ .refine((value) => /^https?:\/\//i.test(value), "href must be http(s)")+ .optional(),+ linkLabel: z.string().min(1).max(60).optional(),+ dismissible: z.boolean().default(true)+});++export const systemStatusValidator = z.object({+ latestVersion: z.string().max(60).optional(),+ announcement: announcementValidator.nullish()+});++export type Announcement = z.infer<typeof announcementValidator>;+export type SystemStatus = z.infer<typeof systemStatusValidator>;++/** Fetches and validates the status document. Null on any failure. */+export async function fetchSystemStatus(+ url: string+): Promise<SystemStatus | null> {+ try {+ const response = await fetch(url, {+ headers: { accept: "application/json" },+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)+ });+ if (!response.ok) {+ log.warn("System status request failed with {status}", {+ status: response.status+ });+ return null;+ }+ const parsed = systemStatusValidator.safeParse(await response.json());+ if (!parsed.success) {+ log.warn("System status document is not valid", {+ issues: parsed.error.issues+ });+ return null;+ }+ return parsed.data;+ } catch (error) {+ log.warn("System status request failed", { error });+ return null;+ }+}diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.poindex bcb86e88ee..21b9315c15 100644--- a/packages/locale/locales/de/mes.po+++ b/packages/locale/locales/de/mes.po@@ -545,6 +545,9 @@ msgstr "Beschreibung"msgid "Details"msgstr "Details"+msgid "Dismiss"+msgstr "Verwerfen"+msgid "Dispatch not found"msgstr "Instandhaltungsauftrag nicht gefunden"diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.poindex 4e73833644..e8883573f5 100644--- a/packages/locale/locales/en/mes.po+++ b/packages/locale/locales/en/mes.po@@ -545,6 +545,9 @@ msgstr "Description"msgid "Details"msgstr "Details"+msgid "Dismiss"+msgstr "Dismiss"+msgid "Dispatch not found"msgstr "Dispatch not found"diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.poindex 38b905477b..c301010132 100644--- a/packages/locale/locales/es/mes.po+++ b/packages/locale/locales/es/mes.po@@ -545,6 +545,9 @@ msgstr "Descripción"msgid "Details"msgstr "Detalles"+msgid "Dismiss"+msgstr "Descartar"+msgid "Dispatch not found"msgstr "Orden de mantenimiento no encontrada"diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.poindex 55ee663efd..b31c12250b 100644--- a/packages/locale/locales/fr/mes.po+++ b/packages/locale/locales/fr/mes.po@@ -545,6 +545,9 @@ msgstr "Description"msgid "Details"msgstr "Détails"+msgid "Dismiss"+msgstr "Fermer"+msgid "Dispatch not found"msgstr "Intervention de maintenance non trouvée"diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.poindex a186ff5efa..143fc06f78 100644--- a/packages/locale/locales/hi/mes.po+++ b/packages/locale/locales/hi/mes.po@@ -545,6 +545,9 @@ msgstr "विवरण"msgid "Details"msgstr "विवरण"+msgid "Dismiss"+msgstr "खारिज करें"+msgid "Dispatch not found"msgstr "रखरखाव कार्य नहीं मिला"diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.poindex 82382baed8..5b9eb98b98 100644--- a/packages/locale/locales/it/mes.po+++ b/packages/locale/locales/it/mes.po@@ -545,6 +545,9 @@ msgstr "Descrizione"msgid "Details"msgstr "Dettagli"+msgid "Dismiss"+msgstr "Ignora"+msgid "Dispatch not found"msgstr "Intervento di manutenzione non trovato"diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.poindex 2aedc4c198..83a9dd1101 100644--- a/packages/locale/locales/ja/mes.po+++ b/packages/locale/locales/ja/mes.po@@ -545,6 +545,9 @@ msgstr "説明"msgid "Details"msgstr "詳細"+msgid "Dismiss"+msgstr "閉じる"+msgid "Dispatch not found"msgstr "保全指示が見つかりません"diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.poindex e77cc2f6c6..ca92cedb74 100644--- a/packages/locale/locales/ko/mes.po+++ b/packages/locale/locales/ko/mes.po@@ -545,6 +545,9 @@ msgstr "설명"msgid "Details"msgstr "상세 정보"+msgid "Dismiss"+msgstr "닫기"+msgid "Dispatch not found"msgstr "유지보수 지시를 찾을 수 없습니다"diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.poindex d2e7fba283..b6bc4b4f77 100644--- a/packages/locale/locales/pl/mes.po+++ b/packages/locale/locales/pl/mes.po@@ -545,6 +545,9 @@ msgstr "Opis"msgid "Details"msgstr "Szczegóły"+msgid "Dismiss"+msgstr "Odrzuć"+msgid "Dispatch not found"msgstr "Nie znaleziono zlecenia utrzymania ruchu"diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.poindex a5e30db752..5b9589a76f 100644--- a/packages/locale/locales/pt/mes.po+++ b/packages/locale/locales/pt/mes.po@@ -545,6 +545,9 @@ msgstr "Descrição"msgid "Details"msgstr "Detalhes"+msgid "Dismiss"+msgstr "Descartar"+msgid "Dispatch not found"msgstr "Ordem de manutenção não encontrada"diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.poindex a053d9f9d8..b2f993e64d 100644--- a/packages/locale/locales/ru/mes.po+++ b/packages/locale/locales/ru/mes.po@@ -545,6 +545,9 @@ msgstr "Описание"msgid "Details"msgstr "Детали"+msgid "Dismiss"+msgstr "Отклонить"+msgid "Dispatch not found"msgstr "Заявка на техобслуживание не найдена"diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.poindex 2554a9019e..2c423c0aee 100644--- a/packages/locale/locales/tr/mes.po+++ b/packages/locale/locales/tr/mes.po@@ -545,6 +545,9 @@ msgstr "Açıklama"msgid "Details"msgstr "Detaylar"+msgid "Dismiss"+msgstr "Kapat"+msgid "Dispatch not found"msgstr "Bakım emri bulunamadı"diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.poindex e60ca0908c..d71b8e0863 100644--- a/packages/locale/locales/zh/mes.po+++ b/packages/locale/locales/zh/mes.po@@ -545,6 +545,9 @@ msgstr "描述"msgid "Details"msgstr "详情"+msgid "Dismiss"+msgstr "关闭"+msgid "Dispatch not found"msgstr "找不到维护工单"diff --git a/packages/react/AGENTS.md b/packages/react/AGENTS.mdindex ab331c0b67..01a0333b28 100644--- a/packages/react/AGENTS.md+++ b/packages/react/AGENTS.md@@ -48,8 +48,9 @@ import { Button, Card, HStack, VStack, IconButton, cn } from "@carbon/react";- **Record outlet**: `RecordOutlet` is the `<Outlet>` of every route under `/x`. It remounts the page inside it when that page is shown for a different record (the params of the route in the outlet, not of a drawer below it), so nothing seeded from the previous record survives. A plain `<Outlet>` there fails the `no-bare-outlet` check- **Data**: `Table` (TanStack), chart components via sub-exports (`@carbon/react/Chart`)- **Rich text**: `@carbon/react/Editor` and `@carbon/react/RichText` (wraps `@carbon/tiptap`)-- **Error boundary**: `@carbon/react/ErrorBoundary` — `RouteErrorBoundary` (exported as `ErrorBoundary` from a module layout so a failed loader shows inside the app shell; it shows the status code and, for a 4xx, the message the server threw — `routeErrorCopy` — so throw a `Response` whose body says what was wrong. A 5xx or thrown `Error` gets generic copy) and `RootErrorBoundary` (drop-in root `ErrorBoundary` for RR v7 that maps 404 / other HTTP / thrown `Error` to a styled screen) plus its parts (`ErrorScreen`, `GlitchHeading`, `StatusReadout`, `MagneticLink`, `NoiseOverlay`). Wrap it in the app's `Document` and pass `env` so `window.env` is set (the client crashes hydration otherwise). Copy is intentionally hardcoded English, not i18n.+- **Error boundary**: `@carbon/react/ErrorBoundary` — `RouteErrorBoundary` (exported as `ErrorBoundary` from a module layout so a failed loader shows inside the app shell; it shows the status code and, for a 4xx, the message the server threw — `routeErrorCopy` — so throw a `Response` whose body says what was wrong. A 5xx or thrown `Error` gets generic copy) and `RootErrorBoundary` (drop-in root `ErrorBoundary` for RR v7 that maps 404 / 503 (the maintenance screen) / other HTTP / thrown `Error` to a styled screen) plus its parts (`ErrorScreen`, `GlitchHeading`, `StatusReadout`, `MagneticLink`, `NoiseOverlay`). Wrap it in the app's `Document` and pass `env` so `window.env` is set (the client crashes hydration otherwise). Copy is intentionally hardcoded English, not i18n.- **Avatar**: `src` may be a URL or a generated-avatar value from `user.avatarUrl` (`dicebear:<style>:<seed>[:<rrggbb>]`; the styles and value helpers are in `@carbon/utils` `avatar.ts`). A generated value renders as a plain `<img>` of `generatedAvatarUrl(value)` (`utils/generatedAvatarImage.ts`, which `Avatar` imports instead of the renderer so no bundle that shows an avatar carries DiceBear) — `/file/avatar/:value?v=<GENERATED_AVATAR_RENDER_VERSION>` — so it is in the server-rendered HTML and needs no client JavaScript. Every app (ERP, MES, academy) serves that path with a one-line route re-exporting `generatedAvatarLoader` from `@carbon/react/GeneratedAvatar`: it draws the SVG on the server with DiceBear 10 and answers `Cache-Control: public, max-age=31536000, immutable`, so a refresh reads it from the browser cache. **Bump `GENERATED_AVATAR_RENDER_VERSION` whenever the same value would draw differently** (a DiceBear upgrade, a change to the rendering options), or browsers keep the old image. The avatar picker draws in the browser instead (`GeneratedAvatarPreview`, `useGeneratedAvatar`), because a color drag makes a new value per step; there the DiceBear core and each style's JSON load with `import()` (`STYLE_LOADERS`, typed `Record<GeneratedAvatarStyle, …>`), never with a `with: { type: "json" }` attribute (Vite passes it to the browser, which rejects the JSON Vite serves as JavaScript, and the picker stays grey); the server side instead bundles `@dicebear/styles` through `ssrNoExternal` in each app's `vite.config.ts`, because Node refuses a package's JSON without the attribute. `generatedAvatarClassName(style)` picks the image classes: line-art styles on white (`bg-white`) in both themes, color styles on `bg-muted`. A value's optional background goes to DiceBear as `backgroundColor`; on a dark one (`isDarkBackground`, WCAG contrast) the styles that draw lines straight onto the background (`INK_OPTIONS`) get white ink. The app `Avatar` wrappers turn a stored value into `src` with `avatarSrc` (`@carbon/utils`); a new user has no avatar (initials) until they choose one+- **Announcement**: `AnnouncementBar` is the one-line bar both shells render above their page area for the deployment's announcement. It remembers a dismissal in localStorage per user and announcement id, and while shown sets `--announcement-height` on `<html>`; the ERP's `--content-inset` includes it, and a page sized from `100dvh` outside that variable must subtract it- **Polish**: shadows over borders, `tabular-nums` for dynamic numbers, `active:scale-[0.98]` on pressables, `text-balance`/`text-pretty` for text wrapping## Cross-Referencesdiff --git a/packages/react/src/AnnouncementBar.tsx b/packages/react/src/AnnouncementBar.tsxnew file mode 100644index 0000000000..1a0e4c54df--- /dev/null+++ b/packages/react/src/AnnouncementBar.tsx@@ -0,0 +1,98 @@+// 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 { useEffect } from "react";+import { LuInfo, LuTriangleAlert, LuX } from "react-icons/lu";+import { Alert } from "./Alert";+import useLocalStorage from "./hooks/useLocalStorage";+import { IconButton } from "./IconButton";++export type AnnouncementBarAnnouncement = {+ id: string;+ message: string;+ severity: "info" | "warning" | "critical";+ href?: string;+ linkLabel?: string;+ dismissible: boolean;+};++const VARIANT = {+ info: "info",+ warning: "warning",+ critical: "destructive"+} as const;++// Full-height pages size themselves from the viewport, so the bar's height is+// published for them to subtract. Keep in step with the `h-9` below.+const HEIGHT_VARIABLE = "--announcement-height";+const HEIGHT = "2.25rem";++/**+ * A one-line announcement across the top of the app's content. A dismissal is+ * remembered in this browser per user and announcement id, so a new id shows+ * the bar again. The message is remote content and is rendered as text only.+ */+export function AnnouncementBar({+ announcement,+ userId,+ dismissLabel,+ defaultLinkLabel+}: {+ announcement: AnnouncementBarAnnouncement | null | undefined;+ userId: string;+ dismissLabel: string;+ defaultLinkLabel: string;+}) {+ const [dismissedId, setDismissedId] = useLocalStorage<string | null>(+ `announcement-dismissed:${userId}`,+ null+ );+ const visible =+ !!announcement &&+ !(announcement.dismissible && dismissedId === announcement.id);++ useEffect(() => {+ if (!visible) return;+ const root = document.documentElement;+ root.style.setProperty(HEIGHT_VARIABLE, HEIGHT);+ return () => {+ root.style.removeProperty(HEIGHT_VARIABLE);+ };+ }, [visible]);++ if (!visible || !announcement) return null;++ const Icon = announcement.severity === "info" ? LuInfo : LuTriangleAlert;++ return (+ <Alert+ variant={VARIANT[announcement.severity]}+ className="flex h-9 shrink-0 items-center gap-2 rounded-none border-x-0 border-t-0 px-3 py-0 text-sm"+ >+ <Icon className="shrink-0" />+ <span className="min-w-0 flex-1 truncate" title={announcement.message}>+ {announcement.message}+ </span>+ {announcement.href && (+ <a+ href={announcement.href}+ target="_blank"+ rel="noopener noreferrer"+ className="shrink-0 font-medium underline underline-offset-2"+ >+ {announcement.linkLabel ?? defaultLinkLabel}+ </a>+ )}+ {announcement.dismissible && (+ <IconButton+ aria-label={dismissLabel}+ variant="ghost"+ size="sm"+ icon={<LuX />}+ onClick={() => setDismissedId(announcement.id)}+ />+ )}+ </Alert>+ );+}diff --git a/packages/react/src/ErrorBoundary/RootErrorBoundary.tsx b/packages/react/src/ErrorBoundary/RootErrorBoundary.tsxindex 9b8d427729..86f6d6cb53 100644--- a/packages/react/src/ErrorBoundary/RootErrorBoundary.tsx+++ b/packages/react/src/ErrorBoundary/RootErrorBoundary.tsx@@ -67,6 +67,28 @@ function resolveConfig(error: unknown, retry: () => void): ErrorScreenProps {};}+ // Thrown by `maintenanceMiddleware` while MAINTENANCE_MODE is on. A 503+ // from anywhere else (a gateway, an overloaded upstream) is not maintenance.+ if (error.status === 503 && error.data?.message === "maintenance") {+ return {+ code: "503",+ eyebrow: "— scheduled maintenance",+ title: "Carbon is down for maintenance.",+ message:+ "We are working on the system and will be back shortly. Nothing you saved is lost; try again in a few minutes.",+ highlightIndex: 3,+ logLines: [+ "> opening channel to server ...",+ "> maintenance window in progress",+ "> requests paused, data intact",+ "> status_code: 503 / SERVICE_UNAVAILABLE",+ "> retry_after: 300s",+ "> recommendation: retry shortly"+ ],+ actions: [{ label: "retry", onClick: retry }]+ };+ }+// Any other HTTP status thrown as a route responseconst detail =typeof error.data === "string"diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsxindex 7e344738ce..d1d4bd011c 100644--- a/packages/react/src/index.tsx+++ b/packages/react/src/index.tsx@@ -22,6 +22,7 @@ import { ActionMenu } from "./ActionMenu";import type { ActionPresentation } from "./ActionPresentation";import { ActionPresentationProvider } from "./ActionPresentation";import { Alert, AlertDescription, AlertTitle } from "./Alert";+import { AnnouncementBar } from "./AnnouncementBar";import { AutodeskProvider, AutodeskViewer } from "./AutodeskViewer";import type { AvatarProps } from "./Avatar";import {@@ -433,6 +434,7 @@ export {Alert,AlertDescription,AlertTitle,+ AnnouncementBar,AutodeskProvider,AutodeskViewer,Avatar,diff --git a/sst.config.ts b/sst.config.tsindex 34ce032192..49b56bfd66 100644--- a/sst.config.ts+++ b/sst.config.ts@@ -67,6 +67,8 @@ export default $config({process.env.CLOUDFLARE_TURNSTILE_SITE_KEY,CONTROLLED_ENVIRONMENT: process.env.CONTROLLED_ENVIRONMENT,DOMAIN: process.env.DOMAIN ?? "carbon.ms",+ MAINTENANCE_MODE: process.env.MAINTENANCE_MODE,+ SYSTEM_STATUS_URL: process.env.SYSTEM_STATUS_URL,ERP_URL: process.env.URL_ERP ? `https://${process.env.URL_ERP}` : "https://itar.carbon.ms",EXCHANGE_RATES_API_KEY: process.env.EXCHANGE_RATES_API_KEY,GOOGLE_PLACES_API_KEY: process.env.GOOGLE_PLACES_API_KEY,@@ -180,6 +182,8 @@ export default $config({process.env.CLOUDFLARE_TURNSTILE_SITE_KEY,CONTROLLED_ENVIRONMENT: process.env.CONTROLLED_ENVIRONMENT,DOMAIN: process.env.DOMAIN ?? "carbon.ms",+ MAINTENANCE_MODE: process.env.MAINTENANCE_MODE,+ SYSTEM_STATUS_URL: process.env.SYSTEM_STATUS_URL,ERP_URL: process.env.URL_ERP ? `https://${process.env.URL_ERP}` : "https://itar.carbon.ms",EXCHANGE_RATES_API_KEY: process.env.EXCHANGE_RATES_API_KEY,INNGEST_BASE_URL: process.env.INNGEST_BASE_URL,