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
perf(ui): prefetch on press again, and let the click reuse the prefetch
Sidwebworks639a952983a8
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 3284d24b53..a181456bcb 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -2996,6 +2996,6 @@ tag until proven otherwise.**Problem:** Single-fetch `.data` responses carry `cache-control: max-age=0, must-revalidate` and no validator, so the browser never serves the click from the prefetched response: both requests reach the server. Chrome also holds a second request for a URL until the first one's response arrives (its HTTP cache admits one writer per URL). The click's request therefore waited behind the prefetch: 781 ms against 518 ms median click-to-page in production, and two same-URL `fetch` calls took 572 / 923 ms where two `cache: "no-store"` ones took 615 / 585 ms.-**Rule:** Do not start a second request for a URL that is already in flight, and do not prefetch a response the browser is not allowed to reuse. Before adding a prefetch, read the response's `cache-control`. Measure a prefetch by click-to-page time, not by whether the request was sent.+**Rule:** A prefetch only helps if the browser may reuse its response. Give a prefetch response (`Sec-Purpose: prefetch`) a short `private` lifetime and leave every other response uncached; `prefetchCacheMiddleware` (`@carbon/utils`) does it in each app's root `middleware`, the fix React Router points to (remix-run/react-router#13255). Measure a prefetch by click-to-page time, not by whether the request was sent. A first fix removed the prefetch instead (`6e3bdf7bc6`); it worked but threw away the head start.-**Applies to:** `packages/react/src/PrefetchLink.tsx`; any `<Link prefetch>` or `PrefetchPageLinks`; a revalidation started while a navigation to the same URL is loading.+**Applies to:** `packages/react/src/PrefetchLink.tsx`; `packages/utils/src/prefetch.ts`; any `<Link prefetch>` or `PrefetchPageLinks`; a revalidation started while a navigation to the same URL is loading.diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsxindex ed3e28ac20..d20d9ba4cf 100644--- a/apps/erp/app/root.tsx+++ b/apps/erp/app/root.tsx@@ -30,6 +30,7 @@ import {getPreferenceHeaders,isSearchParamOnlyNavigation,modeValidator,+ prefetchCacheMiddleware,themes} from "@carbon/utils";import { faviconLinks } from "@carbon/utils/favicon";@@ -73,7 +74,8 @@ export const middleware = timedMiddleware({request: requestMiddleware,security: securityMiddleware,formBody: formBodyMiddleware,- flash: flashMiddleware+ flash: flashMiddleware,+ prefetchCache: prefetchCacheMiddleware});export const clientMiddleware = [flashClientMiddleware,diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsxindex 214a3accb2..877b401325 100644--- a/apps/mes/app/root.tsx+++ b/apps/mes/app/root.tsx@@ -30,6 +30,7 @@ import {getPreferenceHeaders,isSearchParamOnlyNavigation,modeValidator,+ prefetchCacheMiddleware,themes} from "@carbon/utils";import { faviconLinks } from "@carbon/utils/favicon";@@ -72,7 +73,8 @@ export const middleware = timedMiddleware({request: requestMiddleware,security: securityMiddleware,formBody: formBodyMiddleware,- flash: flashMiddleware+ flash: flashMiddleware,+ prefetchCache: prefetchCacheMiddleware});export const clientMiddleware = [flashClientMiddleware,diff --git a/apps/starter/app/root.tsx b/apps/starter/app/root.tsxindex 6bc07dba7a..4528b4d840 100644--- a/apps/starter/app/root.tsx+++ b/apps/starter/app/root.tsx@@ -16,7 +16,12 @@ import { validator } from "@carbon/form";import { requestIdMiddleware } from "@carbon/logger/middleware.server";import { Button, Heading, Toaster, useMode } from "@carbon/react";import type { Theme } from "@carbon/utils";-import { colorSchemeHintScript, modeValidator, themes } from "@carbon/utils";+import {+ colorSchemeHintScript,+ modeValidator,+ prefetchCacheMiddleware,+ themes+} from "@carbon/utils";import { faviconLinks } from "@carbon/utils/favicon";import { Analytics } from "@vercel/analytics/react";import type React from "react";@@ -48,7 +53,8 @@ export const middleware = [requestIdMiddleware,securityMiddleware,formBodyMiddleware,- flashMiddleware+ flashMiddleware,+ prefetchCacheMiddleware];export const clientMiddleware = [flashClientMiddleware];diff --git a/packages/react/AGENTS.md b/packages/react/AGENTS.mdindex 02528fe4b5..0957259b06 100644--- a/packages/react/AGENTS.md+++ b/packages/react/AGENTS.md@@ -42,7 +42,7 @@ import { Button, Card, HStack, VStack, IconButton, cn } from "@carbon/react";- **Layout**: `VStack` / `HStack` with numeric `spacing` prop (maps to `space-y-*`/`space-x-*`)- **Overlays**: `Drawer`, `Modal`, `ModalDrawer` (unified drawer/modal), `BottomSheet`, `Popover`. A controlled `Modal`/`Drawer` with no `onOpenChange` cannot be dismissed and shows no close button; never pass a handler that does nothing (`no-noop-open-change` check). A route rendered as a modal or drawer closes with `useCloseRoute()` (back when this tab has history, else the parent route), not `navigate(-1)`- **App nav**: `NavRail` is the primary left nav of both the ERP and MES shells (56px icon rail, expands after a 150ms mouse hover or when pinned via `SidebarProvider` (⌘B unless `keyboardShortcut={false}`, as in the ERP), left drawer below md that closes itself on navigation). Optional `header` (use `NavRailBrand` for a logo + name) and `footer` slots; `NavRailGroup` adds a titled section that shows as a divider while collapsed. Entries are `NavRailItem` (a button, or `asChild` for a trigger/link) and `NavRailLink`; `label` is a string and doubles as the accessible name. A Radix menu/popover opened from a `NavRailItem` keeps the rail as it was (open or collapsed) until it closes. Render inside `SidebarProvider`; the shadcn-style `Sidebar*` primitives remain for other layouts-- **Links**: `PrefetchLink` is the app's React Router `Link` and the one place that decides whether links prefetch. Today they do not: page data is served `max-age=0`, so a prefetched response is never reused, and the browser holds the click's request for the same URL behind it (about 260 ms slower per click than no prefetch, measured in production). Use it instead of `<Link prefetch="intent">`. `NavRailLink` and both apps' `Hyperlink` already use it+- **Links that prefetch**: `PrefetchLink` is a React Router `Link` that prefetches its destination when the pointer goes down on it. Use it instead of `<Link prefetch="intent">`, which prefetches on a 100 ms hover and so runs a page's loaders for every row the mouse passes over. The click reuses the prefetch only because `prefetchCacheMiddleware` (`@carbon/utils`, in each app's root `middleware`) gives a prefetch response a few seconds of private cache; without it both requests reach the server and the click waits behind the prefetch. `NavRailLink` and both apps' `Hyperlink` already use it- **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) 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.diff --git a/packages/react/src/PrefetchLink.tsx b/packages/react/src/PrefetchLink.tsxindex 88b286c233..ab2a86cea7 100644--- a/packages/react/src/PrefetchLink.tsx+++ b/packages/react/src/PrefetchLink.tsx@@ -4,24 +4,59 @@"use client";-import { forwardRef } from "react";+import { forwardRef, useState } from "react";import type { LinkProps } from "react-router";-import { Link } from "react-router";+import { Link, PrefetchPageLinks, useHref } from "react-router";++const ABSOLUTE_URL = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;/**- * The app's `Link`: the one place that decides whether links prefetch. Today- * they do not.+ * A `Link` that prefetches its destination when the pointer goes down on it.+ *+ * `prefetch="intent"` prefetches on a 100 ms hover, so moving the mouse down a+ * list ran every hovered page's loaders for a click that mostly never came. A+ * press is a commitment: it costs one request, and the page gets the time+ * between press and release as a head start.*- * Page data is served `max-age=0`, so the browser cannot answer a click from a- * prefetched response. It also holds a second request for a URL until the- * first one's response arrives, so a prefetch started on hover or on press- * made the click's own request wait behind it: about 260 ms slower per click- * than no prefetch, measured in production.+ * The click reuses the prefetched response only because+ * `prefetchCacheMiddleware` (`@carbon/utils`) lets the browser keep it for a+ * few seconds. Without that header both requests reach the server, and the+ * browser holds the click's request until the prefetch's response arrives:+ * slower than no prefetch at all.** Use this instead of `<Link prefetch="intent">`.*/export const PrefetchLink = forwardRef<HTMLAnchorElement,Omit<LinkProps, "prefetch">->((props, ref) => <Link ref={ref} {...props} />);+>(({ onPointerDown, ...props }, ref) => {+ const href = useHref(props.to, { relative: props.relative });+ // A new key remounts the prefetch tags, so each press prefetches again.+ const [presses, setPresses] = useState(0);+ const canPrefetch =+ props.to !== "#" &&+ !(typeof props.to === "string" && ABSOLUTE_URL.test(props.to));++ return (+ <>+ <Link+ ref={ref}+ {...props}+ onPointerDown={(event) => {+ onPointerDown?.(event);+ // A modified or non-primary press opens a new tab or a menu: the+ // page being prefetched would not be the one that uses it.+ const plain =+ event.button === 0 &&+ !event.metaKey &&+ !event.ctrlKey &&+ !event.shiftKey &&+ !event.altKey;+ if (plain && canPrefetch) setPresses((n) => n + 1);+ }}+ />+ {presses > 0 && <PrefetchPageLinks key={presses} page={href} />}+ </>+ );+});PrefetchLink.displayName = "PrefetchLink";diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.mdindex e3f52a0d71..87a5334696 100644--- a/packages/utils/AGENTS.md+++ b/packages/utils/AGENTS.md@@ -62,6 +62,7 @@ pnpm --filter @carbon/utils typecheck| `string` | Slugify, truncate, camelCase/titleCase conversions || `items` | Item lookups and `getReadableIdWithRevision` (`readableId.revision`) || `revalidate` | `shouldRevalidate` predicates: `isSearchParamOnlyNavigation` (root loaders), `isUnaffectedByNavigation` (detail layouts — names the route/search params the loader reads) |+| `prefetch` | `prefetchCacheMiddleware` — root `middleware` of every app: a prefetch response (`Sec-Purpose: prefetch`) gets `private, max-age=5`, so the click reuses it instead of asking again and waiting behind it. Navigations and revalidations stay uncached || `redirect` | `redirect(to, init?)` — the only redirect a loader or action uses: a path on this origin, anything else lands on the home page (`no-raw-redirect` check); `redirectExternal(url, init?)` to leave the origin on purpose with a URL the server built; `safePath(to, fallback)` for a destination that is stored or forwarded rather than redirected to. `redirectBeforeLoaders(loader)` — route middleware for an index route that only redirects, so the redirect runs before its parents' loaders || `status` | Status resolution, status color mapping || `rules` | Rule engine: condition AST, the shared `Operator` vocabulary, JIT-compiled evaluator + surfaces for storage rules and sales rules |diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex ba5705689f..b56d2d8763 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -45,6 +45,7 @@ export * from "./mode";export * from "./object";export * from "./payment-funding";export * from "./pick-guards";+export * from "./prefetch";export * from "./purchase-cost-adjustment";export * from "./receiving";export * from "./redirect";diff --git a/packages/utils/src/prefetch.test.ts b/packages/utils/src/prefetch.test.tsnew file mode 100644index 0000000000..56fcb50df2--- /dev/null+++ b/packages/utils/src/prefetch.test.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 { describe, expect, it } from "vitest";+import { prefetchCacheMiddleware } from "./prefetch";++const run = (+ headers: Record<string, string>,+ response: Response,+ method = "GET"+) =>+ prefetchCacheMiddleware(+ {+ request: new Request("https://app.test/x/parts.data", { method, headers })+ },+ async () => response+ );++describe("prefetchCacheMiddleware", () => {+ it("caches a prefetch for a few seconds, privately", async () => {+ const res = await run({ "Sec-Purpose": "prefetch" }, new Response("ok"));+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=5");+ });++ it("recognises the older Purpose header", async () => {+ const res = await run({ Purpose: "prefetch" }, new Response("ok"));+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=5");+ });++ it("leaves a navigation uncached", async () => {+ const res = await run({}, new Response("ok"));+ expect(res.headers.get("Cache-Control")).toBeNull();+ });++ it("keeps a Cache-Control the route set", async () => {+ const res = await run(+ { "Sec-Purpose": "prefetch" },+ new Response("ok", { headers: { "Cache-Control": "no-store" } })+ );+ expect(res.headers.get("Cache-Control")).toBe("no-store");+ });++ it("does not cache a redirect or an error", async () => {+ const redirect = await run(+ { "Sec-Purpose": "prefetch" },+ new Response(null, { status: 302, headers: { Location: "/x" } })+ );+ const failed = await run(+ { "Sec-Purpose": "prefetch" },+ new Response("no", { status: 500 })+ );+ expect(redirect.headers.get("Cache-Control")).toBeNull();+ expect(failed.headers.get("Cache-Control")).toBeNull();+ });++ it("sets the header on a response whose headers are immutable", async () => {+ const immutable = Response.redirect("https://app.test/", 302);+ const ok = new Response("ok");+ Object.defineProperty(ok, "headers", { value: immutable.headers });+ const res = await run({ "Sec-Purpose": "prefetch" }, ok);+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=5");+ });+});diff --git a/packages/utils/src/prefetch.ts b/packages/utils/src/prefetch.tsnew file mode 100644index 0000000000..d08ff6d000--- /dev/null+++ b/packages/utils/src/prefetch.ts@@ -0,0 +1,59 @@+// 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.++/**+ * Lets the browser keep a prefetched response for a few seconds, so the click+ * that follows is answered from it instead of asking the server again.+ *+ * export const middleware = [..., prefetchCacheMiddleware];+ *+ * Page data is served without a lifetime, so a `<link rel="prefetch">` was+ * never reused: the click made a second request, and the browser held it until+ * the prefetch's response arrived. Only a prefetch gets the lifetime, and only+ * `private`: a navigation, a revalidation after a save and a realtime reload+ * still go to the server. The fix React Router points to for this+ * (remix-run/react-router#13255).+ */+export const PREFETCH_MAX_AGE_SECONDS = 5;++// Browsers have named the header differently over the years.+const PURPOSE_HEADERS = [+ "Sec-Purpose",+ "Purpose",+ "X-Purpose",+ "Sec-Fetch-Purpose",+ "X-Moz"+];++export function isPrefetchRequest(request: Request) {+ if (request.method !== "GET") return false;+ return PURPOSE_HEADERS.some((name) =>+ request.headers.get(name)?.toLowerCase().startsWith("prefetch")+ );+}++export async function prefetchCacheMiddleware<Result>(+ { request }: { request: Request },+ next: () => Promise<Result>+): Promise<Result> {+ const response = await next();+ if (+ !(response instanceof Response) ||+ response.status !== 200 ||+ response.headers.has("Cache-Control") ||+ !isPrefetchRequest(request)+ ) {+ return response;+ }+ const value = `private, max-age=${PREFETCH_MAX_AGE_SECONDS}`;+ try {+ response.headers.set("Cache-Control", value);+ return response;+ } catch {+ // Immutable headers (a proxied `fetch` response): copy, then set.+ const copy = new Response(response.body, response);+ copy.headers.set("Cache-Control", value);+ return copy as Result;+ }+}