Skip to content

Conversation

@mihirpenugonda
Copy link

@mihirpenugonda mihirpenugonda commented Jun 8, 2025

Summary
A complete API key validation system that tests keys against real provider APIs before saving them.

Summary by CodeRabbit

  • New Features

    • Added live API key validation for OpenAI, Google, and OpenRouter directly within the form, providing instant feedback on key validity before saving.
    • Visual indicators now display validation status (spinner, checkmark, or cross) and error messages for each API key field.
    • Prevents saving invalid API keys and notifies users with clear success or error messages.
  • Bug Fixes

    • Ensures previous validation results are cleared when API key inputs are changed for accurate feedback.

@vercel
Copy link

vercel bot commented Jun 8, 2025

@mihirpenugonda is attempting to deploy a commit to the Harsh's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link

coderabbitai bot commented Jun 8, 2025

Walkthrough

The changes introduce asynchronous API key validation for multiple providers within the APIKeyForm UI. A new service module handles provider-specific validation logic. The store and form components are updated to support real-time validation feedback, blocking submission if any key is invalid and displaying appropriate UI indicators and error messages.

Changes

File(s) Change Summary
frontend/components/APIKeyForm.tsx Enhanced form to perform async API key validation before saving; added UI feedback for validation.
frontend/stores/APIKeyStore.ts Added methods to validate single/all API keys asynchronously using the new validation service.
lib/apiValidationService.ts New module implementing provider-specific API key validation logic and result interface.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant APIKeyForm
    participant APIKeyStore
    participant apiValidationService

    User->>APIKeyForm: Submit form
    APIKeyForm->>APIKeyStore: validateAllKeysAPI()
    APIKeyStore->>apiValidationService: validateAPIKey(provider, key) (for each provider)
    apiValidationService-->>APIKeyStore: APIValidationResult(s)
    APIKeyStore-->>APIKeyForm: Validation results
    alt Any key invalid
        APIKeyForm-->>User: Show error toast, block save
    else All keys valid
        APIKeyForm->>APIKeyStore: Save keys
        APIKeyForm-->>User: Show success toast
    end
Loading

Poem

🐇
Keys must be checked, the rabbits decree,
Each hop to a service, as swift as can be.
If green lights appear, the form hops ahead,
But a red, and it stops—no saving instead!
Now validation’s live, with icons to show,
This bunny’s delighted—let the good data flow!

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

frontend/components/APIKeyForm.tsx

