Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: exclude gpu devices while mining #1560

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

mmrrnn
Copy link
Collaborator

@mmrrnn mmrrnn commented Feb 24, 2025

Description

Allow user to enable/disable specific GPU devices when mining in progress. After each change mining is paused and restarted to apply changes.

What process can a PR reviewer use to test or verify this change?

  1. Start mining if auto mining disabled
  2. Go to Mining settings, "GPU Mining devices" specifically
  3. Toggle off/on gpu devices separately

image

Summary by CodeRabbit

  • New Features

    • Enhanced GPU device settings for a more intuitive and responsive experience when excluding devices.
    • Mining activity now automatically resumes if it was active prior to making exclusion adjustments.
  • Refactor

    • Simplified the underlying logic for managing GPU device exclusions, ensuring clearer toggle behavior in the settings.

@mmrrnn mmrrnn marked this pull request as ready for review February 24, 2025 15:56
Copy link

coderabbitai bot commented Feb 24, 2025

📝 Walkthrough

Walkthrough

This pull request simplifies the management of GPU mining toggle states. In the GPU device component, several mining status variables are removed and a new variable, isExcludingGpuDevices, is introduced to manage exclusions. In the mining store, the state and action for excluding GPU devices have been updated to set this flag, conditionally pause mining, and restart mining if it was previously initiated. Redundant logging related to excluded devices has also been removed.

Changes

Files Change Summaries
src/containers/floating/Settings/sections/mining/GpuDevices.tsx Removed variables (isCPUMining, isGPUMining, miningInitiated, isMiningInProgress) and simplified toggle switch logic. Updated checked property to rely on exclusion status and disabled property to consider isExcludingGpuDevices along with mining conditions.
src/store/useMiningStore.ts Added new state property isExcludingGpuDevices (initialized to false). Modified the setExcludedGpuDevice action to set this flag, check active mining conditions, disable GPU mining if all devices are excluded, and restart mining when necessary. Removed redundant logging.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant C as GpuDevices Component
    participant S as MiningStore

    U->>C: Toggle GPU device switch
    C->>S: Invoke setExcludedGpuDevice()
    S->>S: Set isExcludingGpuDevices = true
    S->>S: Check active CPU/GPU mining status
    S->>S: Exclude the selected GPU device(s)
    S->>S: If all GPUs excluded, disable GPU mining
    S->>S: If mining was initiated, restart mining
    S->>S: Set isExcludingGpuDevices = false
    S-->>C: Return updated mining state
Loading

Suggested reviewers

  • Misieq01
  • MCozhusheck

Poem

I’m a hopping rabbit in the code forest bright,
Skipping through changes with delight tonight.
Variables removed, new flags in sight,
Excluding GPUs just feels so right.
Code carrots crunch in pure delight,
Celebration in bytes, our future is light!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
src/store/useMiningStore.ts (1)

88-118: 🛠️ Refactor suggestion

Improve error handling and state management in setExcludedGpuDevice.

While the implementation correctly handles the GPU device exclusion workflow, there are a few areas that could be improved:

  1. Error handling for mining pause/restart operations
  2. Potential race conditions between state checks and actions
  3. Input validation for excludedGpuDevices array

Consider applying these improvements:

 setExcludedGpuDevice: async (excludedGpuDevices) => {
+    if (!Array.isArray(excludedGpuDevices)) {
+        throw new Error('excludedGpuDevices must be an array');
+    }
+
     set({ isExcludingGpuDevices: true });
-    const metricsState = useMiningMetricsStore.getState();
+    try {
+        const metricsState = useMiningMetricsStore.getState();

-    if (metricsState.cpu_mining_status.is_mining || metricsState.gpu_mining_status.is_mining) {
-        console.info('Pausing mining...');
-        await pauseMining();
-    }
+        if (metricsState.cpu_mining_status.is_mining || metricsState.gpu_mining_status.is_mining) {
+            console.info('Pausing mining...');
+            await pauseMining();
+        }

-    try {
         await invoke('set_excluded_gpu_devices', { excludedGpuDevices });

         const totalGpuDevices = useMiningMetricsStore.getState().gpu_devices?.length || 0;
         if (excludedGpuDevices.length === totalGpuDevices) {
             const appConfigStore = useAppConfigStore.getState();
             appConfigStore.setGpuMiningEnabled(false);
         }
         set({ excludedGpuDevices });
-    } catch (e) {
-        const appStateStore = useAppStateStore.getState();
-        console.error('Could not set excluded gpu device: ', e);
-        appStateStore.setError(e as string);
-        set({ excludedGpuDevices: undefined });
-    }

-    if (useMiningStore.getState().miningInitiated) {
-        console.info('Restarting mining...');
-        await startMining();
-    }
-    set({ isExcludingGpuDevices: false });
+        if (useMiningStore.getState().miningInitiated) {
+            console.info('Restarting mining...');
+            await startMining();
+        }
+    } catch (e) {
+        const appStateStore = useAppStateStore.getState();
+        console.error('Error in setExcludedGpuDevice: ', e);
+        appStateStore.setError(e as string);
+        set({ excludedGpuDevices: undefined });
+    } finally {
+        set({ isExcludingGpuDevices: false });
+    }
 },
🧹 Nitpick comments (2)
src/containers/floating/Settings/sections/mining/GpuDevices.tsx (2)

66-71: Enhance ToggleSwitch performance and accessibility.

While the toggle switch implementation is functionally correct, consider these improvements:

 <ToggleSwitch
     key={device.name}
     checked={!excludedDevices.includes(i)}
     disabled={isExcludingGpuDevices || !miningAllowed || !isGpuMiningEnabled}
     onChange={() => handleSetExcludedDevice(i)}
+    aria-label={`Toggle ${device.name}`}
+    title={isExcludingGpuDevices ? t('gpu-device-excluding-in-progress') : undefined}
 />

Also consider memoizing the checked state:

const isDeviceEnabled = useMemo(
  () => !excludedDevices.includes(i),
  [excludedDevices, i]
);

29-40: Consider memoizing excluded devices array operations.

The handleSetExcludedDevice callback could benefit from memoizing the array operations to prevent unnecessary re-renders.

 const handleSetExcludedDevice = useCallback(
     async (device: number) => {
+        const newExcludedDevices = excludedDevices.includes(device)
+            ? excludedDevices.filter(d => d !== device)
+            : [...excludedDevices, device];
-        if (!excludedDevices.includes(device)) {
-            excludedDevices.push(device);
-            await setExcludedDevice([...excludedDevices]);
-        } else {
-            excludedDevices.splice(excludedDevices.indexOf(device), 1);
-            await setExcludedDevice([...excludedDevices]);
-        }
+        await setExcludedDevice(newExcludedDevices);
     },
     [excludedDevices, setExcludedDevice]
 );
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 83ac3a3 and 7442c1f.

📒 Files selected for processing (2)
  • src/containers/floating/Settings/sections/mining/GpuDevices.tsx (2 hunks)
  • src/store/useMiningStore.ts (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tauri-build
🔇 Additional comments (3)
src/store/useMiningStore.ts (2)

10-21: LGTM! State interface is well-defined.

The new isExcludingGpuDevices boolean property is appropriately added to the State interface.


32-43: LGTM! Initial state is properly initialized.

The isExcludingGpuDevices property is correctly initialized to false in the initial state.

src/containers/floating/Settings/sections/mining/GpuDevices.tsx (1)

27-27: LGTM! State hook is correctly implemented.

The isExcludingGpuDevices state is properly accessed using the store hook.

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