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: MES assembly step keyboard shortcuts — Space/Enter records, arrows navigate; clicker-safe guards
aashu15e79a167549
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 2945918f45..c454a4a544 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -1286,3 +1286,10 @@ as the breakdown. Name the two so they cannot be confused (`violations` vs**Applies to:** `packages/jobs/src/backups/scope.ts`(`findExportScopeViolationsDetailed`, `computeScopeExclusions`, `totalExcludedRows`),`Manifest.excludedRowsByTable`, and any future "N things are wrong" surface.++## Browser-testing MES flows that write data++- **Context:** Verifying AssemblyView keyboard shortcuts with agent-browser while editing the same file (Vite HMR live).+- **Problem:** Step records appeared at timestamps with no corresponding keypress; hours went into suspecting the new code. Cause: overlapping test sessions — a page left open across HMR edits (sometimes with a modal up) replays/refires interactions, and interleaved key presses land on freshly auto-advanced steps.+- **Rule:** When a browser test writes rows, run it as a closed loop: wipe the rows, reload the page fresh, then check the DB after EVERY single action before pressing the next key. Never diagnose from an accumulated tail of prior test sessions.+- **Applies to:** agent-browser verification of any MES/ERP flow with side effects, especially while HMR is live.diff --git a/.ai/plans/2026-09-04-keyboard-shortcuts.md b/.ai/plans/2026-09-04-keyboard-shortcuts.mdnew file mode 100644index 0000000000..e25906a2bb--- /dev/null+++ b/.ai/plans/2026-09-04-keyboard-shortcuts.md@@ -0,0 +1,66 @@+# Keyboard Shortcuts — implementation plan (merged, executed)++**Spec / source:** `.ai/specs/2026-09-04-keyboard-shortcuts.md`+**Branch:** `fix/mes-ui-imp` (worktree `/Users/aashu/work/carbon/carbon-fix-mes-ui-imp`)+**Supersedes:** `2026-09-04-mes-assembly-step-shortcuts.md` + `2026-09-04-button-shortcut-prop.md`+(merged on user request; both fully executed — this file is the consolidated record).++## Progress — Part A: MES assembly step shortcuts+- [x] A1: Lift the current step's primary action into a parent-readable ref (`primaryStepActionRef`)+- [x] A2: Capture-phase document keydown listener (Space/Enter/←/→) with guards: modified-key,+ editable-target, dialog, barcode-wedge yield, armed-swallow window (750ms, added post-plan)+- [x] A3: Key badges on Mark done / Record / Skip (later migrated from `Kbd` glyphs to `ShortcutKey`)+- [x] A4: Typecheck + browser verification (records, navigation, gates; test data cleaned)++## Progress — Part B: Button `shortcut` prop+- [x] B1: Extend `useShortcutKeys` — `KeyboardKeys` enum, `ShortcutInput` (string | definition,+ single or array), `resolveShortcutKeys`, `parseShortcut`, `guard` option+- [x] B2: `ShortcutKey` — reference keycap styling + `SHORTCUT_KEY_ICON_MAP` (SVG glyphs, text fallback)+- [x] B3: `Button` — `shortcut` / `hideShortcutKey` props, merged ref, ref-click action, dialog+ guard, badge replaces `rightIcon` while visible; barrel exports (`KeyboardKeys`, `ShortcutInput`)+- [x] B4: Unit tests (`__tests__/useShortcutKeys.test.ts` — resolver + parser, 27 total green)+- [x] B5: Typecheck (react/mes/erp), tests, browser verification via temporary probe (reverted)++## Progress — Part C: post-build revisions (user-directed)+- [x] C1: String prop form (`"mod+s"`) passing straight through to react-hotkeys-hook+- [x] C2: MES badges migrated to `ShortcutKey`; Skip's `LuSkipForward` rightIcon removed+- [x] C3: `RecordModal` Record button (`Step.tsx`) given `shortcut="enter"`+- [x] C4: Armed clicker guard time-boxed to `ARMED_SWALLOW_MS = 750` so select-all + deliberate+ Enter submits (trade-off accepted: slow clicker re-press can submit the default)++## Files changed (all uncommitted; user commits manually)+- `apps/mes/app/components/AssemblyView.tsx` — listener, action ref, badges+- `apps/mes/app/components/JobOperation/components/Step.tsx` — RecordModal submit shortcut+- `packages/react/src/hooks/useShortcutKeys.ts` — enum, types, resolver, parser, guard+- `packages/react/src/ShortcutKey.tsx` — keycap restyle, icon map+- `packages/react/src/Button.tsx` — shortcut wiring+- `packages/react/src/index.tsx` — barrel exports+- `packages/react/src/__tests__/useShortcutKeys.test.ts` — new tests++## Verification record+```bash+pnpm --filter @carbon/react typecheck # green+pnpm --filter @carbon/react test # 27 passed (needed one-time: pnpm --filter @carbon/config build)+pnpm exec turbo run typecheck --filter=mes --filter=erp # green+```+Browser (dev stack, agent-browser): step record/navigate/gates on `/x/assembly/…`; modal+select-all + delayed-Enter submit; `mod+d`, `mod+enter` and array-of-bindings probes on a temp+Button usage (reverted); disabled/dialog-guard/hideShortcutKey checks. All test records and+auto-started labor events deleted from the dev DB afterwards.++## Known follow-ups (not planned here)+- Migrate ERP `useKeyboardShortcuts` call sites (e.g. `New.tsx`, Pagination) to the Button prop.+- Consider scopes/conflict detection if two mounted buttons ever claim one combo.++## Progress — Part D: thermo-nuclear review fixes+- [x] D1: Focused-button double-fire — `clickSelf` now `preventDefault()`s before ref-click+ (bare Enter/Space on a focused shortcut button fired native click + hotkey click);+ verified in browser: focused Record + Enter = exactly one record+- [x] D2: Dialog-open detection extracted to `packages/react/src/utils/dialog.ts`+ (`hasOpenDialog` / `isInsideOpenDialog`, barrel-exported) — used by Button and AssemblyView+- [x] D3: `parseShortcut` trims tokens ("mod + s" now valid); string bindings normalize through+ the same parse path as structured ones (suite green, 27 tests)+- [x] D4: `enabledOnInputElements` first-binding-only rule documented; badge render derived from+ a narrowed `badgeShortcut` local+- Deferred (discretionary): extracting AssemblyView's listener into a named hook; converging+ ERP's `useKeyboardShortcuts` onto `useShortcutKeys`diff --git a/.ai/research/mes-step-shortcuts.md b/.ai/research/mes-step-shortcuts.mdnew file mode 100644index 0000000000..fc5c2d65aa--- /dev/null+++ b/.ai/research/mes-step-shortcuts.md@@ -0,0 +1,57 @@+# Research: MES step-advance keyboard shortcuts++Date: 2026-09-04. Grounded against the codebase by an Explore agent; paths/line numbers verified at research time.++## 1. Shared Kbd / shortcut-hint components — already exist++| Component | Path | Notes |+|---|---|---|+| `Kbd` | `packages/react/src/Kbd.tsx:5-21` | Plain styled `<kbd>` (`bg-muted`, `border-b-[3px]`, mono bold). Exported from `@carbon/react` barrel (`index.tsx:176/:483`). |+| `ShortcutKey` | `packages/react/src/ShortcutKey.tsx:24-50` | Richer: `ShortcutDefinition`, mac/windows glyphs via `useOperatingSystem()`. Exported (`index.tsx:284/:570`). No app call sites. |+| `usePrettifyShortcut` | `packages/react/src/hooks/usePrettifyShortcut.ts` | Wraps `prettifyKeyboardShortcut` (`packages/utils/src/keyboard.ts:1`). |+| `CommandShortcut` | `packages/react/src/Command.tsx:249-263` | cmdk slot; unused by the ERP command palette. |++**Canonical hint pattern: `Tooltip` + `Kbd`** — cleanest reference is `apps/erp/app/components/New.tsx` (53 lines): `useKeyboardShortcuts({ n })` ref-clicks the button; tooltip shows `<Kbd>N</Kbd>`. Also `Pagination.tsx:95,113-141` (prettifyShortcut in tooltip) and ~10 explorer files with inline `<Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>`.++MES (`apps/mes/app/components`) has **zero** Kbd/shortcut usage today.++## 2. Keyboard-handling patterns++- `useKeyboardShortcuts` (`packages/react/src/hooks/useKeyboardShortcuts.ts`) — **the de-facto standard**, ~15 ERP call sites. Flat `{ key: handler }` map; combined keys fire on keydown, single keys on keyup; window listeners; built-in focus guard (`:14-21`) ignoring INPUT/TEXTAREA/SELECT/ProseMirror.+- `useShortcutKeys` (`useShortcutKeys.ts`) — react-hotkeys-hook wrapper, mac/win aware, `enableOnFormTags` opts; **no app call sites**. `[email protected]` is in the pnpm catalog and declared by apps/mes but never imported there.+- Only `Gantt.tsx:32,1327` uses `useHotkeys` directly.++## 3. AssemblyView (`apps/mes/app/components/AssemblyView.tsx`, 3418 lines)++- Step cursor is the `?step=` search param: `currentStep` `:774-780`, `goToStep(n)` `:1118-1127`, `isLastStep` `:1011`. Unit axis separate (`activeIndex` `:872`).+- Action bar `:2239-2273`: Record → `StepCompleteAction` (`:2910-3060`); Skip → inline `goToStep(currentStep + 1)` button `:2262-2271` (no named handler).+- `StepCompleteAction`: `markTaskDone()` `:2948-2954` (fetcher POST to `path.to.record`); `handleUndo()` `:2939`. Branches: done → undo pill; `type === "Task"` → "Mark done" button (only one-keystroke path); all other types → "Record" button opening `RecordModal`.+- Record disable = `hasPendingScans` (`:991`, from `pendingScanMaterials` `:988-990`) — a **soft gate; Skip deliberately bypasses it** (comment `:983-987`); warning renders `:2243-2250`.+- Step types (`procedureStepType`, `packages/database/src/types.ts:80473-80482`): `Value | Measurement | Checkbox | Timestamp | Person | List | File | Task | Inspection`. Null defaults to `"Task"` (`:2936`).+- **Auto-advance already exists** `:1140-1175`: when current step flips done, `goToStep(currentStep + 1)` and labor clock kicks.+- No keydown listener; **zero Lingui usage** — every string is a hardcoded English literal (pre-existing i18n debt).+- Gotcha: `markTaskDone` lives in child `StepCompleteAction`; `goToStep`/`hasPendingScans` live in parent → shortcut needs ref-click (New.tsx approach) or a lifted handler.++## 4. JobOperation standard view++- `Step.tsx` (`JobOperation/components/Step.tsx:94-270`): per-row flow — Task with no record → inline fetcher.Form "Complete" submit; other types → `onRecord(step)` opens `RecordModal` (in `JobOperation.tsx:2674-2690`, state `:448-459`).+- **No step cursor** — flat list; a step-advance shortcut has nothing to advance.+- `Controls.tsx` `StartStopButton:216-316` is a `ValidatedForm` submit (not onClick) — shortcut would need ref-click/form submit; existing `ButtonWithTooltip` is a natural Kbd hint host.++## 5. Focus guards & lessons++- `useKeyboardShortcuts.ts:14-21` is the repo's only generic guard (INPUT/TEXTAREA/SELECT + `.ProseMirror`; not generic contenteditable).+- `.ai/lessons.md:373-377` — react-aria NumberField swallows Enter/arrows; use `onKeyDownCapture`.+- `.ai/lessons.md:812-814` — bind nav keys at `document` in capture phase inside the owning component; `preventDefault`+`stopPropagation` only for claimed keys; never claim `Escape`.++## 6. Specs++- `.ai/specs/implemented/2026-07-14-mes-execution-views.md:399` lists "hands-free advance" as acknowledged future work. No spec defines a step-advancement contract; nothing gets violated.++## 7. i18n++MES fully wired for Lingui (`apps/mes/app/root.tsx:9,43,262-270`; catalog `packages/locale/locales/{locale}/mes`). New visible strings must use `useLingui()` `t` / `<Trans>`; run `pnpm lingui:extract` after.++## Practical summary++Reuse `Kbd` (+ optional Tooltip) and `useKeyboardShortcuts`; AssemblyView is the natural home (real cursor, `goToStep`, `markTaskDone`, auto-advance, soft scan gate). Only `Task` steps can complete in one keystroke — the other 8 types open `RecordModal`. The standard operation view has no cursor, so step-advance doesn't map there.diff --git a/.ai/specs/2026-09-04-keyboard-shortcuts.md b/.ai/specs/2026-09-04-keyboard-shortcuts.mdnew file mode 100644index 0000000000..e14e29a2e7--- /dev/null+++ b/.ai/specs/2026-09-04-keyboard-shortcuts.md@@ -0,0 +1,133 @@+# Keyboard Shortcuts — MES step advancement + app-wide Button `shortcut` prop++**Status:** Implemented (uncommitted) · **Date:** 2026-09-04 · **Branch:** `fix/mes-ui-imp`+**Research:** `.ai/research/mes-step-shortcuts.md`+**Supersedes:** `2026-09-04-mes-assembly-step-shortcuts.md` + `2026-09-04-button-shortcut-prop.md` (merged on user request)++## Summary / Problem++Two connected features, built in sequence:++1. **MES assembly view hands-free advance** — operators work away from the tablet (vehicle+ trolley); a Bluetooth clicker/pedal (a keyboard emitting Space/Enter/arrows) should advance+ procedure steps without walking back. Customer request; also listed as future work in+ `.ai/specs/implemented/2026-07-14-mes-execution-views.md:399`.+2. **App-wide Button shortcuts** — any `@carbon/react` `Button` can declare a hotkey via a prop,+ with a visible key badge, built on the previously dormant `useShortcutKeys` (react-hotkeys-hook+ wrapper) + `ShortcutKey` renderer.++## Goals++- Assembly view: Space/Enter fires the current step's primary action (Task → record instantly;+ input steps → open `RecordModal`); ←/→ navigate steps (→ ≡ Skip); visible key badges; every+ existing gate respected (pending-scan soft gate, modal semantics, typing focus).+- Button: `shortcut?: ShortcutInput | ShortcutInput[]` — string form (`"mod+s"`) or structured+ `ShortcutDefinition` (per-platform combos), arrays as alternative bindings (badge shows the+ first); `hideShortcutKey` keeps the hotkey and hides the badge; hotkey strictly follows+ disabled/loading; dialog-aware guard.+- `KeyboardKeys` enum as optional typed autocomplete for key names.+- Badges render as the reference keycap style, with centered SVG glyphs where mapped+ (`SHORTCUT_KEY_ICON_MAP`) and text fallback.++## Non-goals++- No scope/priority system; no conflict detection between two mounted buttons claiming a combo+ (last registered wins). No migration of ERP `useKeyboardShortcuts` call sites. No shortcut on+ the step Undo action (deliberate — a clicker must not be able to un-record work; it's an+ IconButton, so a badge wouldn't render anyway). No tooltip layer.++## Design++### MES assembly view (`apps/mes/app/components/AssemblyView.tsx`)++- One `document` keydown listener in the **capture phase** (per `.ai/lessons.md:812-814`), claims+ only Space/Enter/←/→ with `preventDefault`+`stopPropagation` (prevents focused-button+ double-fire), never Escape, never modified combos.+- The current step's primary action is lifted from `StepCompleteAction` into a parent ref+ (`primaryStepActionRef`), null when done/gated/submitting — the key is inert exactly when the+ button is.+- Guards, in order: modified-key → ignore; dialog open → armed-swallow window (below) else native+ semantics; editable target (INPUT/TEXTAREA/SELECT/contenteditable/ProseMirror) → ignore;+ barcode-wedge buffer non-empty → yield Enter to `useKeyboardWedge` (kanban scan-to-complete+ terminates with Enter).+- **Armed-swallow window:** for `ARMED_SWALLOW_MS = 750` after the shortcut opens a modal,+ Space/Enter are swallowed — the RecordModal autofocuses (and selects) its input, so a clicker+ double-press would natively submit the default value (reproduced: a 0 measurement). After the+ window a deliberate Enter submits normally; any other key or pointer tap ends the window early.+ Known trade-off (user-accepted): a clicker pressed again slowly on an input step can submit the+ default.+- Badges on Mark done/Record (`enter`) and Skip (`arrowright`) use the shared `ShortcutKey`+ renderer, `hidden md:flex`; Skip's `LuSkipForward` rightIcon was removed (badge owns the+ trailing slot).+- `RecordModal`'s Record button (`Step.tsx`) carries `shortcut="enter"` — badge in the modal, and+ Enter clicks it when focus isn't in a field (in-field Enter submits natively).++### Button prop (`packages/react/src/Button.tsx` + `hooks/useShortcutKeys.ts` + `ShortcutKey.tsx`)++- `ShortcutInput = string | ShortcutDefinition`; `resolveShortcutKeys()` normalizes one-or-many+ inputs to react-hotkeys-hook key strings; `parseShortcut()` splits a string (leading modifier+ tokens + key) or picks the platform arm, feeding the badge renderer.+- `KeyboardKeys` enum values are react-hotkeys-hook-compatible names (`"enter"`, `"arrowup"`,+ `"space"`, letters, digits).+- Button: internal ref merged with the forwarded ref; hotkey **ref-clicks** the button (preserves+ `type="submit"` form semantics; disabled click is a native no-op) with+ `enabled: !(isDisabled || disabled || isLoading)`; dialog guard = only buttons inside an open+ `[role="dialog"][data-state="open"]` respond while one exists; badge renders after the label,+ replaces `rightIcon` while visible, suppressed for `isIcon`/`isLoading` (IconButton inherits).+- `ShortcutKey` restyled to the reference keycap (fixed-height chip, `bg-white/10`,+ `rounded-[3px]`, shadow, backdrop blur, currentColor); `SHORTCUT_KEY_ICON_MAP` renders+ enter/space/backspace/arrows and mac ⌘⇧⌥ modifiers as centered lucide SVGs, text fallback+ otherwise (windows modifiers stay `Ctrl+`-style text).+- Exports added to the `@carbon/react` barrel: `KeyboardKeys`, `ShortcutInput` (hook, renderer,+ other types were already exported).++## Design Decisions++| Decision | Choice | Why |+|---|---|---|+| MES keys | Space/Enter = record, ←/→ = navigate | What clickers/page-turner pedals emit; user-approved |+| MES scope | Assembly view only | Only view with a step cursor (`?step=`); user-approved |+| MES listener | Own capture-phase document listener | Needs keydown+preventDefault double-fire safety; `useKeyboardShortcuts` fires single keys on keyup |+| Wedge coexistence | Enter yields while scan buffer non-empty | Kanban scan-to-complete terminates with Enter |+| Clicker double-press | Time-boxed 750ms swallow (was: until disarm) | User wants select-all + deliberate Enter to submit; window still catches rapid double-press |+| Non-Task step on Space/Enter | Open RecordModal | Visible feedback beats a silent no-op |+| Undo shortcut | None, deliberately | Clicker must not un-record; badge wouldn't render on an IconButton |+| Button engine | Extend dormant `useShortcutKeys` (react-hotkeys-hook) | User's direction; typed, platform-aware, zero call sites to break |+| Button prop shape | `string \| ShortcutDefinition`, single or array | User loosened from enum-only; strings pass through, arrays = alternatives |+| Trigger mechanism | Ref-click | Form-submit semantics; native disabled no-op |+| Modal behavior | Dialog-aware guard | Background hotkeys under a modal are bug reports waiting |+| Badge vs rightIcon | Badge replaces rightIcon while visible; leftIcon kept | Both trailing elements read cluttered; user-requested |+| Badge glyphs | `SHORTCUT_KEY_ICON_MAP` SVGs + text fallback | User's reference renderer flexibility; icons center better |+| Branch | `fix/mes-ui-imp` | Running dev stack for browser verification |++## Acceptance criteria (all verified in browser on the dev stack)++1. Assembly view: Space/Enter records a Task step (auto-advance follows); opens the RecordModal on+ input steps; inert while typing, while gated by pending scans, and during the 750ms window.+2. ←/→ navigate without recording; clamped at both ends; inert while a modal is open.+3. RecordModal: select-all default stays; Enter past the window (or after typing) submits; Record+ button shows the ↵ badge and responds to Enter when focus is outside fields.+4. `<Button shortcut="mod+s">` and structured/array forms trigger via the combo, render the keycap+ badge (SVG glyphs where mapped), respect disabled/loading, respect the dialog guard, submit+ forms for `type="submit"`, and `hideShortcutKey` hides only the badge.+5. `pnpm --filter @carbon/react typecheck|test` green (27 tests incl. resolver/parser suites);+ `turbo run typecheck --filter=mes --filter=erp` green.++## Open Questions (audit trail — resolved across both original specs)++- [x] MES keys / scope / hint UI / worktree — user picked recommended options.+- [x] Button prop shape — ShortcutDefinition+enum, then user loosened to strings; arrays for+ multiple bindings per action.+- [x] `hideShortcutKey` name; dialog-aware guard; same worktree — user-approved.++## Changelog++- 2026-09-04 — Both features specced, interviewed, implemented and browser-verified.+- 2026-09-04 — Execution discoveries folded in: barcode-wedge Enter yield; armed clicker guard+ (later time-boxed to 750ms at user request); `@carbon/config` needed a one-time build for vitest.+- 2026-09-04 — Post-build revisions (user-directed): string prop form; reference keycap styling;+ badge replaces rightIcon; SVG glyph map; MES badges migrated from hand-rolled `Kbd` to+ `ShortcutKey`; RecordModal Record button given `shortcut="enter"`.+- 2026-09-04 — Merged the two specs into this file; originals removed. Phantom-record scare during+ testing traced to overlapping test sessions across HMR edits, not shipped code (controlled+ repro: load creates nothing; Enter opens modal only; second Enter records exactly one row).diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsxindex d85f8662af..efcc3f2032 100644--- a/apps/mes/app/components/AssemblyView.tsx+++ b/apps/mes/app/components/AssemblyView.tsx@@ -21,6 +21,7 @@ import {DropdownMenuRadioItem,DropdownMenuTrigger,generateHTML,+ hasOpenDialog,IconButton,Modal,ModalBody,@@ -30,6 +31,7 @@ import {ModalOverlay,ModalTitle,Separator,+ ShortcutKey,SidebarTrigger,Spinner,Status,@@ -73,7 +75,6 @@ import {LuListFilter,LuPause,LuPlay,- LuSkipForward,LuTimer,LuTrash,LuUndo2,@@ -603,8 +604,10 @@ export function AssemblyView({});// Kanban barcode scan → complete the operation (matches the operation view).+ // The returned buffer is non-empty while a scan burst is in flight — the+ // keyboard-shortcut effect below yields Enter to the wedge during that window.const completeFetcher = useFetcher();- useKeyboardWedge({+ const wedgeBuffer = useKeyboardWedge({test: (input) =>kanban?.completedBarcodeOverride? input === kanban.completedBarcodeOverride@@ -990,6 +993,12 @@ export function AssemblyView({);const hasPendingScans = pendingScanMaterials.length > 0;+ // The current step's primary action (Mark done / open RecordModal), lifted via+ // ref so the keyboard-shortcut effect can trigger it from the parent. Null when+ // the step is done, gated, or submitting — the key is inert exactly when the+ // button is.+ const primaryStepActionRef = useRef<(() => void) | null>(null);+// Open production events per work type (to pass to the complete flow so it// can close them on completion).const openByType = (type: string) =>@@ -1174,6 +1183,77 @@ export function AssemblyView({if (!isLastStep) goToStep(currentStep + 1);}, [currentStep, currentStepDone, isLastStep, allStepsRecorded]);+ // ── Keyboard shortcuts (Bluetooth clicker / pedal friendly) ────────────────+ // Space/Enter fire the current step's primary action (Mark done, or open the+ // RecordModal for input steps); ←/→ navigate steps (→ ≡ Skip). Bound on+ // document in the CAPTURE phase so preventDefault lands before a focused+ // button's native click (Space clicks on keyup only if keydown wasn't+ // prevented; Enter clicks on keydown) — otherwise one press could both+ // record and re-trigger the focused button.+ // For a short window after the shortcut opens a modal, the action keys stay+ // swallowed — the RecordModal autofocuses (and selects) its input, so a+ // clicker DOUBLE-press would otherwise natively submit the form's DEFAULT+ // value (a 0 measurement). After the window a deliberate Enter submits+ // normally (the selected default is a valid thing to accept), and any other+ // key or a pointer tap ends the window early.+ const ARMED_SWALLOW_MS = 750;+ const shortcutArmedAtRef = useRef<number | null>(null);+ useEffect(() => {+ function handleShortcutKeyDown(event: KeyboardEvent) {+ if (event.metaKey || event.ctrlKey || event.altKey) return;+ const isAction = event.key === " " || event.key === "Enter";+ const isNext = event.key === "ArrowRight";+ const isPrev = event.key === "ArrowLeft";++ // Any open dialog (RecordModal, issue/scan modals, zoom) keeps native+ // key semantics — except the armed clicker swallow described above.+ if (hasOpenDialog()) {+ const armedAt = shortcutArmedAtRef.current;+ if (+ isAction &&+ armedAt !== null &&+ Date.now() - armedAt < ARMED_SWALLOW_MS+ ) {+ event.preventDefault();+ event.stopPropagation();+ } else {+ shortcutArmedAtRef.current = null;+ }+ return;+ }+ shortcutArmedAtRef.current = null;+ if (!isAction && !isNext && !isPrev) return;++ // A barcode wedge scan terminates with Enter — yield it to+ // useKeyboardWedge while a scan burst is buffered.+ if (event.key === "Enter" && wedgeBuffer !== "") return;++ const target = event.target;+ if (target instanceof Element) {+ if (["INPUT", "TEXTAREA", "SELECT"].includes(target.nodeName)) return;+ if (target.closest('[contenteditable="true"], .ProseMirror')) return;+ }++ event.preventDefault();+ event.stopPropagation();++ if (isAction) {+ shortcutArmedAtRef.current = Date.now();+ primaryStepActionRef.current?.();+ } else if (isNext && !isLastStep) goToStep(currentStep + 1);+ else if (isPrev && currentStep > 0) goToStep(currentStep - 1);+ }+ function handlePointerDown() {+ shortcutArmedAtRef.current = null;+ }+ document.addEventListener("keydown", handleShortcutKeyDown, true);+ document.addEventListener("pointerdown", handlePointerDown, true);+ return () => {+ document.removeEventListener("keydown", handleShortcutKeyDown, true);+ document.removeEventListener("pointerdown", handlePointerDown, true);+ };+ }, [currentStep, isLastStep, wedgeBuffer]);+// Stop the labor clock automatically once every step is recorded for this unit.const allDoneRef = useRef(allStepsRecorded);// biome-ignore lint/correctness/useExhaustiveDependencies: transition-detect on all-complete@@ -2256,6 +2336,7 @@ export function AssemblyView({activeIndex={activeIndex}done={isStepDone(step)}disabled={hasPendingScans}+ actionRef={primaryStepActionRef}/></div>)}@@ -2263,11 +2344,15 @@ export function AssemblyView({variant="outline"size="lg"className="shrink-0"- rightIcon={<LuSkipForward />}isDisabled={isLastStep}onClick={() => goToStep(currentStep + 1)}>Skip+ <ShortcutKey+ shortcut="arrowright"+ variant="medium"+ className="hidden md:flex"+ /></Button></div></div>@@ -2911,7 +2996,8 @@ function StepCompleteAction({step,activeIndex,done,- disabled = false+ disabled = false,+ actionRef}: {step: Step;activeIndex: number;@@ -2919,6 +3005,9 @@ function StepCompleteAction({// Soft gate: the step's tracked parts aren't fully issued for this unit, so// block completion (Mark done / Record) until they're scanned. Skip bypasses.disabled?: boolean;+ // Written every render with the primary action so the parent's Space/Enter+ // shortcut fires the same thing the button would.+ actionRef?: { current: (() => void) | null };}) {const fetcher = useFetcher();const user = useUser();@@ -2953,6 +3042,21 @@ function StepCompleteAction({fetcher.submit(fd, { method: "post", action: path.to.record });}+ // No dep array: re-assign every render so the shortcut always sees the+ // freshest closure; cleared on unmount so a stale action can't fire.+ useEffect(() => {+ if (!actionRef) return;+ actionRef.current =+ done || disabled || busy+ ? null+ : type === "Task"+ ? markTaskDone+ : recordModal.onOpen;+ return () => {+ actionRef.current = null;+ };+ });+// ── Already done: show recorded value + Undo button ──if (done && record) {let recordedDisplay: string | null = null;@@ -3019,6 +3123,11 @@ function StepCompleteAction({onClick={markTaskDone}>Mark done+ <ShortcutKey+ shortcut="enter"+ variant="medium"+ className="hidden md:flex"+ /></Button>);}@@ -3034,6 +3143,11 @@ function StepCompleteAction({onClick={recordModal.onOpen}>Record+ <ShortcutKey+ shortcut="enter"+ variant="medium"+ className="hidden md:flex"+ /></Button>{recordModal.isOpen && (<RecordModaldiff --git a/apps/mes/app/components/JobOperation/components/Step.tsx b/apps/mes/app/components/JobOperation/components/Step.tsxindex 68420bfaaf..ed65a98029 100644--- a/apps/mes/app/components/JobOperation/components/Step.tsx+++ b/apps/mes/app/components/JobOperation/components/Step.tsx@@ -667,6 +667,9 @@ export function RecordModal({(attribute.type === "File" && !filePath)}rightIcon={<LuCircleCheck />}+ // Focus in a field submits natively on Enter; this covers focus+ // elsewhere in the modal and renders the ↵ badge.+ shortcut="enter"type="submit"><Trans>Record</Trans>