Repository navigation
test(device): extract phase reducer + 35 unit/integration tests - #6
Conversation
Pulls the Phase union and transition logic out of AuthorizeDeviceClient into a pure `phaseReducer(state, action)` so the state machine can be tested without React, the DOM, or better-auth mocks. Component now calls `useReducer(phaseReducer, initialPhase)` and dispatches actions from handlers + the derivation effect. - apps/web/app/device/phase-reducer.ts — new pure module with the Phase union, PhaseAction union, `phaseReducer`, and state machine ASCII diagram as the file header - apps/web/app/device/phase-reducer.test.ts — 20 unit tests, 100% branch coverage of transitions including the `email ?? ""` regression from PR #3 review - apps/web/app/device/AuthorizeDeviceClient.tsx — switches to useReducer; "Try again" button collapses to a single SESSION_RESOLVED dispatch (no duplicated derivation logic) - apps/web/app/device/AuthorizeDeviceClient.test.tsx — 15 thin integration tests via @testing-library/react + jsdom covering the effect wiring, providers-prop conditional render, and async handler dispatch sites - apps/web/vitest.config.ts — new config wiring @vitejs/plugin-react for JSX transform + `@/*` alias. Default env stays node; integration test opts into jsdom via `/* @vitest-environment jsdom */` - apps/web/package.json — jsdom, @testing-library/{react, user-event, jest-dom}, @vitejs/plugin-react (dev deps) Result: 86 web tests pass (was 51). +35 new tests in <1s, typecheck clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 42 minutes and 39 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThis PR extracts a pure state machine ( Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
apps/web/app/device/phase-reducer.ts (1)
6-29: Nit: the ASCII diagram has a few mis-aligned arrows/boxes.The
approvingbox at line 17 is indented inconsistently with the arrow fromsigned-out, and a couple of stray|segments (lines 9, 19) don't connect to anything. Legible, but a quick pass to tidy would make this a reliable source of truth for future contributors. Skip if you'd rather not spend time on it.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/device/phase-reducer.ts` around lines 6 - 29, The ASCII state diagram in phase-reducer.ts has misaligned elements: move the "approving" box so its left edge aligns under the arrow coming from "signed-out" (so the device.approve arrow cleanly points into the box), remove the stray vertical bar segments that don't connect (the orphaned '|' near the top and near "approving"), and tidy spacing/indentation for the surrounding boxes ("signed-out", "approving", "approved") so arrows line up visually and the diagram remains a clear source of truth for the device phase states.apps/web/vitest.config.ts (1)
3-3: Optional: preferimport.meta.dirnameover__dirnamein this ESM config.
apps/web/package.jsonsets"type": "module", so__dirnameis not a native ESM global — it works here only because Vite transpiles the TS config through esbuild's CJS shim. Given@vitejs/plugin-react@6already requires Node ≥20.19, you can drop thenode:pathimport and use the built-inimport.meta.dirnamefor a cleaner ESM-native config.♻️ Proposed refactor
import { defineConfig } from "vitest/config" import react from "@vitejs/plugin-react" -import path from "node:path" // Vitest 4's default pipeline doesn't transform JSX in .tsx test files — // `@vitejs/plugin-react` wires up the automatic JSX runtime so component // tests like app/device/AuthorizeDeviceClient.test.tsx parse cleanly. // Test environment defaults to node (fast); jsdom-dependent files set // it per-file with a `/* `@vitest-environment` jsdom */` comment. export default defineConfig({ plugins: [react()], resolve: { alias: { - "@": path.resolve(__dirname, "."), + "@": import.meta.dirname, }, }, })Also applies to: 14-14
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/vitest.config.ts` at line 3, The config imports "node:path" and uses __dirname which is a CJS shim; remove the node:path import and replace usages of __dirname with the ESM-native import.meta.dirname, e.g. compute paths via new URL('.', import.meta.url).pathname or use import.meta.dirname (Node ≥20.19) where the code currently references __dirname so the TS/Vite config is fully ESM-native.apps/web/app/device/AuthorizeDeviceClient.test.tsx (1)
130-147: Copy-matched assertions are tightly coupled to UI strings.
/new provider or email/iand/new email creates one/iboth key off the exact phrasing inAuthorizeDeviceClient.tsxline 207-208. That's fine today, but any copy tweak (e.g., product asks for "Signing up") will break these tests with a confusing failure. Consider either asserting on a more stable anchor (e.g., presence/absence of the divider element) or extracting the string to a constant the test imports. Not blocking.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/device/AuthorizeDeviceClient.test.tsx` around lines 130 - 147, The test is brittle because it asserts on exact copy strings from the AuthorizeDeviceClient component; update AuthorizeDeviceClient.test.tsx to use a more stable anchor instead—either assert on the divider element (e.g., queryByRole or getByTestId for the divider) to confirm visibility/absence of the OAuth section or export the copy constant from AuthorizeDeviceClient and import it into the test to compare against that constant; adjust the assertions around screen.getByText(/new email creates one/i) and screen.getByText(/new provider or email/i) to use the chosen stable selector (divider test id/role) or the imported constant accordingly while leaving the render( <AuthorizeDeviceClient ... /> ) and provider fixtures (noProviders) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/web/app/device/AuthorizeDeviceClient.tsx`:
- Around line 31-49: The effect is re-triggering because the session object
reference is unstable; stabilize it before dispatching SESSION_RESOLVED by
memoizing the session (e.g., with useMemo or a small hook) and use that
stableSession in the useEffect dependency array instead of raw session, or
alternatively add a guard in phaseReducer to ignore SESSION_RESOLVED when
current phase is an in-progress auth state like "email-sent" or "approving";
update the useEffect that currently calls dispatch({ type: "SESSION_RESOLVED",
session, userCode }) to use the stableSession and keep dependencies to
[sessionPending, stableSession, userCode], and/or add the guard in phaseReducer
to avoid overwriting those phases.
In `@apps/web/package.json`:
- Around line 48-59: Update the package.json engines constraint to match
`@vitejs/plugin-react`@6.0.1's required Node floor: locate the "engines" field in
package.json (root/apps/web package.json) and change the node entry to
">=20.19.0 || >=22.12.0" so the engines block enforces the correct minimum Node
versions for functions that reference `@vitejs/plugin-react` (e.g., dev/build
scripts).
---
Nitpick comments:
In `@apps/web/app/device/AuthorizeDeviceClient.test.tsx`:
- Around line 130-147: The test is brittle because it asserts on exact copy
strings from the AuthorizeDeviceClient component; update
AuthorizeDeviceClient.test.tsx to use a more stable anchor instead—either assert
on the divider element (e.g., queryByRole or getByTestId for the divider) to
confirm visibility/absence of the OAuth section or export the copy constant from
AuthorizeDeviceClient and import it into the test to compare against that
constant; adjust the assertions around screen.getByText(/new email creates
one/i) and screen.getByText(/new provider or email/i) to use the chosen stable
selector (divider test id/role) or the imported constant accordingly while
leaving the render( <AuthorizeDeviceClient ... /> ) and provider fixtures
(noProviders) unchanged.
In `@apps/web/app/device/phase-reducer.ts`:
- Around line 6-29: The ASCII state diagram in phase-reducer.ts has misaligned
elements: move the "approving" box so its left edge aligns under the arrow
coming from "signed-out" (so the device.approve arrow cleanly points into the
box), remove the stray vertical bar segments that don't connect (the orphaned
'|' near the top and near "approving"), and tidy spacing/indentation for the
surrounding boxes ("signed-out", "approving", "approved") so arrows line up
visually and the diagram remains a clear source of truth for the device phase
states.
In `@apps/web/vitest.config.ts`:
- Line 3: The config imports "node:path" and uses __dirname which is a CJS shim;
remove the node:path import and replace usages of __dirname with the ESM-native
import.meta.dirname, e.g. compute paths via new URL('.',
import.meta.url).pathname or use import.meta.dirname (Node ≥20.19) where the
code currently references __dirname so the TS/Vite config is fully ESM-native.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: d902b02c-8450-4621-9bf8-f45a5d7f7634
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (7)
CHANGELOG.mdapps/web/app/device/AuthorizeDeviceClient.test.tsxapps/web/app/device/AuthorizeDeviceClient.tsxapps/web/app/device/phase-reducer.test.tsapps/web/app/device/phase-reducer.tsapps/web/package.jsonapps/web/vitest.config.ts
| "@testing-library/jest-dom": "^6.9.1", | ||
| "@testing-library/react": "^16.3.2", | ||
| "@testing-library/user-event": "^14.6.1", | ||
| "@types/node": "^25.1.0", | ||
| "@types/pg": "^8.20.0", | ||
| "@types/react": "^19.2.10", | ||
| "@types/react-dom": "^19.2.3", | ||
| "@vitejs/plugin-react": "^6.0.1", | ||
| "@workspace/eslint-config": "workspace:^", | ||
| "@workspace/typescript-config": "workspace:*", | ||
| "eslint": "^9.39.2", | ||
| "jsdom": "^29.0.2", |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify resolved vite/vitest versions and Node engines compatibility.
fd -t f 'pnpm-lock.yaml|package-lock.json|yarn.lock' --max-depth 3 | head -5
rg -n -C1 '"vite"|"vitest"' --type=json -g '!**/node_modules/**' apps/web package.json 2>/dev/null
fd -t f 'package.json' --max-depth 2 -x grep -l '"engines"' {} \; | head
cat package.json 2>/dev/null | jq '.engines // {}' 2>/dev/null
rg -n -C2 '^\s*"(vite|vitest)"' pnpm-lock.yaml 2>/dev/null | head -40Repository: Codehagen/helpbase
Length of output: 215
🏁 Script executed:
# Get resolved Vite version from pnpm-lock.yaml
rg -A 5 "^\s+vite:" pnpm-lock.yaml | head -30
# Check if apps/web has explicit vite or vitest deps
cat apps/web/package.json | grep -E '"(vite|vitest)"' || echo "No vite/vitest in apps/web/package.json"
# Look for CI config files
fd -t f '\.github|\.gitlab-ci|\.circleci|\.travis' --max-depth 2
# Find Node version in CI files
fd -t f -e yml -e yaml | head -10 | xargs grep -l "node" 2>/dev/null || echo "Searching..."Repository: Codehagen/helpbase
Length of output: 959
🏁 Script executed:
# Check Node version in CI workflows
find .github/workflows -name "*.yml" -o -name "*.yaml" 2>/dev/null | xargs grep -i "node" 2>/dev/null | head -20
# Also check root for Node engine spec
cat package.json | jq '.engines'
# Verify `@vitejs/plugin-react` 6.0.1 peer dependency requirements
rg -A 10 '@vitejs/plugin-react' pnpm-lock.yaml | head -50Repository: Codehagen/helpbase
Length of output: 1771
Update root package.json engines to enforce the Node version floor required by @vitejs/plugin-react@6.0.1.
@vitejs/plugin-react@6.0.1 requires node: ^20.19.0 || >=22.12.0, but package.json only specifies ">=20", which is too loose. The resolved Vite 8.0.7, Vitest 4.1.3, and all testing library deps are compatible with React 19.2.4 — however, the engines constraint should be tightened in the root package.json to reflect this requirement. Update to "engines": { "node": ">=20.19.0 || >=22.12.0" } to match the plugin's documented floor.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web/package.json` around lines 48 - 59, Update the package.json engines
constraint to match `@vitejs/plugin-react`@6.0.1's required Node floor: locate the
"engines" field in package.json (root/apps/web package.json) and change the node
entry to ">=20.19.0 || >=22.12.0" so the engines block enforces the correct
minimum Node versions for functions that reference `@vitejs/plugin-react` (e.g.,
dev/build scripts).
…sed, 1 TODO filed
Pre-landing review surfaced 12 findings across testing + adversarial
specialists. Applied all the ones worth fixing in this PR:
Auto-fixes (mechanical):
- phase-reducer.ts: freeze initialPhase + type as Readonly<Phase> so
the exported reference can't be accidentally mutated
- AuthorizeDeviceClient.test.tsx: tighten /check/i regex to
/for your.*sign-in link/i — prior matcher also matched "Checking
session…" on the loading screen
- phase-reducer.test.ts: rename and re-purpose the misleading
"empty userCode + null session" case to assert the guard ordering
(userCode check fires before session check)
New coverage (ASK items approved):
- AuthorizeDeviceClient.test.tsx: assert Cancel button is disabled
while approve is in flight. Without this, removing
`disabled={approving}` from Cancel would silently break the
"can't deny mid-approve" invariant.
- AuthorizeDeviceClient.test.tsx: assert all sign-in surfaces
(GitHub button, email submit) disable while a social redirect is
in flight. Prevents concurrent OAuth redirects from a
double-click.
Filed TODO-021 for a pre-existing bug the adversarial review
surfaced: `SESSION_LOADING` clobbers non-loading phases, so a
background Better Auth session refresh wipes `email-sent` back to
the spinner. Not introduced by this refactor; worth a standalone
follow-up.
Tests: 88 pass (was 86; +2 new). Typecheck clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
CodeRabbit flagged a real regression path (confirmed with upstream bug reports): better-auth's useSession() doesn't memoize its return, so any re-render can re-fire the derivation effect even when session data is unchanged. Without a guard, a user watching "Check your email" gets bounced to the sign-in form when the session reference updates. Fix: SESSION_LOADING and SESSION_RESOLVED now only apply when the current phase is derivable (loading / signed-out / signed-in / error). In-progress and terminal phases (email-sent, approving, approved, denied) ignore background session refreshes. - phase-reducer.ts: `isDerivable()` helper + guard in both SESSION_* branches. Error intentionally stays derivable so "Try again" still routes correctly. - phase-reducer.test.ts: +2 tests asserting preservation of email-sent/approving/approved/denied across SESSION_LOADING and SESSION_RESOLVED - package.json: bump Node engines floor to `^20.19.0 || >=22.12.0` per @vitejs/plugin-react@6.0.1 - TODOS.md: drop TODO-021 (closed by this commit) Tests: 90 pass (was 88). Typecheck clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Summary
Extracts the 8-phase `Phase` state machine from `AuthorizeDeviceClient` into a pure `phaseReducer` function, then adds 35 tests on top — 20 pure-function reducer tests (100% branch coverage) and 15 thin integration tests via React Testing Library + jsdom.
This was the 1A + 2C option from the /plan-eng-review on this task: refactor to `useReducer` first, then unit-test the reducer, then add a thin integration layer. Net result: higher coverage, faster tests, durable under future phase additions.
Why a refactor before tests?
The component originally used `useState` with ~7 scattered `setPhase` call sites across a `useEffect` and 4 async handlers. Testing that shape would have forced every transition through a full component render + DOM assertion, which couples tests to markup rather than logic. Extracting the reducer turned the transitions into a pure function — test surface dropped from "render a component and stub better-auth" to "call a function with an action and expect a state." Pure reducer tests run in sub-millisecond time and don't touch jsdom.
The component itself got simpler too: the `"Try again"` handler collapses from a duplicated derivation block into a single `dispatch({ type: "SESSION_RESOLVED", session, userCode })` — same logic path the effect uses.
What's tested
Reducer (20 tests, node env, <5ms each)
Integration (15 tests, jsdom, ~80ms each)
Explicitly not tested
Files
Test plan
🤖 Generated with Claude Code
Summary by CodeRabbit
Tests
Chores