Skip to content

Conversation

@elibosley
Copy link
Member

@elibosley elibosley commented Jan 27, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added PM2 update process before starting the Unraid API
  • Styling Updates

    • Updated border color and styling across multiple components
    • Modified theme color configurations for borders and dark themes
  • Logging Improvements

    • Enhanced SSO removal logging visibility
    • Added more descriptive restart messages for SSO user addition
  • Chores

    • Minor refactoring of logging and error handling in various components

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 27, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request encompasses a series of modifications across multiple files in the Unraid project, focusing on logging, SSO management, UI styling, and theme configuration. The changes include updates to logging imports, SSO removal logic, PM2 update process, and UI component styling. The modifications introduce subtle refinements to error handling, logging messages, and visual presentation, with an emphasis on border styling and theme color adjustments.

Changes

File Change Summary
api/src/core/sso/sso-remove.ts Updated logging import from cliLogger to logger
api/src/index.ts Removed SSO removal log message
api/src/unraid-api/cli/sso/add-sso-user.command.ts Added 5-second delay before Unraid API restart, updated log message
api/src/unraid-api/cli/start.command.ts Added PM2 update process with error handling
unraid-ui/src/components/common/sheet/sheet.variants.ts Added border-border class to sheetVariants
unraid-ui/src/theme/preset.ts Added borderColor property with default value
web/assets/main.css Removed universal selector border styling
web/components/Notifications/List.vue Removed divide-gray-200 class
web/components/shadcn/sheet/index.ts Added border-border class to sheet variants
web/store/theme.ts Updated border color and dark themes

Possibly related PRs

Suggested reviewers

  • zackspear
  • mdatelle
  • pujitm

Poem

🐰 A Rabbit's Ode to Code Refinement 🔧

Borders crisp, logs now bright,
SSO dancing in the light,
PM2 updates with gentle grace,
Styling tweaks at steady pace,
Code evolves, a rabbit's delight! 🚀


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between f514adb and 35d5740.

📒 Files selected for processing (1)
  • api/src/unraid-api/cli/start.command.ts (1 hunks)

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

@elibosley elibosley requested a review from pujitm January 27, 2025 21:20
Copy link
Contributor

@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: 2

🧹 Nitpick comments (6)
api/src/unraid-api/cli/sso/add-sso-user.command.ts (3)

43-44: LGTM! Good UX improvement.

Adding a delay before restart gives users time to read the message and prepare for the API restart. The implementation uses a standard Promise-based setTimeout pattern.

However, consider extracting the delay duration to a constant for better maintainability:

