Skip to content

Fix/race condition error creating device#407

Open
egalvis27 wants to merge 3 commits into
mainfrom
fix/race-condition-error-creating-device
Open

Fix/race condition error creating device#407
egalvis27 wants to merge 3 commits into
mainfrom
fix/race-condition-error-creating-device

Conversation

@egalvis27

@egalvis27 egalvis27 commented Jul 9, 2026

Copy link
Copy Markdown

What is Changed / Added


  • Fixed a race condition in backup device initialization for users with no previously registered device.
  • Registered the device-created listener before triggering the initial getOrCreateDevice flow.
  • Added a state guard so a late error result cannot overwrite SUCCESS after a device is already set.
  • Added regression tests in DeviceContext to cover:
    • race case (device-created arrives before an error result),
    • fallback to ERROR when no device is created,
    • listener unsubscribe on unmount.

Why

  • This issue mainly affects new users (no existing device yet).
  • In that path, device creation can succeed, but a delayed error from the initial request may still arrive afterward.
  • Before this fix, that delayed error could force UI state to ERROR, showing "There was an error loading your backups" and blocking the backups view.
  • This change preserves the valid SUCCESS state once a device is available, so backups remain accessible.

Summary by CodeRabbit

  • Bug Fixes
    • Improved device refresh behavior to correctly handle out-of-order async device events.
    • Prevented device errors from overwriting an already successful device state.
    • Ensured device-created event listeners are registered/unregistered reliably.
  • Tests
    • Added a DeviceContext test suite covering device state transitions, error handling, and listener cleanup.
    • Updated test mocks to better initialize the test environment.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7c532f99-cafc-4934-8265-6a6cd5813736

📥 Commits

Reviewing files that changed from the base of the PR and between 6cfc49a and 1934040.

📒 Files selected for processing (1)
  • src/apps/renderer/context/DeviceContext.test.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/apps/renderer/context/DeviceContext.test.tsx

📝 Walkthrough

Walkthrough

DeviceProvider’s device refresh flow now uses async/await with guarded error handling and listener registration before refresh. A new test suite covers success, failure, and cleanup behavior, and the Vitest @internxt/inxt-js mock adds an Environment export.

Changes

DeviceContext Refactor and Testing

Layer / File(s) Summary
Async refresh flow and error-state guard
src/apps/renderer/context/DeviceContext.tsx
setDeviceErrorState guards ERROR transitions against overwriting SUCCESS; refreshDevice becomes async/await, sets LOADING, awaits getOrCreateDevice(), and calls setCurrentDevice on success or setDeviceErrorState on failure; useEffect now registers the onDeviceCreated listener before invoking refreshDevice().
Test suite and mock support
src/apps/renderer/context/DeviceContext.test.tsx, vitest.setup.main.ts
New tests cover device-created-before-error ordering (SUCCESS), error-only failure (ERROR), and unmount cleanup (unsubscribe called), supported by an added Environment mock function in the @internxt/inxt-js test mock.

Estimated code review effort: 2 (Simple) | ~12 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and describes the main change: fixing a race condition during device creation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/race-condition-error-creating-device

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/apps/renderer/context/DeviceContext.test.tsx (1)

71-81: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a test for the normal success path.

The suite covers the race condition, error-only, and unmount cleanup, but doesn't explicitly assert SUCCESS state when getOrCreateDevice returns data without a device-created event. The unmount test uses this path but only checks cleanup, not state. Adding a focused test would close the coverage gap.

🧪 Suggested test
   it('should set success state when getOrCreateDevice returns data', async () => {
     getOrCreateDeviceMock.mockResolvedValue({ data: device });
 
     const { result } = renderDeviceContextHook();
 
     await vi.waitFor(() => {
       expect(result.current.deviceState.status).toBe('SUCCESS');
     });
 
     if (result.current.deviceState.status === 'SUCCESS') {
       expect(result.current.deviceState.device).toStrictEqual(device);
     }
   });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/apps/renderer/context/DeviceContext.test.tsx` around lines 71 - 81, Add a
focused success-path test in DeviceContext.test.tsx for
DeviceContext/useDeviceContext that mocks getOrCreateDevice to return device
data and verifies the state becomes SUCCESS when no device-created event
arrives. Reuse the existing renderDeviceContextHook, getOrCreateDeviceMock, and
subscription mocks, but assert the success state explicitly instead of only
checking unmount cleanup.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/apps/renderer/context/DeviceContext.test.tsx`:
- Around line 1-82: Prettier formatting is failing in DeviceContext.test.tsx, so
update the test file to match the project’s formatting rules and unblock CI.
Reformat the existing DeviceContext test suite with the standard formatter so
imports, spacing, and line breaks align with the rest of the file, keeping the
current test logic and symbols like renderDeviceContextHook,
getOrCreateDeviceMock, and onDeviceCreatedMock unchanged.

---

Nitpick comments:
In `@src/apps/renderer/context/DeviceContext.test.tsx`:
- Around line 71-81: Add a focused success-path test in DeviceContext.test.tsx
for DeviceContext/useDeviceContext that mocks getOrCreateDevice to return device
data and verifies the state becomes SUCCESS when no device-created event
arrives. Reuse the existing renderDeviceContextHook, getOrCreateDeviceMock, and
subscription mocks, but assert the success state explicitly instead of only
checking unmount cleanup.
🪄 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: 0c014535-3cd5-4963-856c-97c9a1bc3ec0

📥 Commits

Reviewing files that changed from the base of the PR and between e6b1171 and 6cfc49a.

📒 Files selected for processing (3)
  • src/apps/renderer/context/DeviceContext.test.tsx
  • src/apps/renderer/context/DeviceContext.tsx
  • vitest.setup.main.ts

Comment thread src/apps/renderer/context/DeviceContext.test.tsx Outdated
@sonarqubecloud

sonarqubecloud Bot commented Jul 9, 2026

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant