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

feat(suite-desktop): open system settings using desktopApi #17017

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

szymonlesisz
Copy link
Contributor

@szymonlesisz szymonlesisz commented Feb 14, 2025

Description

Another cherry pick from the bluetooth branch.
Open system settings using desktopApi.

Originally i did it only for the bluetooth module but then i realized it could be also used to open other settings, like for example camera settings if it was once declined (useful especially on macos)

tested on linux ubuntu gnome, debian gnome, macos and windows, i didnt tried KDE or any other

Copy link

coderabbitai bot commented Feb 14, 2025

Walkthrough

This pull request introduces new methods to the desktop API and integrates a system settings module for managing Bluetooth settings across various operating systems. Two methods are added to the API: system/open-settings in the InvokeChannels interface, which accepts a parameter for Bluetooth settings, and openSystemSettings in the DesktopApi interface, corresponding to the IPC channel. The factory function is updated to include the openSystemSettings method, allowing invocation of the system settings functionality. Additionally, a new module for system settings is created, which determines the appropriate command to open Bluetooth settings based on the operating system—supporting Linux (with checks for desktop environments), macOS, and Windows—while handling errors for unsupported environments. This module is added to the core modules list and includes an IPC handler for the system/open-settings event.

✨ 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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: 3

🧹 Nitpick comments (1)
packages/suite-desktop-core/src/modules/system-settings.ts (1)

47-55: Enhance type safety and extensibility.

The IPC handler could benefit from better type safety and extensibility for future settings.

Consider this enhancement:

+type SupportedSettings = 'bluetooth' | 'camera' | 'privacy';
+
 export const init: ModuleInit = () => {
-    ipcMain.handle('system/open-settings', (_, settings) => {
+    ipcMain.handle('system/open-settings', (_, settings: SupportedSettings) => {
         if (settings === 'bluetooth') {
             return openBluetoothSettings();
+        } else if (settings === 'camera') {
+            // TODO: Implement camera settings
+            return { success: false, error: 'Camera settings not implemented yet' };
+        } else if (settings === 'privacy') {
+            // TODO: Implement privacy settings
+            return { success: false, error: 'Privacy settings not implemented yet' };
         }
 
         return { success: false, error: `Unknown settings: ${settings}` };
     });
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8304a7b and 1077075.

📒 Files selected for processing (4)
  • packages/suite-desktop-api/src/api.ts (2 hunks)
  • packages/suite-desktop-api/src/factory.ts (1 hunks)
  • packages/suite-desktop-core/src/modules/index.ts (2 hunks)
  • packages/suite-desktop-core/src/modules/system-settings.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: run-desktop-tests (@group=wallet, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=other, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=passphrase, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=settings, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=device-management, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=suite, trezor-user-env-unix)
  • GitHub Check: Setup and Cache Dependencies
  • GitHub Check: Analyze with CodeQL (javascript)
  • GitHub Check: build-web
🔇 Additional comments (2)
packages/suite-desktop-api/src/api.ts (1)

112-112: LGTM!

The API interface changes are well-defined and consistent with the implementation.

Also applies to: 179-179

packages/suite-desktop-core/src/modules/index.ts (1)

33-33: LGTM!

The module integration follows the established pattern and is correctly placed in the MODULES array.

Also applies to: 67-67

@szymonlesisz szymonlesisz force-pushed the feat/suite-desktop-system-settings branch from 1077075 to a65ecc9 Compare February 17, 2025 09:41
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: 1

♻️ Duplicate comments (3)
packages/suite-desktop-core/src/modules/system-settings.ts (3)

1-1: ⚠️ Potential issue

Use execFile instead of exec for better security.

Using exec can lead to command injection vulnerabilities. Consider using execFile which is safer for executing commands with arguments.

-import { exec } from 'child_process';
+import { execFile } from 'child_process';

12-21: ⚠️ Potential issue

Improve command validation and error handling.

The function needs better input validation and error handling:

  1. Command string is passed directly to exec without validation
  2. Error details might contain sensitive information
-const openSettings = (cmd: string, env?: Record<string, string>) =>
+const ALLOWED_COMMANDS = ['gnome-control-center', 'systemsettings5', 'open', 'start'] as const;
+type AllowedCommand = typeof ALLOWED_COMMANDS[number];
+
+const openSettings = (cmd: AllowedCommand, args: string[], env?: Record<string, string>) =>
     new Promise<InvokeResult>(resolve => {
-        exec(cmd, { env: { ...process.env, ...env } }, error => {
+        execFile(cmd, args, { env: { ...process.env, ...env } }, error => {
             if (error) {
-                resolve({ success: false, error: error.toString() });
+                resolve({ success: false, error: 'Failed to open system settings' });
             } else {
                 resolve({ success: true });
             }
         });
     });

23-46: 🛠️ Refactor suggestion

Improve error handling for desktop environments.

The function needs better error handling:

  1. No error for missing desktop environment variable
  2. No explicit error for unsupported desktop environments
  3. Commands should be split into command and arguments
 const openBluetoothSettings = () => {
     if (isLinux()) {
         const xdg = process.env.ORIGINAL_XDG_CURRENT_DESKTOP || process.env.XDG_CURRENT_DESKTOP;
+        if (!xdg) {
+            return { success: false, error: 'Desktop environment not detected' };
+        }
         if (xdg?.includes('GNOME')) {
-            return openSettings('gnome-control-center bluetooth', {
+            return openSettings('gnome-control-center', ['bluetooth'], {
                 XDG_CURRENT_DESKTOP: xdg,
             });
         } else if (xdg?.includes('KDE')) {
-            return openSettings('systemsettings5', {
+            return openSettings('systemsettings5', [], {
                 XDG_CURRENT_DESKTOP: xdg,
             });
+        } else {
+            return { success: false, error: `Unsupported desktop environment: ${xdg}` };
         }
     }
     if (isMacOs()) {
-        return openSettings('open "x-apple.systempreferences:com.apple.Bluetooth"');
+        return openSettings('open', ['x-apple.systempreferences:com.apple.Bluetooth']);
     }
     if (isWindows()) {
-        return openSettings('start ms-settings:bluetooth');
+        return openSettings('start', ['ms-settings:bluetooth']);
     }
     return { success: false, error: 'Unsupported os' };
 };
🧹 Nitpick comments (1)
packages/suite-desktop-core/src/modules/system-settings.ts (1)

48-56: Add type safety for settings parameter.

The settings parameter should be typed to ensure only valid settings are passed.

+type SystemSettings = 'bluetooth';
+
 export const init: ModuleInit = () => {
-    ipcMain.handle('system/open-settings', (_, settings) => {
+    ipcMain.handle('system/open-settings', (_, settings: SystemSettings) => {
         if (settings === 'bluetooth') {
             return openBluetoothSettings();
         }
 
         return { success: false, error: `Unknown settings: ${settings}` };
     });
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1077075 and a65ecc9.

📒 Files selected for processing (4)
  • packages/suite-desktop-api/src/api.ts (2 hunks)
  • packages/suite-desktop-api/src/factory.ts (1 hunks)
  • packages/suite-desktop-core/src/modules/index.ts (2 hunks)
  • packages/suite-desktop-core/src/modules/system-settings.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/suite-desktop-core/src/modules/index.ts
  • packages/suite-desktop-api/src/api.ts
  • packages/suite-desktop-api/src/factory.ts
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: run-desktop-tests (@group=wallet, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=other, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=passphrase, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=settings, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=device-management, trezor-user-env-unix)
  • GitHub Check: build-web
  • GitHub Check: Setup and Cache Dependencies
  • GitHub Check: run-desktop-tests (@group=suite, trezor-user-env-unix)
  • GitHub Check: Analyze with CodeQL (javascript)

packages/suite-desktop-core/src/modules/system-settings.ts Outdated Show resolved Hide resolved
@szymonlesisz szymonlesisz force-pushed the feat/suite-desktop-system-settings branch from a65ecc9 to 096a7ce Compare February 17, 2025 09:48
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

♻️ Duplicate comments (3)
packages/suite-desktop-core/src/modules/system-settings.ts (3)

1-1: ⚠️ Potential issue

Use execFile instead of exec for better security.

Using exec can lead to command injection vulnerabilities. Consider using execFile which is safer for executing commands with arguments.

-import { exec } from 'child_process';
+import { execFile } from 'child_process';

12-21: ⚠️ Potential issue

Enhance security and error handling in openSettings.

The function needs several improvements:

  1. Input validation for commands
  2. Proper argument separation
  3. Better error handling with specific error types
-const openSettings = (cmd: string, env?: Record<string, string>) =>
+const ALLOWED_COMMANDS = ['gnome-control-center', 'systemsettings5', 'open', 'start'] as const;
+type AllowedCommand = typeof ALLOWED_COMMANDS[number];
+
+const openSettings = (cmd: AllowedCommand, args: string[], env?: Record<string, string>) =>
     new Promise<InvokeResult>(resolve => {
-        exec(cmd, { env: { ...process.env, ...env } }, error => {
+        execFile(cmd, args, { env: { ...process.env, ...env } }, error => {
             if (error) {
-                resolve({ success: false, error: error.toString() });
+                resolve({ 
+                    success: false, 
+                    error: `Failed to open settings: ${error.message}` 
+                });
             } else {
                 resolve({ success: true });
             }
         });
     });

23-46: 🛠️ Refactor suggestion

Improve error handling and command execution in openBluetoothSettings.

The function needs several improvements:

  1. Better error handling for unsupported desktop environments
  2. Proper command and argument separation
  3. Validation of environment variables
 const openBluetoothSettings = () => {
     if (isLinux()) {
         const xdg = process.env.ORIGINAL_XDG_CURRENT_DESKTOP || process.env.XDG_CURRENT_DESKTOP;
+        if (!xdg) {
+            return { success: false, error: 'Desktop environment not detected' };
+        }
         if (xdg?.includes('GNOME')) {
-            return openSettings('gnome-control-center bluetooth', {
+            return openSettings('gnome-control-center', ['bluetooth'], {
                 XDG_CURRENT_DESKTOP: xdg,
             });
         } else if (xdg?.includes('KDE')) {
-            return openSettings('systemsettings5', {
+            return openSettings('systemsettings5', [], {
                 XDG_CURRENT_DESKTOP: xdg,
             });
+        } else {
+            return { success: false, error: `Unsupported desktop environment: ${xdg}` };
         }
     }
     if (isMacOs()) {
-        return openSettings('open "x-apple.systempreferences:com.apple.Bluetooth"');
+        return openSettings('open', ['x-apple.systempreferences:com.apple.Bluetooth']);
     }
     if (isWindows()) {
-        return openSettings('start ms-settings:bluetooth');
+        return openSettings('start', ['ms-settings:bluetooth']);
     }
     return { success: false, error: 'Unsupported os' };
 };
🧹 Nitpick comments (1)
packages/suite-desktop-core/src/modules/system-settings.ts (1)

48-56: Add type safety to settings parameter.

Consider adding a type for the settings parameter to ensure type safety at compile time.

+type SystemSettings = 'bluetooth';
+
 export const init: ModuleInit = () => {
-    ipcMain.handle('system/open-settings', (_, settings) => {
+    ipcMain.handle('system/open-settings', (_, settings: SystemSettings) => {
         if (settings === 'bluetooth') {
             return openBluetoothSettings();
         }
 
         return { success: false, error: `Unknown settings: ${settings}` };
     });
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a65ecc9 and 096a7ce.

📒 Files selected for processing (4)
  • packages/suite-desktop-api/src/api.ts (2 hunks)
  • packages/suite-desktop-api/src/factory.ts (1 hunks)
  • packages/suite-desktop-core/src/modules/index.ts (2 hunks)
  • packages/suite-desktop-core/src/modules/system-settings.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/suite-desktop-core/src/modules/index.ts
  • packages/suite-desktop-api/src/factory.ts
  • packages/suite-desktop-api/src/api.ts
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build-web
  • GitHub Check: run-desktop-tests (@group=wallet, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=other, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=passphrase, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=settings, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=device-management, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=suite, trezor-user-env-unix)
  • GitHub Check: Analyze with CodeQL (javascript)
  • GitHub Check: Setup and Cache Dependencies

@szymonlesisz
Copy link
Contributor Author

NOTE: this PR conflicts with bluetooth-ipc PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

1 participant