Oops! Something went wrong! :(

ESLint: 9.28.0

ESLint couldn't find the plugin "eslint-plugin-react-hooks".

(The package "eslint-plugin-react-hooks" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react-hooks@latest --save-dev

The plugin "eslint-plugin-react-hooks" was referenced from the config file in " » eslint-config-next/core-web-vitals » /node_modules/.pnpm/eslint-config-next@15.3.2_eslint@9.28.0_jiti@2.4.2__typescript@5.8.3/node_modules/eslint-config-next/index.js".

If you still can't figure out the problem, please see https://eslint.org/docs/latest/use/troubleshooting.

frontend/stores/APIKeyStore.ts

Oops! Something went wrong! :(

ESLint: 9.28.0

ESLint couldn't find the plugin "eslint-plugin-react-hooks".

(The package "eslint-plugin-react-hooks" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react-hooks@latest --save-dev

The plugin "eslint-plugin-react-hooks" was referenced from the config file in " » eslint-config-next/core-web-vitals » /node_modules/.pnpm/eslint-config-next@15.3.2_eslint@9.28.0_jiti@2.4.2__typescript@5.8.3/node_modules/eslint-config-next/index.js".

If you still can't figure out the problem, please see https://eslint.org/docs/latest/use/troubleshooting.

lib/apiValidationService.ts

Oops! Something went wrong! :(

ESLint: 9.28.0

ESLint couldn't find the plugin "eslint-plugin-react-hooks".

(The package "eslint-plugin-react-hooks" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react-hooks@latest --save-dev

The plugin "eslint-plugin-react-hooks" was referenced from the config file in " » eslint-config-next/core-web-vitals » /node_modules/.pnpm/eslint-config-next@15.3.2_eslint@9.28.0_jiti@2.4.2__typescript@5.8.3/node_modules/eslint-config-next/index.js".

If you still can't figure out the problem, please see https://eslint.org/docs/latest/use/troubleshooting.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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

♻️ Duplicate comments (1)
lib/apiValidationService.ts (1)

46-65: 🛠️ Refactor suggestion

Apply same timeout and error handling improvements as OpenAI validator.

This function has the same issues as validateOpenAI - needs timeout handling and better error messages.

🧹 Nitpick comments (1)
frontend/components/APIKeyForm.tsx (1)

73-83: Good UX: Clearing stale validation results on input change.

The effect correctly clears validation results when inputs change. Consider using a more functional approach:

-  useEffect(() => {
-    Object.keys(watchedValues).forEach(provider => {
-      if (apiValidationResults[provider]) {
-        setApiValidationResults(prev => {
-          const newResults = { ...prev };
-          delete newResults[provider];
-          return newResults;
-        });
-      }
-    });
-  }, [watchedValues, apiValidationResults]);
+  useEffect(() => {
+    const providersWithResults = Object.keys(watchedValues).filter(
+      provider => apiValidationResults[provider]
+    );
+    
+    if (providersWithResults.length > 0) {
+      setApiValidationResults(prev => 
+        Object.fromEntries(
+          Object.entries(prev).filter(([key]) => !providersWithResults.includes(key))
+        )
+      );
+    }
+  }, [watchedValues]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ed9c4c3 and 259fd16.

📒 Files selected for processing (3)
  • frontend/components/APIKeyForm.tsx (10 hunks)
  • frontend/stores/APIKeyStore.ts (3 hunks)
  • lib/apiValidationService.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
frontend/stores/APIKeyStore.ts (1)
lib/apiValidationService.ts (1)
  • APIValidationResult (3-6)
lib/apiValidationService.ts (1)
frontend/stores/APIKeyStore.ts (1)
  • Provider (6-6)
frontend/components/APIKeyForm.tsx (3)
lib/apiValidationService.ts (1)
  • APIValidationResult (3-6)
frontend/stores/APIKeyStore.ts (1)
  • Provider (6-6)
frontend/components/ui/input.tsx (1)
  • Input (21-21)
🔇 Additional comments (7)
frontend/stores/APIKeyStore.ts (3)

3-3: Good aliasing of the imported validation function.

The alias validateAPIKeyService clearly distinguishes the imported function from the store methods, preventing naming conflicts.


62-68: Well-implemented single key validation with proper edge case handling.

The method correctly validates empty keys before delegating to the service, providing clear error messages.


70-85: ⚠️ Potential issue

Fix race condition in concurrent validation results collection.

The current implementation assigns results within the map callback before Promise.all completes, which could lead to partial results if interrupted. Results should be collected after all promises resolve.

Apply this diff to fix the race condition:

-      validateAllKeysAPI: async () => {
-        const keys = get().keys;
-        const results: Record<Provider, APIValidationResult> = {} as Record<Provider, APIValidationResult>;
-        
-        const validationPromises = PROVIDERS.map(async (provider) => {
-          const key = keys[provider];
-          if (key && key.trim().length > 0) {
-            results[provider] = await validateAPIKeyService(provider, key);
-          } else {
-            results[provider] = { isValid: false, error: `${provider} API key is required` };
-          }
-        });
-
-        await Promise.all(validationPromises);
-        return results;
-      },
+      validateAllKeysAPI: async () => {
+        const keys = get().keys;
+        
+        const validationPromises = PROVIDERS.map(async (provider) => {
+          const key = keys[provider];
+          if (key && key.trim().length > 0) {
+            return { provider, result: await validateAPIKeyService(provider, key) };
+          } else {
+            return { provider, result: { isValid: false, error: `${provider} API key is required` } };
+          }
+        });
+
+        const validationResults = await Promise.all(validationPromises);
+        
+        const results: Record<Provider, APIValidationResult> = {} as Record<Provider, APIValidationResult>;
+        validationResults.forEach(({ provider, result }) => {
+          results[provider] = result;
+        });
+        
+        return results;
+      },

Likely an incorrect or invalid review comment.

lib/apiValidationService.ts (1)

67-85: Well-structured validation dispatcher with proper edge case handling.

The function correctly validates empty keys and uses an exhaustive switch statement with a default case for unknown providers.

frontend/components/APIKeyForm.tsx (3)

1-1: Appropriate imports for validation functionality.

The added imports correctly bring in state management hooks and validation-related components.

Also applies to: 19-20


53-54: Efficient state management for validation tracking.

Good use of Set for O(1) lookups when checking validation status. The state structure clearly separates results from loading states.


202-247: Excellent UI feedback implementation for validation states.

The dynamic styling with border colors (red/green) and validation icons (spinner/check/cross) provides clear visual feedback. The absolute positioning of icons ensures they don't affect input layout.

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