fix(ui): keep the maxFiles budget in step within a single tick
Follow-up to #6939. CodeRabbit raised this on that PR, but the review landed after it was merged, so the fix needs its own PR.
The bug
attachmentCountRef.current = attachmentFiles.length is a render-time assignment. Two add() calls before the next render therefore both budget against the pre-add count, so each admits up to the full remaining capacity and together they can exceed maxFiles.
maxFiles = 5, tray empty
add(3 files) -> sees count 0, capacity 5, admits 3
add(3 files) -> still sees count 0 (no render yet), admits 3
=> 6 attachments
The fix
Advance the ref as each batch is admitted. The render-time assignment still re-syncs it from state afterwards, so removals and clears stay authoritative.
Why not CodeRabbit's suggestion
It proposed moving validation inside the setAttachmentFiles((prev) => ...) updater and using prev.length. That is the right instinct for freshness, but applyAttachmentConstraints calls onError, and React invokes state updaters twice under StrictMode — every rejection would fire two toasts. Correcting the budget in place keeps the side effect outside the updater.
Testing
bun test packages/ui/src— 50 passbun run --cwd packages/ui typecheck,bunx biome check
Not verified in the running app. Re-running the in-app cap test needs the new-workspace composer, and the workspace I had been testing in is mid-onboarding with no project after an unrelated setup.sh --force (its Neon branch had been deleted by the branch-cleanup sweep). The earlier in-app checks — 7 files against maxFiles={5} attaching 5 with a toast, 12MB against a 10MB cap attaching none — were run against the code this sits on top of, and this change only tightens the count between two calls in one tick.
Summary by cubic
Fixes a same-tick race where attachment count checks used a render-time snapshot, letting consecutive add() calls collectively exceed maxFiles and a clear(); add(...) reject files that now fit.
All list mutations now funnel through a synchronous mirror ref that updates the list and count before returning, and takeFiles() reads that mirror too — so a submit right after an add no longer clears files it never handed back. Validation stays outside the React state updater because StrictMode invokes updaters twice and would double the error toast.
Summary by CodeRabbit
- Bug Fixes
- Improved file attachment validation when adding multiple batches quickly.
- Attachment limits are now tracked accurately across consecutive additions, preventing invalid uploads caused by outdated counts.
- Multiple add actions in the same moment now consistently respect the configured attachment constraints.
- Attachment counts now remain synchronized with the selected files for more reliable upload behavior.
- Improved consistency when removing attachments or navigating away while files are selected.