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
fix: stop duplicate writes from replayed submits and retries (#1772)
Sid69e12568a3f3
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 5fe2dc86f2..318f857151 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -2589,3 +2589,45 @@ tracked file.**Applies to:** `packages/database/src/types.ts`,`packages/database/supabase/functions/lib/types.ts`,`apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json`, any generated artifact.++---++## A submit button that stays live is a duplicate-write engine++**Context:** Finalizing quote Q000699 emailed the customer the same PDF three times within+one minute, same recipient list each time. The finalize action evaluates sales rules across+every line, renders a PDF, uploads it, writes a `document` row, flips the quote to `Sent`,+renders two email bodies and signs an attachment URL before it triggers the send — seconds+of wall time, during which `QuoteFinalizeModal`'s Finalize button was enabled and not even+spinning (`isDisabled={loading}`, where `loading` was the modal's own data-fetch flag).++**Problem:** Three layers of the same defect, and only the first is about a button.+(1) `fetcher.submit` aborts the previous BROWSER request; the server action it started runs+to completion regardless, because nothing in a route action reads `request.signal`. So N+clicks are N complete sets of side effects. The guard had existed as `onSubmit={onClose}`+(the modal unmounted before a second click was possible) and was dropped in `e59a9e26e2`+when closing moved to `useRuleViolations({ onSuccess: onClose })` — correct on its own, since+violations must be able to reopen the modal, but nothing replaced the guard.+(2) `@carbon/react`'s `Button` left `isLoading` out of the DOM `disabled` attribute while+`useShortcutKeys` already treated it as disabling — so a spinning button refused Enter but+still took a mouse click, and every call site guarding a submit with+`isLoading={fetcher.state !== "idle"}` was showing a spinner over a live button.+(3) `fetchWithRetry` replayed every method on a 5xx or a 25 s timeout. PostgREST commits+before it answers, so a retried insert is a duplicate row and a retried `.rpc()` re-runs a+transaction. The `quoteToQuote` incidents had already produced the rule — *"a retry wrapper+must never blindly retry a write with real side effects and no idempotency key"* — but the+fix carved out only `/functions/v1/`, leaving every PostgREST write still replaying.++**Rule:** A submit path needs a guard at each layer that can replay it. The button disables+while its own submission is in flight (`<Submit>`, or `isLoading` bound to the fetcher's+state); `ValidatedForm` drops a re-entrant submit so the form holds even when a button+forgets; a retry wrapper replays only idempotent methods; and a job retries only failures+that provably had no effect — for an SMTP send that means connect/greet/auth errors only,+never an ambiguous `ETIMEDOUT` that may have been delivered. When triaging "the operation+failed but extra copies appeared", check all four before assuming a browser double-submit.+`isDisabled` bound to any-old-boolean is not a guard: name the submit state.++**Applies to:** `packages/react/src/Button.tsx`, `packages/form/src/ValidatedForm.tsx`,+`packages/auth/src/lib/supabase/client.ts` (`fetchWithRetry`, `isReplayable`),+`packages/jobs/src/inngest/functions/notifications/send-{email,slack}.ts`, and any+`<Button type="submit">` — enforced by `no-unguarded-submit` (`@carbon/checks`).diff --git a/.claude/rules/conventions-forms.md b/.claude/rules/conventions-forms.mdindex 2d94991008..b8d20f5b3f 100644--- a/.claude/rules/conventions-forms.md+++ b/.claude/rules/conventions-forms.md@@ -180,6 +180,19 @@ const ThingForm = ({ initialValues, type = "drawer", open, onClose }: ThingFormP- `VStack spacing={4}` for vertical layout; `grid grid-cols-1 lg:grid-cols-3gap-x-8 gap-y-4` for multi-column.- Permission check drives `isDisabled` on `<Submit>`.+- **A submit button must disable while its own submission is in flight.** Inside a+ `ValidatedForm` use `<Submit>`, which disables on `isSubmitting`; the form itself+ also drops a re-entrant submit, so the two together make a double POST impossible.+ On a `fetcher.Form` / `<Form>` bind the button yourself —+ `isLoading={fetcher.state !== "idle"}` (on `@carbon/react`'s `Button`, `isLoading`+ disables as well as spins), or `navigation.formAction === <action>` for a+ navigation form. Every extra click is a whole extra POST: `fetcher.submit` aborts+ the previous browser request, but the server action it started runs to completion+ — nothing reads `request.signal`. A slow action (render a PDF, post a ledger entry,+ email a customer) is exactly where this bites, and the missing spinner is what+ invites the second click. Enforced by `no-unguarded-submit` (`@carbon/checks`);+ note that an `isDisabled` bound to something that is not a submit-state signal+ does NOT count.- Pass `fetcher` from `useFetcher()` when the form is a drawer/modal (so loadingstate and action data flow through the fetcher); plain page forms may omit it.diff --git a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsHeader.tsx b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsHeader.tsxindex 2d5e2a6e3d..cc3ba1b05d 100644--- a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsHeader.tsx+++ b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsHeader.tsx@@ -12,7 +12,7 @@ import {} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { LuClipboardList, LuPackagePlus, LuSettings2 } from "react-icons/lu";-import { Form, Link } from "react-router";+import { Form, Link, useNavigation } from "react-router";import { SearchFilter } from "~/components";import { useLocations } from "~/components/Form/Location";import { usePermissions } from "~/hooks";@@ -49,6 +49,7 @@ export function PickingListsHeader({}: PickingListsHeaderProps) {const { t } = useLingui();const permissions = usePermissions();+ const navigation = useNavigation();const locations = useLocations();return (@@ -78,6 +79,7 @@ export function PickingListsHeader({type="submit"leftIcon={<LuPackagePlus />}isDisabled={!permissions.can("create", "inventory")}+ isLoading={navigation.formAction === path.to.newPickingList}><Trans>Generate Picking List</Trans>{" "}{selectedJobOperationIds.length}diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsxindex a5344cee94..5f0378f27a 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx@@ -66,6 +66,7 @@ const QuotationFinalizeModal = ({onSuccess: onClose});const { fetcher } = ruleViolations;+ const isSubmitting = fetcher.state !== "idle";const integrations = useIntegrations();const canEmail = integrations.has("email");@@ -248,7 +249,11 @@ const QuotationFinalizeModal = ({<Button variant="secondary" onClick={onClose}><Trans>Cancel</Trans></Button>- <Button isDisabled={loading} type="submit">+ <Button+ isDisabled={loading || isSubmitting}+ isLoading={isSubmitting}+ type="submit"+ ><Trans>Finalize</Trans></Button></ModalFooter>diff --git a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsxindex 523e7fc102..cc12287d1d 100644--- a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx+++ b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQHeader.tsx@@ -177,6 +177,7 @@ const SalesRFQHeader = () => {)}<Button+ isLoading={statusFetcher.state !== "idle"}isDisabled={status !== "Ready for Quote" ||routeData?.lines?.length === 0 ||diff --git a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx b/apps/erp/app/routes/x+/person+/$personId.timecard.tsxindex 445fe32ce2..d60e0dadbf 100644--- a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx+++ b/apps/erp/app/routes/x+/person+/$personId.timecard.tsx@@ -598,6 +598,7 @@ export default function PersonTimecardRoute() {/>)}<Button+ isLoading={fetcher.state !== "idle"}variant="secondary"type="submit"disabled={isNaN(new Date(addClockIn).getTime())}@@ -680,6 +681,7 @@ export default function PersonTimecardRoute() {)}<input type="hidden" name="note" value={editNote} /><Button+ isLoading={fetcher.state !== "idle"}variant="secondary"type="submit"disabled={isNaN(new Date(editClockIn).getTime())}diff --git a/apps/erp/app/routes/x+/reimbursements+/$reimbursementId._index.tsx b/apps/erp/app/routes/x+/reimbursements+/$reimbursementId._index.tsxindex a1dd8e53dd..ce9c252f18 100644--- a/apps/erp/app/routes/x+/reimbursements+/$reimbursementId._index.tsx+++ b/apps/erp/app/routes/x+/reimbursements+/$reimbursementId._index.tsx@@ -4,7 +4,13 @@ import { flash } from "@carbon/auth/session.server";import { Button, HStack, useDisclosure, VStack } from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import type { LoaderFunctionArgs } from "react-router";-import { Form, Link, redirect, useLoaderData } from "react-router";+import {+ Form,+ Link,+ redirect,+ useLoaderData,+ useNavigation+} from "react-router";import { Confirm } from "~/components/Modals";import { usePermissions } from "~/hooks";import {@@ -157,6 +163,7 @@ export default function ReimbursementDetailRoute() {balanceDue,defaultBankAccount} = useLoaderData<typeof loader>();+ const navigation = useNavigation();const { t } = useLingui();const permissions = usePermissions();const voidModal = useDisclosure();@@ -193,7 +200,14 @@ export default function ReimbursementDetailRoute() {method="post"action={path.to.reimbursementPost(reimbursement.id)}>- <Button type="submit" variant="primary">+ <Button+ type="submit"+ variant="primary"+ isLoading={+ navigation.formAction ===+ path.to.reimbursementPost(reimbursement.id)+ }+ ><Trans>Post</Trans></Button></Form>diff --git a/apps/erp/app/routes/x+/settings+/billing.tsx b/apps/erp/app/routes/x+/settings+/billing.tsxindex 28c683310f..f337c7fcbe 100644--- a/apps/erp/app/routes/x+/settings+/billing.tsx+++ b/apps/erp/app/routes/x+/settings+/billing.tsx@@ -29,7 +29,13 @@ import { msg } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";import { useState } from "react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";-import { data, Form, redirect, useLoaderData } from "react-router";+import {+ data,+ Form,+ redirect,+ useLoaderData,+ useNavigation+} from "react-router";import { z } from "zod";import { usePermissions, useUser } from "~/hooks";import type { Handle } from "~/utils/handle";@@ -183,6 +189,7 @@ export async function action({ request }: ActionFunctionArgs) {// This route now only handles actions - UI is in the company routeexport default function PaymentSettings() {const { plan, usage, employees } = useLoaderData<typeof loader>();+ const navigation = useNavigation();const { isOwner } = usePermissions();const { id: userId } = useUser();const edition = useEdition();@@ -268,7 +275,10 @@ export default function PaymentSettings() {<CardFooter><Form method="post" action={path.to.billing}><input type="hidden" name="intent" value="billing-portal" />- <Button type="submit">+ <Button+ type="submit"+ isLoading={navigation.formAction === path.to.billing}+ ><Trans>Manage Subscription</Trans></Button></Form>diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsxindex 15e4e55565..622229c613 100644--- a/apps/mes/app/components/AssemblyView.tsx+++ b/apps/mes/app/components/AssemblyView.tsx@@ -2769,6 +2769,7 @@ function TimerControl({<input type="hidden" name="unitIndex" value={unitIndex} />) : null}<button+ disabled={fetcher.state !== "idle"}type="submit"aria-label={active ? "Pause timer" : "Start timer"}className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4"diff --git a/apps/mes/app/components/Inspection/InspectionView.tsx b/apps/mes/app/components/Inspection/InspectionView.tsxindex 34997aee77..2900792fb9 100644--- a/apps/mes/app/components/Inspection/InspectionView.tsx+++ b/apps/mes/app/components/Inspection/InspectionView.tsx@@ -1330,6 +1330,7 @@ function TimerControl({<input type="hidden" name="id" value={openEvent.id} />) : null}<button+ disabled={fetcher.state !== "idle"}type="submit"aria-label={active ? "Pause timer" : "Start timer"}className="flex h-full shrink-0 items-center gap-1 border-l border-border px-2 transition-colors hover:bg-accent active:scale-[0.98] md:gap-2 md:px-4"diff --git a/apps/mes/app/routes/x+/timecard.tsx b/apps/mes/app/routes/x+/timecard.tsxindex 9b17879cc8..cfca7a6e5b 100644--- a/apps/mes/app/routes/x+/timecard.tsx+++ b/apps/mes/app/routes/x+/timecard.tsx@@ -387,6 +387,7 @@ export default function MESTimecardPage() {/>)}<Button+ isLoading={fetcher.state !== "idle"}variant="secondary"type="submit"disabled={isNaN(diff --git a/docs/next.config.mjs b/docs/next.config.mjsindex a8105755b1..d022206d2d 100644--- a/docs/next.config.mjs+++ b/docs/next.config.mjs@@ -1,10 +1,25 @@+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";import { createMDX } from "fumadocs-mdx/next";+// The monorepo root, not docs/: pnpm hoists `next` into the root+// node_modules/.pnpm store, and Turbopack refuses to compile anything outside+// its root — scoping to docs/ makes the framework itself unresolvable.+const workspaceRoot = join(dirname(fileURLToPath(import.meta.url)), "..");+const withMDX = createMDX();/** @type {import('next').NextConfig} */const config = {reactStrictMode: true,+ // Next's own default, pinned so it cannot drift: shipping browser source maps+ // would publish the docs site's unminified sources and inflate the build for+ // no reader-facing gain.+ productionBrowserSourceMaps: false,+ // Turbopack walks up looking for a lockfile to infer the workspace root, and+ // a stray one above the repo (a ~/pnpm-lock.yaml) makes it pick the HOME+ // directory — so it traces every sibling checkout instead of this repo.+ turbopack: { root: workspaceRoot },// Consume the shared status→color constants (@carbon/utils/status-colors) — a pure-TS// workspace module, so Next must transpile it.transpilePackages: ["@carbon/utils"],@@ -15,6 +30,23 @@ const config = {// `.message` directly without pulling the macro runtime.experimental: {swcPlugins: [["@lingui/swc-plugin", {}]],+ // Static generation is the memory peak here: the API and MCP reference+ // pages expand ~108 MDX sources into ~2,180 pages, rendered across a pool+ // of worker processes that each hold their own Next runtime.+ //+ // The pool size is otherwise `os.cpus().length - 1` (13 on a dev laptop)+ // regardless of how much memory is actually free, which is what pushes a+ // constrained machine into OOM. This scales it to free memory instead —+ // `max(min(cpus, freemem/1GB), 4)` in Next's getNumberOfWorkers.+ //+ // NOTE: `os.freemem()` reports the HOST's memory, not a cgroup limit, so+ // under Docker with a memory cap set `cpus` to a hard number instead —+ // an explicit `cpus` overrides this branch entirely.+ memoryBasedWorkersCount: true,+ // No server source maps in a production build either: they are pure build+ // cost and retained heap for a docs site that ships no server code worth+ // debugging from a stack trace.+ serverSourceMaps: false,},// The monorepo pins React 18 (catalog) while this app runs React 19, so two// @types/react versions coexist and `next build` trips on the ReactNode /diff --git a/packages/auth/src/lib/supabase/client.test.ts b/packages/auth/src/lib/supabase/client.test.tsindex 2e123cfe33..a84122be0c 100644--- a/packages/auth/src/lib/supabase/client.test.ts+++ b/packages/auth/src/lib/supabase/client.test.ts@@ -78,6 +78,51 @@ describe("fetchWithRetry", () => {expect(response.status).toBe(200);});+ // PostgREST commits before it answers, so a 5xx or a dropped response says+ // nothing about whether the write landed. Retrying is how one insert becomes+ // several rows. Same rule as the Edge Function carve-out above.+ it.each([+ ["POST (insert / upsert / rpc)", "POST"],+ ["PATCH (update)", "PATCH"],+ ["DELETE (delete)", "DELETE"]+ ])("does not retry a PostgREST write on a 5xx — %s", async (_label, method) => {+ fetchSpy.mockResolvedValue(jsonResponse(503));++ const response = await fetchWithRetry(+ "http://supabase.internal.test/rest/v1/quote",+ { method, body: "{}" }+ );++ expect(fetchSpy).toHaveBeenCalledTimes(1);+ expect(response.status).toBe(503);+ });++ it("does not retry a PostgREST write on a network error — the error propagates", async () => {+ fetchSpy.mockRejectedValue(new Error("connection reset"));++ await expect(+ fetchWithRetry("http://supabase.internal.test/rest/v1/quote", {+ method: "POST",+ body: "{}"+ })+ ).rejects.toThrow("connection reset");++ expect(fetchSpy).toHaveBeenCalledTimes(1);+ });++ it("treats a request with no explicit method as a replayable GET", async () => {+ fetchSpy+ .mockResolvedValueOnce(jsonResponse(500))+ .mockResolvedValueOnce(jsonResponse(200));++ const response = await fetchWithRetry(+ "http://supabase.internal.test/rest/v1/quote?id=eq.1"+ );++ expect(fetchSpy).toHaveBeenCalledTimes(2);+ expect(response.status).toBe(200);+ });+it("returns a non-retryable status from a normal request on the first attempt", async () => {fetchSpy.mockResolvedValue(jsonResponse(404));diff --git a/packages/auth/src/lib/supabase/client.ts b/packages/auth/src/lib/supabase/client.tsindex 1f483c9368..11f9491f02 100644--- a/packages/auth/src/lib/supabase/client.ts+++ b/packages/auth/src/lib/supabase/client.ts@@ -17,14 +17,17 @@ const RETRYABLE_STATUS = new Set([500, 502, 503, 504, 512, 408, 524]);const sleep = (ms: number) =>new Promise<void>((resolve) => setTimeout(resolve, ms));+const methodOf = (input: RequestInfo | URL, init?: RequestInit) =>+ (+ init?.method ?? (input instanceof Request ? input.method : "GET")+ ).toUpperCase();+// Storage object writes (uploads) must NOT go through the retry/timeout wrapper:// re-sending a multi-GB PUT on a 5xx is wasteful, and the 25s per-attempt timeout// would abort any legitimately long upload. Fail fast — pass straight through and// honor only the caller's own signal.const isStorageUpload = (input: RequestInfo | URL, init?: RequestInit) => {- const method = (- init?.method ?? (input instanceof Request ? input.method : "GET")- ).toUpperCase();+ const method = methodOf(input, init);if (method !== "POST" && method !== "PUT") return false;const url = input instanceof Request ? input.url : String(input);return url.includes("/storage/v1/object/");@@ -35,13 +38,30 @@ const isEdgeFunctionInvoke = (input: RequestInfo | URL) => {return url.includes("/functions/v1/");};+// Only a READ may be replayed. A 5xx or a lost response does not mean the write+// did not land — PostgREST commits before it answers, so a retried insert is a+// duplicate row and a retried RPC re-runs a transaction. None of PostgREST's+// write verbs carry an idempotency key: insert/upsert/rpc are POST, update is+// PATCH, delete is DELETE. This is the same rule the Edge Function carve-out+// above encodes (.ai/lessons.md — the quoteToQuote duplicate-quote incidents,+// "a retry wrapper must never blindly retry a write with real side effects and+// no idempotency key"); that fix covered `/functions/v1/` and left every+// PostgREST write still replaying. The per-attempt timeout still applies to+// writes — it bounds latency without duplicating anything.+const isReplayable = (input: RequestInfo | URL, init?: RequestInit) => {+ const method = methodOf(input, init);+ return method === "GET" || method === "HEAD";+};+export const fetchWithRetry: typeof fetch = async (input, init) => {if (isStorageUpload(input, init) || isEdgeFunctionInvoke(input)) {return fetch(input, init);}+ const maxRetries = isReplayable(input, init) ? MAX_RETRIES : 0;+let lastError: unknown;- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {+ for (let attempt = 0; attempt <= maxRetries; attempt++) {const timeoutSignal = AbortSignal.timeout(PER_ATTEMPT_TIMEOUT_MS);const signal = init?.signal? AbortSignal.any([init.signal, timeoutSignal])@@ -49,7 +69,7 @@ export const fetchWithRetry: typeof fetch = async (input, init) => {try {const response = await fetch(input, { ...init, signal });- if (RETRYABLE_STATUS.has(response.status) && attempt < MAX_RETRIES) {+ if (RETRYABLE_STATUS.has(response.status) && attempt < maxRetries) {await sleep(BACKOFF_MS[attempt] ?? 1000);continue;}@@ -57,7 +77,7 @@ export const fetchWithRetry: typeof fetch = async (input, init) => {} catch (error) {lastError = error;if (init?.signal?.aborted) throw error;- if (attempt >= MAX_RETRIES) throw error;+ if (attempt >= maxRetries) throw error;await sleep(BACKOFF_MS[attempt] ?? 1000);}}diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.mdindex 5c19ca4b1d..9e9e0699cb 100644--- a/packages/checks/AGENTS.md+++ b/packages/checks/AGENTS.md@@ -36,6 +36,7 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)- **Forwarded headers** (own source, `REQUEST_HANDLING_ROOTS`: every app + auth, ee, jobs, lib, utils, edge functions): `noRawForwardedHeaders` fails a raw read of `X-Forwarded-For/-Host/-Proto` or `X-Real-IP` outside `packages/utils/src/headers.ts` — use `getClientIp` / `getRequestProtocol` / `getRequestHost` / `getRequestOrigin`. Hand-rolled reads keyed login rate limits and ITAR audit records on the forgeable first `X-Forwarded-For` entry. No baseline entries- **Numeric-precision checks** (in `TS_CHECKS`, over `sources/typescript.ts`): `noRawRounding` flags `Math.round/ceil/floor` and `.toFixed` on value-bearing numbers (use `round`/`scrapAllowance`/`applyRate`/`deriveRate` from `@carbon/utils`); `noInlineFractionDigits` flags `minimum`/`maximumFractionDigits` at a call site (pick a named kind from `@carbon/utils` `format.ts`, and `INPUT_FORMAT.*` for anything editable); `noUnroundedTrackedQuantity` flags inline unrounded arithmetic inside a `.updateTable("trackedEntity")` statement's `quantity:` set, and a raw `===`/`!==`/`<` compare against a `*[Ee]ntity*.quantity` read (use `round`/`settleQuantity` at the write, `isFullDraw` at a split gate — see `.claude/rules/traceability-model.md`). It is scoped to what one file can prove: a `quantity:` set from an already-rounded variable is unflaggable either way, and a compare of two locals is presumed rounded where they were defined. It has **no baseline entries** — the whole tree was fixed in the pass that added it, so any finding is new. `sources/typescript.ts` walks `apps/erp/app/{components,hooks,modules,routes}`, `apps/mes/app`, `packages/database/supabase/functions`, `packages/{ee,jobs}/src`, `packages/documents/src/{pdf,utils}` and the shared packages `packages/{utils,form,react,printing,workflows}/src` — tests and the image/logo resizers excluded. The shared packages matter: `@carbon/utils` is where the standard's own helpers live, and `form`/`react` own the number inputs whose `formatOptions` are part of the storage round-trip. See `.claude/rules/numeric-precision.md`- **Tenant-scoped Kysely writes** (in `TS_CHECKS`): `noUnscopedKyselyWrite` fails any `.updateTable(`/`.deleteFrom(` under `apps/erp/app/{modules,routes}`, `apps/mes/app` or `packages/jobs/src` whose statement (up to `.execute…(`/`.compile(`/`;`/`,` at depth 0, comments blanked) has no `.where("companyId", …)` / `.where("alias.companyId", …)`. Kysely is the superuser connection, and the public API hands a service's `db` param that same client, so the statement's own predicate is the only tenant boundary — ten drag-sort services (`updateQuoteLineOrder` and friends) were a reported cross-tenant write because they keyed on `id` alone. `company` is exempt (its `id` is the tenant); a `companyId` in `.set()` does not count; a link table with no `companyId` column passes by scoping through its parent in a subquery. Edge functions and `packages/ee` are out of scope (see the file header). One baseline entry: the `companyGroup` delete in `packages/jobs/.../scheduled/purge-company.ts` (a group has no `companyId` column; its `id` is the tenant-group key). Every other hit was fixed when it was added+- **Unguarded submit buttons** (in `TS_CHECKS`, `.tsx` only): `noUnguardedSubmit` fails a `<Button>`/`<button>`/`<IconButton>` carrying `type="submit"` whose own opening tag names no in-flight signal (`isLoading`, `isSubmitting`, `isPending`, `isSaving`, `useIsSubmitting`, or a `*fetcher|navigation|transition*.state` read). A live submit button posts again on every click and each POST runs to completion server-side — `fetcher.submit` aborts the previous BROWSER request, but no route action reads `request.signal` — which is how one quote finalize emailed the customer the same PDF three times. It parses the real opening tag (brace- and quote-aware), so a guard written after `type="submit"` still counts and a `>` inside `{a > b}` does not end the tag early. **The presence of `isDisabled` is deliberately not enough**: the incident's button was `isDisabled={loading}` where `loading` was the modal's data-fetch flag, so a check that accepted any `isDisabled` would have passed the exact line it exists to catch; word boundaries matter too (`loading` must not satisfy `isLoading`). Buttons inside a `<ValidatedForm>` are skipped — `ValidatedForm.handleSubmit` drops a re-entrant submit, so a second click cannot produce a second POST however the button is written. `packages/form/src/components/Submit.tsx` is excluded; it IS the guard. The check cannot do dataflow, so a guard held in a differently-named local (`disabled={busy}`) is baselined rather than rewritten. 32 baseline entries, all reviewed: logout/company-switch/theme/console-toggle (idempotent), delete and rule-unassign (a second delete is a no-op), the two chat composers (guarded by a `flushSync` clear plus an empty-message return), and `ConfiguratorForm` (its submit is an `onSubmit` callback — the in-flight state lives at the caller)- **Edge-function auth** (`EDGE_FUNCTION_CHECKS`): `edgeFunctionAuthorizesCaller` fails any function under `packages/database/supabase/functions/` that never calls `requirePermissions` / `requireCaller` / `requireServiceRole` / `getSupabaseServiceRole`, because `verify_jwt` accepts the published anon key. `ALLOWED` in the check holds the functions that are correct without one, each with its reason (`logo-resizer`, `transcription`). `embed`, `event-wake` and `trigger` are baselined, not allowed: Postgres calls them over pg_net with the anon key from `config`, so gating them needs a migration that makes Postgres send a server credential first- **Structure checks**: `moduleShape` — validates ERP modules have `types.ts`, `ui/`, `index.ts`, `<name>.service.ts`, `<name>.models.ts`- **Clobber detection**: `findClobbers(branch, main)` — identifies DB objects redefined on both sidesdiff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.jsonindex 6939317610..f0bb62eda1 100644--- a/packages/checks/src/conformance/baseline.json+++ b/packages/checks/src/conformance/baseline.json@@ -82,7 +82,6 @@"no-integration-id-branching::apps/erp/app/modules/account/account.models.ts::\"email\", \"slack\"","no-integration-id-branching::apps/erp/app/modules/accounting/accounting.service.ts::\"xero\", \"quickbooks\"","no-integration-id-branching::apps/erp/app/modules/settings/settings.server.ts::=== \"ramp\"",- "no-integration-id-branching::apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx::=== \"ramp\"","no-integration-id-branching::apps/erp/app/routes/x+/settings+/integrations.$id.tsx::=== \"quickbooks\"","no-integration-id-branching::apps/erp/app/routes/x+/settings+/integrations.$id.tsx::=== \"ramp\"","no-integration-id-branching::apps/erp/app/routes/x+/settings+/integrations.$id.tsx::=== \"rillet\"",@@ -95,7 +94,6 @@"no-integration-id-branching::packages/ee/src/workflows/catalog/actions.ts::\"email\", \"slack\"","no-integration-id-branching::packages/ee/src/workflows/definition/catalog.ts::\"email\", \"slack\"","no-integration-id-branching::packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts::=== \"rillet\"",- "no-integration-id-branching::packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts::=== \"rillet\"","no-legacy-rls::20230123004206_claims.sql::has_company_permission(","no-legacy-rls::20230123004317_companies-rls.sql::has_company_permission(","no-legacy-rls::20230123004339_employee-types.sql::has_company_permission(",@@ -464,8 +462,6 @@"no-raw-rounding::apps/erp/app/routes/x+/settings+/printing.tsx::const heightDots = Math.round(height * dpi);","no-raw-rounding::apps/erp/app/routes/x+/settings+/printing.tsx::const widthDots = Math.round(width * dpi);","no-raw-rounding::apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx::size: Math.round(file.byteLength / 1024),",- "no-raw-rounding::apps/erp/app/routes/x+/users+/operators.new.tsx::return Math.floor(1000 + Math.random() * 9000).toString();",- "no-raw-rounding::apps/erp/app/routes/x+/users+/operators.reset-pin.$operatorId.tsx::return Math.floor(1000 + Math.random() * 9000).toString();","no-raw-rounding::apps/mes/app/components/AssemblyView.tsx::Math.round(operation?.operationQuantity ?? trackedEntities.length)","no-raw-rounding::apps/mes/app/components/AssemblyView.tsx::Math.round(operation?.quantityComplete ?? 0)","no-raw-rounding::apps/mes/app/components/AssemblyView.tsx::const h = Math.floor(s / 3600)",@@ -567,6 +563,36 @@"no-required-column-without-default::20241210214820_purchasing-redux.sql::ADD COLUMN \"supplierInteractionId\" TEXT NOT NULL","no-required-column-without-default::20241210214820_purchasing-redux.sql::ADD COLUMN IF NOT EXISTS \"supplierInteractionId\" TEXT NOT NULL","no-required-column-without-default::20260402000000_journal-entries.sql::ADD COLUMN \"journalEntryId\" TEXT NOT NULL",+ "no-unguarded-submit::apps/erp/app/components/AvatarMenu.tsx::<button type=\"submit\" className=\"w-full h-full flex items-center\">",+ "no-unguarded-submit::apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx::<Button type=\"submit\" disabled={!isStepValid} variant={isLastStep && destructive ? \"destructive\" : \"primary\"} >",+ "no-unguarded-submit::apps/erp/app/components/Layout/Topbar/Breadcrumbs.tsx::<button type=\"submit\">",+ "no-unguarded-submit::apps/erp/app/components/Layout/Topbar/CompanySwitcher.tsx::<button type=\"submit\">",+ "no-unguarded-submit::apps/erp/app/components/MfaEnrollmentRequired.tsx::<Button type=\"submit\" variant=\"ghost\" size=\"md\" className=\"w-full text-muted-foreground\" >",+ "no-unguarded-submit::apps/erp/app/components/RichText.tsx::<Button type=\"submit\" variant=\"link\" size=\"md\">",+ "no-unguarded-submit::apps/erp/app/components/SessionLockOverlay.tsx::<Button type=\"submit\" variant=\"link\" size=\"sm\" className=\"text-muted-foreground\" >",+ "no-unguarded-submit::apps/erp/app/modules/inventory/ui/StorageRules/RuleAssignmentsList.tsx::<IconButton type=\"submit\" icon={<LuTrash />} aria-label={ isBroadcast ? t`Edit the rule to remove the \"Applies to all\" flag` : t`Unassign rule` } title={ isBroadcast ? t`Edit the rule to remove the \"Applies to all\" flag` : undefined } variant=\"ghost\" size=\"sm\" isDisabled={!canDelete || isLocked} />",+ "no-unguarded-submit::apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx::<Button className=\"h-10\" aria-label={t`Send`} type=\"submit\" leftIcon={<LuSend />} >",+ "no-unguarded-submit::apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx::<Button variant=\"destructive\" type=\"submit\">",+ "no-unguarded-submit::apps/erp/app/modules/sales/ui/SalesRules/SalesRuleAssignmentsList.tsx::<IconButton type=\"submit\" icon={<LuTrash />} aria-label={ isBroadcast ? t`Edit the rule's item filters to remove it` : t`Unassign rule` } title={ isBroadcast ? t`Edit the rule's item filters to remove it` : undefined } variant=\"ghost\" size=\"sm\" isDisabled={!canUpdate || isBroadcast} />",+ "no-unguarded-submit::apps/erp/app/modules/settings/ui/Theme/ThemeForm.tsx::<Button key={t.name} variant=\"secondary\" type=\"submit\" className={cn( \"justify-start w-full\", isActive && \"border-2 border-primary\" )} style={ { \"--theme-primary\": `hsl(${ t?.activeColor[mode === \"dark\" ? \"dark\" : \"light\"] })` } as React.CSSProperties } >",+ "no-unguarded-submit::apps/erp/app/routes/_oauth+/authorize.tsx::<Button type=\"submit\" size=\"lg\" className=\"w-full\">",+ "no-unguarded-submit::apps/erp/app/routes/_public+/invite.$code.tsx::<Button type=\"submit\">",+ "no-unguarded-submit::apps/erp/app/routes/_public+/invite.$code.tsx::<Button {...fade} transition={{ duration: 1.2, ease: \"easeInOut\", delay: 1.5 }} size=\"lg\" type=\"submit\" autoFocus >",+ "no-unguarded-submit::apps/erp/app/routes/_public+/mfa.tsx::<Button type=\"submit\" variant=\"link\" size=\"sm\">",+ "no-unguarded-submit::apps/erp/app/routes/_public+/unlock.tsx::<Button type=\"submit\" variant=\"link\" size=\"sm\">",+ "no-unguarded-submit::apps/erp/app/routes/onboarding+/plan.tsx::<IconButton size=\"lg\" type=\"submit\" variant=\"ghost\" icon={<LuMoveLeft />} aria-label={t`Back`} />",+ "no-unguarded-submit::apps/erp/app/routes/select-company+/_index.tsx::<button type=\"submit\" className=\"font-medium text-foreground hover:underline\" >",+ "no-unguarded-submit::apps/erp/app/routes/x+/templates+/shared.tsx::<IconButton size=\"sm\" variant=\"ghost\" type=\"submit\" aria-label=\"Delete section\" icon={<LuTrash2 />} />",+ "no-unguarded-submit::apps/mes/app/components/JobOperation/components/Chat.tsx::<Button className=\"h-10\" aria-label=\"Send\" type=\"submit\" leftIcon={<LuArrowUp />} >",+ "no-unguarded-submit::apps/mes/app/components/SessionLockOverlay.tsx::<Button type=\"submit\" variant=\"link\" size=\"sm\" className=\"text-muted-foreground\" >",+ "no-unguarded-submit::apps/mes/app/components/UserNav.tsx::<button ref={consoleSubmitRef} className=\"sr-only\" type=\"submit\" />",+ "no-unguarded-submit::apps/mes/app/components/UserNav.tsx::<button ref={modeSubmitRef} className=\"sr-only\" type=\"submit\" />",+ "no-unguarded-submit::apps/mes/app/components/UserNav.tsx::<button type=\"submit\" className=\"w-full flex items-center\">",+ "no-unguarded-submit::apps/mes/app/routes/_public+/mfa.tsx::<Button type=\"submit\" variant=\"link\" size=\"sm\">",+ "no-unguarded-submit::apps/mes/app/routes/_public+/unlock.tsx::<Button type=\"submit\" variant=\"link\" size=\"sm\">",+ "no-unguarded-submit::apps/mes/app/routes/x+/_layout.tsx::<Button type=\"submit\" variant=\"link\" size=\"sm\" className=\"w-full text-muted-foreground\" >",+ "no-unguarded-submit::packages/react/src/Acknowledge.tsx::<Button type=\"submit\" variant=\"ghost\" size=\"lg\" className=\"hover:bg-transparent text-white hover:text-white\" rightIcon={<LuArrowUpRight />} >",+ "no-unguarded-submit::packages/react/src/Acknowledge.tsx::<IconButton type=\"submit\" aria-label=\"Close\" variant=\"ghost\" className=\"text-white dark:text-white hover:text-white\" icon={<LuX />} />","no-unscoped-kysely-write::packages/jobs/src/inngest/functions/scheduled/purge-company.ts::.deleteFrom(\"companyGroup\")","no-view-without-invoker::20230123004409_permissions.sql::CREATE VIEW \"modules\" AS","no-view-without-invoker::20230123004436_employee.sql::CREATE OR REPLACE VIEW \"companies\" AS",diff --git a/packages/checks/src/conformance/no-unguarded-submit.test.ts b/packages/checks/src/conformance/no-unguarded-submit.test.tsnew file mode 100644index 0000000000..fb3099c851--- /dev/null+++ b/packages/checks/src/conformance/no-unguarded-submit.test.ts@@ -0,0 +1,157 @@+import { describe, expect, it } from "vitest";+import { noUnguardedSubmit } from "./no-unguarded-submit";++const scan = (contents: string, file = "apps/erp/app/modules/x/ui/Y.tsx") =>+ noUnguardedSubmit.scan(file, contents);++describe("noUnguardedSubmit", () => {+ it("flags a bare submit button inside a fetcher.Form", () => {+ const found = scan(`+ <fetcher.Form method="post" action={path.to.newReceipt}>+ <Button type="submit">New</Button>+ </fetcher.Form>+ `);+ expect(found).toHaveLength(1);+ expect(found[0]?.line).toBe(3);+ expect(found[0]?.snippet).toBe('<Button type="submit">');+ });++ // The regression this check exists for: `loading` was the modal's data-fetch+ // flag, not its submission state, so the button stayed live for the seconds+ // the action spent rendering a PDF and emailing the customer.+ it("flags isDisabled bound to something that is not an in-flight signal", () => {+ expect(scan('<Button isDisabled={loading} type="submit">')).toHaveLength(1);+ });++ it.each([+ [+ '<Button isDisabled={fetcher.state !== "idle"} type="submit">',+ "fetcher state"+ ],+ [+ '<Button isDisabled={statusFetcher.state !== "idle"} type="submit">',+ "named fetcher"+ ],+ [+ '<Button isLoading={isLoading} isDisabled={isLoading} type="submit">',+ "isLoading"+ ],+ [+ '<Button isDisabled={navigation.state !== "idle"} type="submit">',+ "navigation"+ ],+ ['<Button isDisabled={isSubmitting} type="submit">', "isSubmitting"]+ ])("accepts a guarded button (%s)", (tag) => {+ expect(scan(tag)).toHaveLength(0);+ });++ it("ignores buttons inside a ValidatedForm — the form refuses a re-entrant submit", () => {+ expect(+ scan(`+ <ValidatedForm validator={v} method="post">+ <Button type="submit">Save</Button>+ </ValidatedForm>+ `)+ ).toHaveLength(0);+ });++ it("flags a button after a ValidatedForm has closed", () => {+ expect(+ scan(`+ <ValidatedForm validator={v}><Button type="submit">A</Button></ValidatedForm>+ <fetcher.Form><Button type="submit">B</Button></fetcher.Form>+ `)+ ).toHaveLength(1);+ });++ it("handles a multi-line tag and a > inside an expression", () => {+ const found = scan(`+ <Button+ isDisabled={count > 0}+ type="submit"+ >+ Go+ </Button>+ `);+ expect(found).toHaveLength(1);+ expect(found[0]?.snippet).toBe(+ '<Button isDisabled={count > 0} type="submit" >'+ );+ });++ it("flags a lowercase <button> too", () => {+ expect(scan('<button type="submit">Log out</button>')).toHaveLength(1);+ });++ // A signal that only changes a tooltip disables nothing.+ it("rejects an in-flight signal on a prop that does not disable", () => {+ expect(+ scan('<Button title={isSubmitting ? "Saving" : "Save"} type="submit">')+ ).toHaveLength(1);+ });++ // A guard is routinely held in a local, so the scanner resolves one hop.+ it("resolves a guard held in a local variable", () => {+ expect(+ scan(`+ const busy = fetcher.state !== "idle";+ <Button isLoading={busy} type="submit">Go</Button>+ `)+ ).toHaveLength(0);+ });++ it("rejects a local that names no submit state", () => {+ expect(+ scan(`+ const [loading, setLoading] = useState(true);+ <Button isDisabled={loading} type="submit">Go</Button>+ `)+ ).toHaveLength(1);+ });++ it("rejects isLoading bound to a constant — it disables nothing", () => {+ expect(scan('<Button isLoading={false} type="submit">')).toHaveLength(1);+ });++ it("accepts a bare isLoading — always true, so always disabled", () => {+ expect(scan('<Button isLoading type="submit">')).toHaveLength(0);+ });++ it("requires isDisabled/disabled to name a submit state", () => {+ expect(+ scan('<Button isDisabled={isSubmitting} type="submit">')+ ).toHaveLength(0);+ expect(scan('<Button disabled={busy} type="submit">')).toHaveLength(1);+ expect(+ scan(+ '<Button isDisabled={!permissions.can("create", "sales")} type="submit">'+ )+ ).toHaveLength(1);+ });++ it("matches type at an attribute boundary, both quote styles", () => {+ expect(scan("<Button type='submit'>")).toHaveLength(1);+ expect(scan('<Button data-type="submit" type="button">')).toHaveLength(0);+ });++ it("does not let a ValidatedForm-prefixed component grant the exemption", () => {+ expect(+ scan(`+ <ValidatedFormProvider>+ <Button type="submit">Save</Button>+ </ValidatedFormProvider>+ `)+ ).toHaveLength(1);+ });++ it("ignores a non-submit button", () => {+ expect(scan("<Button onClick={go}>Go</Button>")).toHaveLength(0);+ });++ it("does not scan .ts files or the Submit component itself", () => {+ expect(scan('<Button type="submit">', "apps/erp/app/x.ts")).toHaveLength(0);+ expect(+ scan('<Button type="submit">', "packages/form/src/components/Submit.tsx")+ ).toHaveLength(0);+ });+});diff --git a/packages/checks/src/conformance/no-unguarded-submit.ts b/packages/checks/src/conformance/no-unguarded-submit.tsnew file mode 100644index 0000000000..9d3fdd9fe3--- /dev/null+++ b/packages/checks/src/conformance/no-unguarded-submit.ts@@ -0,0 +1,195 @@+import type { ConformanceCheck, Violation } from "../check";++// A submit button that stays live while its own submission is in flight posts+// again on every extra click, and each POST runs to completion on the server —+// `fetcher.submit` aborts the previous BROWSER request, but nothing in a route+// action reads `request.signal`. That is how finalizing one quote emailed the+// customer the same PDF three times (QuoteFinalizeModal, 2026-09-29): the+// action renders a PDF, uploads it, writes the document row and sends the mail,+// and for those several seconds the button was enabled and not even spinning.+//+// The repo has two correct shapes, and this check exists to keep them:+// - inside a ValidatedForm → `<Submit>` (@carbon/form), which disables on+// `isSubmitting`. ValidatedForm additionally refuses a re-entrant submit,+// so buttons under one are not flagged at all (see IN_VALIDATED_FORM).+// - inside a `fetcher.Form` / `<Form>` → `isDisabled={fetcher.state !== "idle"}`+// plus `isLoading`, as QuoteHeader and FinalizeRFQModal do.+//+// The absent spinner matters as much as the absent disable: with no feedback,+// clicking again is the reasonable thing for a user to do.++// An in-flight SIGNAL, not merely the presence of `isDisabled`. The quote bug+// was `isDisabled={loading}`, where `loading` was the modal's data-fetch flag —+// a check that accepted any `isDisabled` would have passed the exact line it+// exists to catch. Word boundaries are load-bearing: `loading` must not satisfy+// `isLoading`.+const IN_FLIGHT_SIGNAL =+ /\bisLoading\b|\bisSubmitting\b|\bisPending\b|\bisSaving\b|\buseIsSubmitting\b|\b\w*(?:fetcher|navigation|transition)\w*\.(?:state|formAction)\b/i;++// Props that actually disable the button. All three are checked the same way —+// the bound expression must name an in-flight signal. Presence alone is not+// enough: `isLoading={false}` spins nothing and disables nothing, and+// `isDisabled={loading}` bound to a data-fetch flag is the exact bug this+// check exists to catch.+const DISABLING_PROPS = ["disabled", "isDisabled", "isLoading"];++// A bare `isLoading` with no expression is `true` — permanently disabled, so+// a second submit is impossible.+const BARE_LOADING_PROP = /\bisLoading\s*(?:\/?>|\s+[a-zA-Z-]+\s*=|\s*$)/;++// Match `type` at an attribute boundary, both JSX quote styles. Searching for+// the bare text matched `data-type="submit"` on a non-submit button and missed+// `type='submit'`.+const SUBMIT_ATTR = /(?:^|[\s{])type\s*=\s*["']submit["']/;++// Where the two guards are DEFINED. `<Submit>` renders `type="submit"` and is+// the component this check tells everyone else to use.+const EXCLUDED_FILES = new Set(["packages/form/src/components/Submit.tsx"]);++const OPEN_TAG = /<(Button|button|IconButton)[\s>]/g;++/**+ * Text of a JSX opening tag starting at `start`, i.e. up to the `>` that closes+ * it — tracking brace depth and quotes so a `>` inside `{a > b}` or inside an+ * attribute string does not end the tag early. Returns null on an unterminated+ * tag rather than guessing.+ */+function openingTag(contents: string, start: number): string | null {+ let depth = 0;+ let quote: string | null = null;+ for (let i = start; i < contents.length; i++) {+ const c = contents[i];+ if (quote) {+ if (c === quote) quote = null;+ continue;+ }+ if (c === '"' || c === "'" || c === "`") {+ quote = c;+ continue;+ }+ if (c === "{") depth++;+ else if (c === "}") depth--;+ else if (c === ">" && depth === 0) return contents.slice(start, i + 1);+ }+ return null;+}++/** The `{...}` expression bound to `prop` in a JSX opening tag, brace-balanced. */+function propExpression(tag: string, prop: string): string | null {+ const at = new RegExp(`\\b${prop}\\s*=\\s*\\{`).exec(tag);+ if (!at) return null;+ const start = at.index + at[0].length;+ let depth = 1;+ for (let i = start; i < tag.length; i++) {+ if (tag[i] === "{") depth++;+ else if (tag[i] === "}" && --depth === 0) return tag.slice(start, i);+ }+ return null;+}++/**+ * Does the tag disable itself while its own submission runs? The signal has to+ * sit on a prop that actually disables — finding `isSubmitting` anywhere in the+ * tag would accept `title={isSubmitting ? "Saving" : "Save"}`, which changes a+ * tooltip and nothing else.+ */+function isGuarded(tag: string, contents: string): boolean {+ if (BARE_LOADING_PROP.test(tag)) return true;+ return DISABLING_PROPS.some((prop) => {+ const expression = propExpression(tag, prop);+ return expression !== null && namesInFlightSignal(expression, contents);+ });+}++/**+ * Does `expression` name an in-flight signal, directly or through ONE hop of+ * same-file resolution? Guards are routinely held in a local — `isLoading={busy}`+ * over `const busy = fetcher.state !== "idle"` is a real guard, and demanding+ * the signal inline would flag a dozen correct call sites. Resolving the+ * binding is what lets the check accept those while still rejecting+ * `isDisabled={loading}` over `const [loading] = useState(true)`, whose+ * declaration names no submit state.+ *+ * One hop, never recursive: a chain long enough to matter is beyond what a+ * text scan should claim to understand, and the baseline is the escape hatch.+ */+function namesInFlightSignal(expression: string, contents: string): boolean {+ if (IN_FLIGHT_SIGNAL.test(expression)) return true;+ for (const identifier of expression.match(/[A-Za-z_$][\w$]*/g) ?? []) {+ const declaration = new RegExp(+ `\\b(?:const|let|var)\\s+${identifier}\\s*=([^;\n]*(?:\n(?!\\s*(?:const|let|var|function|return)\\b)[^;\n]*)*)`+ ).exec(contents);+ if (declaration && IN_FLIGHT_SIGNAL.test(declaration[1] ?? "")) return true;+ }+ return false;+}++/**+ * Is `index` inside a `<ValidatedForm>`? ValidatedForm drops a re-entrant+ * submit in `handleSubmit`, so a second click cannot produce a second POST+ * however the button is written — flagging those would be noise.+ *+ * Matches the complete tag name: a prefix match would let a hypothetical+ * `<ValidatedFormProvider>` exempt a button it establishes no guard for.+ */+const VALIDATED_FORM_OPEN = /<ValidatedForm(?![A-Za-z0-9_])/g;++function inValidatedForm(contents: string, index: number): boolean {+ VALIDATED_FORM_OPEN.lastIndex = 0;+ let open = -1;+ let match: RegExpExecArray | null = VALIDATED_FORM_OPEN.exec(contents);+ while (match !== null && match.index < index) {+ open = match.index;+ match = VALIDATED_FORM_OPEN.exec(contents);+ }+ if (open === -1) return false;+ const close = contents.indexOf("</ValidatedForm>", open);+ return close === -1 || close > index;+}++const lineOf = (contents: string, index: number) =>+ contents.slice(0, index).split("\n").length;++export const noUnguardedSubmit: ConformanceCheck = {+ id: "no-unguarded-submit",+ description:+ 'A submit button must disable while its submission is in flight — use <Submit> inside a ValidatedForm, or isDisabled={fetcher.state !== "idle"} with isLoading',+ provenance: {+ deprecates:+ 'raw <Button type="submit"> with no in-flight guard, which posts again on every click',+ replacedBy:+ "<Submit> from @carbon/form, or isDisabled/isLoading bound to the fetcher's state",+ since: "2026-09-30"+ },+ scan(file: string, contents: string): Violation[] {+ if (!file.endsWith(".tsx")) return [];+ if (EXCLUDED_FILES.has(file)) return [];++ const violations: Violation[] = [];+ OPEN_TAG.lastIndex = 0;+ let match: RegExpExecArray | null = OPEN_TAG.exec(contents);+ while (match !== null) {+ const start = match.index;+ const tag = openingTag(contents, start);+ if (+ tag &&+ SUBMIT_ATTR.test(tag) &&+ !isGuarded(tag, contents) &&+ !inValidatedForm(contents, start)+ ) {+ violations.push({+ file,+ line: lineOf(contents, start),+ // One line, so the baseline key stays stable when the tag is+ // reformatted across lines.+ snippet: tag.replace(/\s+/g, " ").trim(),+ message:+ "Submit button stays live while the submission is in flight — every extra click is another POST the server runs to completion. Bind isDisabled/isLoading to the fetcher's state, or use <Submit> inside a ValidatedForm"+ });+ }+ OPEN_TAG.lastIndex = start + 1;+ match = OPEN_TAG.exec(contents);+ }+ return violations;+ }+};diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.tsindex b727f7105f..50cb094526 100644--- a/packages/checks/src/index.ts+++ b/packages/checks/src/index.ts@@ -19,6 +19,7 @@ export { noNumericPrecision } from "./conformance/no-numeric-precision";export { noRawForwardedHeaders } from "./conformance/no-raw-forwarded-headers";export { noRawRounding } from "./conformance/no-raw-rounding";export { noRequiredColumnWithoutDefault } from "./conformance/no-required-column-without-default";+export { noUnguardedSubmit } from "./conformance/no-unguarded-submit";export { noZeroConcurrency } from "./conformance/no-zero-concurrency";export {type Invariant,diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.tsindex 6b3bd52c21..8dff502abd 100644--- a/packages/checks/src/run.ts+++ b/packages/checks/src/run.ts@@ -22,6 +22,7 @@ import { noNumericPrecision } from "./conformance/no-numeric-precision";import { noRawForwardedHeaders } from "./conformance/no-raw-forwarded-headers";import { noRawRounding } from "./conformance/no-raw-rounding";import { noRequiredColumnWithoutDefault } from "./conformance/no-required-column-without-default";+import { noUnguardedSubmit } from "./conformance/no-unguarded-submit";import { noUnroundedTrackedQuantity } from "./conformance/no-unrounded-tracked-quantity";import { noUnscopedKyselyWrite } from "./conformance/no-unscoped-kysely-write";import { noViewWithoutInvoker } from "./conformance/no-view-without-invoker";@@ -57,7 +58,8 @@ export const TS_CHECKS: ConformanceCheck[] = [noDefaultOnEffects,noUnroundedTrackedQuantity,noIntegrationIdBranching,- noUnscopedKyselyWrite+ noUnscopedKyselyWrite,+ noUnguardedSubmit];/** Checks that run once per edge function, over all of its .ts files. */diff --git a/packages/form/src/ValidatedForm.tsx b/packages/form/src/ValidatedForm.tsxindex 10d88f174a..7eb110abd4 100644--- a/packages/form/src/ValidatedForm.tsx+++ b/packages/form/src/ValidatedForm.tsx@@ -318,6 +318,7 @@ export function ValidatedForm<const reset = useFormStore(formId, (state) => state.reset);const startSubmit = useFormStore(formId, (state) => state.startSubmit);const endSubmit = useFormStore(formId, (state) => state.endSubmit);+ const isSubmitting = useFormStore(formId, (state) => state.isSubmitting);const syncFormProps = useFormStore(formId, (state) => state.syncFormProps);const setFormElementInState = useFormStore(formId,@@ -411,7 +412,34 @@ export function ValidatedForm<target: typeof e.currentTarget,nativeEvent: HTMLSubmitEvent["nativeEvent"]) => {+ // A submit already in flight owns this form. `fetcher.submit` aborts the+ // previous BROWSER request, but the server action it started runs to+ // completion regardless — nothing reads `request.signal` — so a second+ // POST is a second set of side effects: another PDF, another customer+ // email, another ledger write. Guarding here rather than on each submit+ // button is what makes it hold for every form, including the ones whose+ // button forgot. This is the same `isSubmitting` flag `<Submit>` already+ // trusts for its disabled state, so it clears down the same proven paths.+ if (isSubmitting) return;startSubmit();+ try {+ await runSubmit(e, target, nativeEvent);+ } catch (error) {+ // Validation and the caller's `onSubmit` are both awaited, so either can+ // reject before any router submission starts — and then no completion+ // hook exists to clear `isSubmitting`. That already left `<Submit>`+ // permanently disabled; with the re-entry guard above it would wedge the+ // whole form until unmount. Clear, then let the error surface.+ endSubmit();+ throw error;+ }+ };++ const runSubmit = async (+ e: FormEvent<HTMLFormElement>,+ target: typeof e.currentTarget,+ nativeEvent: HTMLSubmitEvent["nativeEvent"]+ ) => {const submitter = nativeEvent.submitter as HTMLFormSubmitter | null;const isValidSubmit = submitter?.form === target;diff --git a/packages/jobs/src/inngest/functions/notifications/delivery-failure.test.ts b/packages/jobs/src/inngest/functions/notifications/delivery-failure.test.tsnew file mode 100644index 0000000000..c900e17a98--- /dev/null+++ b/packages/jobs/src/inngest/functions/notifications/delivery-failure.test.ts@@ -0,0 +1,105 @@+import { NonRetriableError } from "inngest";+import { describe, expect, it } from "vitest";+import {+ emailDeliveryFailure,+ isRetryableEmailFailure,+ isRetryableSlackFailure,+ slackDeliveryFailure+} from "./delivery-failure";++const coded = (code: string, message = "boom") =>+ Object.assign(new Error(message), { code });++describe("email delivery failure", () => {+ // Raised during connect/greet/auth — before a recipient or any DATA is sent,+ // so the relay provably has nothing and a replay cannot duplicate.+ it.each([+ "ECONNECTION",+ "EDNS",+ "EAUTH",+ "ETLS"+ ])("retries %s — nothing reached the relay", (code) => {+ const error = emailDeliveryFailure(coded(code));+ expect(isRetryableEmailFailure(coded(code))).toBe(true);+ expect(error).not.toBeInstanceOf(NonRetriableError);+ expect(error.message).toContain(code);+ });++ // The regression this whole PR exists for: nodemailer raises these at ANY+ // phase, so one can mean "relay accepted it, then the connection dropped".+ // Retrying that is how one quote becomes three copies in an inbox.+ it.each([+ "ETIMEDOUT",+ "ESOCKET"+ ])("does NOT retry %s — delivery is ambiguous", (code) => {+ expect(isRetryableEmailFailure(coded(code))).toBe(false);+ expect(emailDeliveryFailure(coded(code))).toBeInstanceOf(NonRetriableError);+ });++ it("does not retry a rejected envelope — deterministic, never succeeds", () => {+ expect(emailDeliveryFailure(coded("EENVELOPE"))).toBeInstanceOf(+ NonRetriableError+ );+ });++ it("does not retry an error with no code — unclassifiable is not safe", () => {+ expect(isRetryableEmailFailure(new Error("socket hang up"))).toBe(false);+ expect(emailDeliveryFailure(new Error("socket hang up"))).toBeInstanceOf(+ NonRetriableError+ );+ });++ it("keeps the original message, and names the code when there is one", () => {+ expect(emailDeliveryFailure(coded("EAUTH", "bad creds")).message).toBe(+ "Email error (EAUTH): bad creds"+ );+ expect(emailDeliveryFailure(new Error("bad creds")).message).toBe(+ "Email error: bad creds"+ );+ });++ it.each([+ null,+ undefined,+ "a string",+ 42,+ {}+ ])("treats a non-Error rejection (%s) as terminal rather than throwing", (thrown) => {+ expect(isRetryableEmailFailure(thrown)).toBe(false);+ expect(emailDeliveryFailure(thrown)).toBeInstanceOf(NonRetriableError);+ });+});++describe("slack delivery failure", () => {+ // Only reachable with `rejectRateLimitedCalls: true` on the client — at the+ // SDK default a 429 sleeps the Retry-After and throws a bare Error with no+ // code, which lands in the ambiguous branch below.+ it("retries a rate limit — Slack provably did not post", () => {+ const rateLimited = coded("slack_webapi_rate_limited_error");+ expect(isRetryableSlackFailure(rateLimited)).toBe(true);+ expect(slackDeliveryFailure(rateLimited)).not.toBeInstanceOf(+ NonRetriableError+ );+ });++ it.each([+ ["slack_webapi_platform_error", "deterministic, e.g. channel_not_found"],+ ["slack_webapi_request_error", "network — may have posted"],+ ["slack_webapi_http_error", "non-200 — may have posted"]+ ])("does NOT retry %s (%s)", (code) => {+ expect(isRetryableSlackFailure(coded(code))).toBe(false);+ expect(slackDeliveryFailure(coded(code))).toBeInstanceOf(NonRetriableError);+ });++ it("does not retry a bare rate-limit error — the SDK default shape", () => {+ const bare = new Error("A rate limit was exceeded (retry-after: 30)");+ expect(isRetryableSlackFailure(bare)).toBe(false);+ expect(slackDeliveryFailure(bare)).toBeInstanceOf(NonRetriableError);+ });++ it("labels Slack errors distinctly from email ones", () => {+ expect(+ slackDeliveryFailure(coded("slack_webapi_platform_error", "nope")).message+ ).toBe("Slack error (slack_webapi_platform_error): nope");+ });+});diff --git a/packages/jobs/src/inngest/functions/notifications/delivery-failure.ts b/packages/jobs/src/inngest/functions/notifications/delivery-failure.tsnew file mode 100644index 0000000000..ce55524044--- /dev/null+++ b/packages/jobs/src/inngest/functions/notifications/delivery-failure.ts@@ -0,0 +1,73 @@+import { NonRetriableError } from "inngest";++/**+ * Deciding whether a failed message delivery may be replayed.+ *+ * Neither SMTP nor `chat.postMessage` carries an idempotency key, so "did that+ * one land?" is not a question we can ask after the fact. The rule is therefore+ * asymmetric on purpose: replay only failures that PROVABLY delivered nothing,+ * and treat every other failure as terminal. A missed message is recoverable by+ * re-sending; a duplicated one is a customer receiving the same quote three+ * times, which is not.+ *+ * Pure so the decision can be pinned by tests — the callers own the I/O.+ */++/**+ * Nodemailer codes raised while connecting, greeting or authenticating, i.e.+ * before a single recipient or byte of DATA reaches the relay.+ *+ * `ETIMEDOUT` and `ESOCKET` are deliberately absent: nodemailer raises those at+ * ANY phase, so either can mean the relay accepted the message and then dropped+ * the connection before the final ack.+ */+const RETRYABLE_SMTP_CODES = new Set(["ECONNECTION", "EDNS", "EAUTH", "ETLS"]);++/**+ * The only Slack failure that provably posted nothing. A platform error is+ * deterministic (`channel_not_found` will not fix itself) and a request or HTTP+ * error is ambiguous — Slack may have accepted the message before the response+ * was lost.+ *+ * Reaching this requires `rejectRateLimitedCalls: true` on the client: at the+ * SDK default a 429 sleeps the whole Retry-After and then throws a bare Error+ * with no `code`, which lands in the ambiguous branch below.+ */+const RETRYABLE_SLACK_CODES = new Set(["slack_webapi_rate_limited_error"]);++const codeOf = (error: unknown): string | undefined =>+ typeof error === "object" && error !== null+ ? (error as { code?: unknown }).code === undefined+ ? undefined+ : String((error as { code?: unknown }).code)+ : undefined;++const messageOf = (error: unknown): string =>+ error instanceof Error ? error.message : String(error);++/** Throwing this lets Inngest retry; a `NonRetriableError` ends the run. */+const failure = (label: string, error: unknown, retryable: boolean): Error => {+ const code = codeOf(error);+ const message = `${label} error${code ? ` (${code})` : ""}: ${messageOf(error)}`;+ return retryable ? new Error(message) : new NonRetriableError(message);+};++/** True only when the send provably never reached the relay. */+export const isRetryableEmailFailure = (error: unknown): boolean => {+ const code = codeOf(error);+ return code !== undefined && RETRYABLE_SMTP_CODES.has(code);+};++/** True only when Slack provably did not post the message. */+export const isRetryableSlackFailure = (error: unknown): boolean => {+ const code = codeOf(error);+ return code !== undefined && RETRYABLE_SLACK_CODES.has(code);+};++/** The error to throw for a failed email send, classified. */+export const emailDeliveryFailure = (error: unknown): Error =>+ failure("Email", error, isRetryableEmailFailure(error));++/** The error to throw for a failed Slack post, classified. */+export const slackDeliveryFailure = (error: unknown): Error =>+ failure("Slack", error, isRetryableSlackFailure(error));diff --git a/packages/jobs/src/inngest/functions/notifications/send-email.ts b/packages/jobs/src/inngest/functions/notifications/send-email.tsindex 3890cbc32a..275c0c7230 100644--- a/packages/jobs/src/inngest/functions/notifications/send-email.ts+++ b/packages/jobs/src/inngest/functions/notifications/send-email.ts@@ -2,6 +2,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { sendEmail } from "@carbon/lib/email.server";import { NonRetriableError } from "inngest";import { inngest } from "../../client";+import { emailDeliveryFailure } from "./delivery-failure";export const sendEmailFunction = inngest.createFunction({@@ -47,16 +48,10 @@ export const sendEmailFunction = inngest.createFunction(text: payload.text,to: toRecipients});- if (response.error) {- // A rejected envelope (bad recipient/sender address) will never- // succeed on retry.- if ((response.error as { code?: string }).code === "EENVELOPE") {- throw new NonRetriableError(- `Email envelope error: ${response.error.message}`- );- }- throw new Error(`Email error: ${response.error.message}`);- }+ // Retry only what provably never reached the relay; everything else is+ // terminal, because a replay of an ambiguous failure is how one click+ // becomes three copies in the customer's inbox.+ if (response.error) throw emailDeliveryFailure(response.error);// data is null when SMTP is not configured — email is disabled.return response.data;});diff --git a/packages/jobs/src/inngest/functions/notifications/send-slack.ts b/packages/jobs/src/inngest/functions/notifications/send-slack.tsindex fa332fcddf..b52a4fb4a4 100644--- a/packages/jobs/src/inngest/functions/notifications/send-slack.ts+++ b/packages/jobs/src/inngest/functions/notifications/send-slack.ts@@ -2,6 +2,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { resolveIntegrationSecrets } from "@carbon/ee";import { getSlackClient } from "@carbon/lib/slack.server";import { inngest } from "../../client";+import { slackDeliveryFailure } from "./delivery-failure";export const sendSlackFunction = inngest.createFunction({@@ -42,8 +43,22 @@ export const sendSlackFunction = inngest.createFunction(await step.run("post-message", async () => {// Client is a no-op on localhost — see slack.server.ts.- const slack = getSlackClient(accessToken);- await slack.sendMessage({ blocks, channel, text });+ // `retries: 0` because Inngest owns the retry policy here: the SDK's+ // default is ~10 attempts over ~30 minutes, which would both stall this+ // step and retry the ambiguous failures classified below.+ // `rejectRateLimitedCalls` so a 429 arrives as a RateLimitedError the+ // classifier can recognise. Left at its default, the SDK sleeps the+ // whole Retry-After inside this step and then throws a bare Error with+ // no `code`, which the classifier would read as ambiguous and drop.+ const slack = getSlackClient(accessToken, {+ retryConfig: { retries: 0 },+ rejectRateLimitedCalls: true+ });+ try {+ await slack.sendMessage({ blocks, channel, text });+ } catch (err) {+ throw slackDeliveryFailure(err);+ }});return { success: true };diff --git a/packages/jobs/src/inngest/functions/tasks/onboard.ts b/packages/jobs/src/inngest/functions/tasks/onboard.tsindex d793576ba5..ec4595a228 100644--- a/packages/jobs/src/inngest/functions/tasks/onboard.ts+++ b/packages/jobs/src/inngest/functions/tasks/onboard.ts@@ -232,7 +232,9 @@ export const onboardFunction = inngest.createFunction(await step.run("send-slack-customer-notification", async () => {try {- slack.sendMessage({+ // Awaited: sendMessage rethrows now, and an unawaited rejection+ // would escape this catch as an unhandled rejection.+ await slack.sendMessage({channel: "#sales",text: "New Customer",blocks: [diff --git a/packages/lib/src/slack.server.ts b/packages/lib/src/slack.server.tsindex 8a81c41721..c2f1291c1c 100644--- a/packages/lib/src/slack.server.ts+++ b/packages/lib/src/slack.server.ts@@ -33,7 +33,12 @@ class SlackClient {blocks});} catch (error) {+ // Log, then RETHROW. Swallowing here made every caller's own catch dead+ // code and let a failed post report success — `send-slack` classified+ // errors it could never receive and settled `{ success: true }`. All+ // callers already wrap this in a try/catch of their own.log.error("Error sending Slack message", { channel, error });+ throw error;}}}diff --git a/packages/react/src/Acknowledge.tsx b/packages/react/src/Acknowledge.tsxindex 3ea0a6e8ec..da67605745 100644--- a/packages/react/src/Acknowledge.tsx+++ b/packages/react/src/Acknowledge.tsx@@ -1,6 +1,6 @@import type { ComponentProps, ReactNode } from "react";import { useEffect } from "react";-import { Form, useFetcher } from "react-router";+import { Form, useFetcher, useNavigation } from "react-router";import { Button } from "./Button";import type useDisclosure from "./hooks/useDisclosure";import {@@ -408,9 +408,15 @@ function FormButton({variant?: ComponentProps<typeof Button>["variant"];isDisabled?: boolean;}) {+ const navigation = useNavigation();return (<Form method="post" action={action}>- <Button type="submit" variant={variant} isDisabled={isDisabled}>+ <Button+ type="submit"+ variant={variant}+ isDisabled={isDisabled}+ isLoading={navigation.formAction === action}+ >{children}</Button></Form>diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsxindex e521c5ddf5..92bc492d20 100644--- a/packages/react/src/Button.tsx+++ b/packages/react/src/Button.tsx@@ -211,7 +211,14 @@ const Button = forwardRef<HTMLButtonElement, ButtonProps>(}))}type={asChild ? undefined : (props.type ?? "button")}- disabled={isDisabled || props.disabled}+ // `isLoading` disables too. It already blocks the keyboard path via+ // `useShortcutKeys` above, so leaving it out here made the component+ // internally inconsistent: a spinning button refused Enter but still+ // took a mouse click. Every call site that guards a submit with+ // `isLoading={fetcher.state !== "idle"}` — and there are many — was+ // therefore showing a spinner over a live button, which is worse than+ // no spinner: it says "working on it" while accepting another click.+ disabled={isDisabled || props.disabled || isLoading}role={asChild ? undefined : "button"}ref={mergeRefs(ref, innerRef)}>