+const RESTART_DELAY_MS = 5000;
+
 @Injectable()
 @SubCommand({
     name: 'add-user',
     aliases: ['add', 'a'],
     description: 'Add a user for SSO',
 })
 export class AddSSOUserCommand extends CommandRunner {
     // ...
     async run(_input: string[], options: AddSSOUserCommandOptions): Promise<void> {
         try {
             // ...
             if (shouldRestart) {
-                this.logger.info('Restarting the Unraid API in 5 seconds to enable the SSO button');
-                await new Promise(resolve => setTimeout(resolve, 5000));
+                this.logger.info(`Restarting the Unraid API in ${RESTART_DELAY_MS/1000} seconds to enable the SSO button`);
+                await new Promise(resolve => setTimeout(resolve, RESTART_DELAY_MS));
                 await this.restartCommand.run([]);
             }

Line range hint 47-53: Enhance error handling with more context.

The current error handling could be improved to provide more context for debugging:

         } catch (e: unknown) {
             if (e instanceof Error) {
-                this.logger.error('Error adding user: ' + e.message);
+                this.logger.error(`Error adding user: ${e.message}`, { error: e });
             } else {
-                this.logger.error('Error adding user');
+                this.logger.error('Error adding user: Unknown error type', { error: e });
             }
         }

Line range hint 82-82: Fix typo in error message.

-            throw new Error('Please answer the diclaimer with (y/n)\n');
+            throw new Error('Please answer the disclaimer with (y/n)\n');
api/src/unraid-api/cli/start.command.ts (1)

20-30: Consider adding timeout handling and retries.

The PM2 update process could potentially hang or fail temporarily due to network issues.

Consider implementing a retry mechanism with timeouts:

private async retryWithTimeout<T>(
    operation: () => Promise<T>,
    retries = 3,
    timeout = 30000
): Promise<T> {
    for (let attempt = 1; attempt <= retries; attempt++) {
        try {
            return await Promise.race([
                operation(),
                new Promise((_, reject) =>
                    setTimeout(() => reject(new Error('Operation timed out')), timeout)
                )
            ]);
        } catch (error) {
            if (attempt === retries) throw error;
            this.logger.warn(`Attempt ${attempt} failed, retrying...`);
            await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
        }
    }
    throw new Error('Should not reach here');
}

Then use it in your update logic:

await this.retryWithTimeout(
    () => execa(PM2_PATH, ['update']),
    3,  // 3 retries
    30000  // 30 second timeout
);
unraid-ui/src/components/common/sheet/sheet.variants.ts (1)

4-4: LGTM! Consider improving readability.

The addition of border-border class is consistent with the theme configuration. However, the long string of utility classes could be split for better readability.

Consider splitting the classes for better maintainability:

-  "fixed z-50 bg-background gap-4 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500 border-border",
+  [
+    "fixed z-50 bg-background gap-4 shadow-lg",
+    "transition ease-in-out",
+    "data-[state=open]:animate-in data-[state=closed]:animate-out",
+    "data-[state=closed]:duration-300 data-[state=open]:duration-500",
+    "border-border"
+  ].join(" "),
unraid-ui/src/theme/preset.ts (1)

17-19: LGTM! Consider documenting the border color system.

The addition of borderColor configuration with HSL variables is consistent with the theme system.

Consider adding a comment to document the border color usage:

 borderColor: {
+  // Uses HSL variables for consistent theming across light/dark modes
   DEFAULT: "hsl(var(--border))",
 },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 05c8c9b and f514adb.

📒 Files selected for processing (10)
  • api/src/core/sso/sso-remove.ts (2 hunks)
  • api/src/index.ts (0 hunks)
  • api/src/unraid-api/cli/sso/add-sso-user.command.ts (1 hunks)
  • api/src/unraid-api/cli/start.command.ts (1 hunks)
  • unraid-ui/src/components/common/sheet/sheet.variants.ts (1 hunks)
  • unraid-ui/src/theme/preset.ts (1 hunks)
  • web/assets/main.css (0 hunks)
  • web/components/Notifications/List.vue (1 hunks)
  • web/components/shadcn/sheet/index.ts (1 hunks)
  • web/store/theme.ts (2 hunks)
💤 Files with no reviewable changes (2)
  • web/assets/main.css
  • api/src/index.ts
✅ Files skipped from review due to trivial changes (3)
  • api/src/core/sso/sso-remove.ts
  • web/components/Notifications/List.vue
  • web/components/shadcn/sheet/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build Web App
  • GitHub Check: Build and Test API
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (3)
web/store/theme.ts (3)

35-35: LGTM! Border color adjustment improves visibility.

The increase in border lightness from 14.9% to 20% in dark mode enhances contrast while maintaining the dark theme aesthetic.


86-90: LGTM! Type safety in theme check.

The computed property correctly uses type assertion to ensure type safety when checking theme names against DARK_THEMES array.


77-78: Verify the impact of theme change on existing UPC components.

The replacement of 'azure' with 'gray' in DARK_THEMES could affect UPC text color in existing implementations.

Run this script to check for potential impacts:

Comment on lines 22 to 29
const { stderr: updateErr, stdout: updateOut } = await execa(`${PM2_PATH} update`);
if (updateOut) {
this.logger.log(updateOut);
}
if (updateErr) {
this.logger.error('PM2 Update Error: ' + updateErr);
process.exit(1);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling for PM2 update.

The current implementation has several potential issues:

  1. No try-catch around execa which could throw if PM2 is not found
  2. PM2 might write non-fatal messages to stderr
  3. Immediate process.exit() could leave resources unclosed

Consider this improved implementation:

-        const { stderr: updateErr, stdout: updateOut } = await execa(`${PM2_PATH} update`);
-        if (updateOut) {
-            this.logger.log(updateOut);
-        }
-        if (updateErr) {
-            this.logger.error('PM2 Update Error: ' + updateErr);
-            process.exit(1);
-        }
+        try {
+            const { stderr: updateErr, stdout: updateOut } = await execa(PM2_PATH, ['update'], {
+                timeout: 30000, // 30 second timeout
+            });
+            
+            if (updateOut) {
+                this.logger.log(updateOut);
+            }
+            
+            // Only treat stderr as error if it contains specific error patterns
+            if (updateErr && /error|fail|exception/i.test(updateErr)) {
+                this.logger.error('PM2 Update Error: ' + updateErr);
+                await this.cleanup();
+                process.exit(1);
+            } else if (updateErr) {
+                // Log non-fatal stderr messages as warnings
+                this.logger.warn('PM2 Update Warning: ' + updateErr);
+            }
+        } catch (error) {
+            this.logger.error('Failed to execute PM2 update:', error);
+            await this.cleanup();
+            process.exit(1);
+        }

You'll need to implement the cleanup method:

private async cleanup(): Promise<void> {
    // Add cleanup logic here (close connections, etc.)
    this.logger.info('Cleaning up before exit...');
}

@github-actions
Copy link
Contributor

This plugin has been deployed to Cloudflare R2 and is available for testing.
Download it at this URL: https://preview.dl.unraid.net/unraid-api/pr/1077/dynamix.unraid.net.staging.plg

pujitm
pujitm previously approved these changes Jan 27, 2025
Comment on lines +43 to +44
this.logger.info('Restarting the Unraid API in 5 seconds to enable the SSO button');
await new Promise(resolve => setTimeout(resolve, 5000));
Copy link
Member

Choose a reason for hiding this comment

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

what's the reason behind this wait?

Copy link
Member Author

Choose a reason for hiding this comment

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

The API wouldn't sync the config internally, and then wrote over the change.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@elibosley elibosley merged commit bc229e7 into main Jan 28, 2025
4 of 6 checks passed
@elibosley elibosley deleted the feat/ui-fixes branch January 28, 2025 14:12
@github-actions
Copy link
Contributor

This plugin has been deployed to Cloudflare R2 and is available for testing.
Download it at this URL: https://preview.dl.unraid.net/unraid-api/pr/1077/dynamix.unraid.net.staging.plg

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.

3 participants