Skip to content

Added Webview2 to Temp Location and Playwright Custom Relative path i…#4215

Merged
Maheshkale447 merged 2 commits into
Releases/Official-Releasefrom
BugFix/AddedWebView2Temp
May 15, 2025
Merged

Added Webview2 to Temp Location and Playwright Custom Relative path i…#4215
Maheshkale447 merged 2 commits into
Releases/Official-Releasefrom
BugFix/AddedWebView2Temp

Conversation

@prashelke

@prashelke prashelke commented May 15, 2025

Copy link
Copy Markdown
Contributor

…ssue Fixed

Thank you for your contribution.
Before submitting this PR, please make sure:

  • PR description and commit message should describe the changes done in this PR
  • Verify the PR is pointing to correct branch i.e. Release or Beta branch if the code fix is for specific release , else point it to master
  • Latest Code from master or specific release branch is merged to your branch
  • No unwanted\commented\junk code is included
  • No new warning upon build solution
  • Code Summary\Comments are added to my code which explains what my code is doing
  • Existing unit test cases are passed
  • New Unit tests are added for your development
  • Sanity Tests are successfully executed for New and Existing Functionality
  • Verify that changes are compatible with all relevant browsers and platforms.
  • After creating pull request there should not be any conflicts
  • Resolve all Codacy comments
  • Builds and checks are passed before PR is sent for review
  • Resolve code review comments
  • Update the Help Library document to match any feature changes

Summary by CodeRabbit

  • New Features
    • Integrated a web content display capability using Microsoft WebView2 in the AI-Generated Preview Wizard page.
  • Bug Fixes
    • Improved accuracy in extracting values when generating XPath locators from user templates.

@coderabbitai

coderabbitai Bot commented May 15, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce Microsoft WebView2 integration into the AI-generated preview wizard page by adding initialization logic and error handling for the control. A new property for storing a temporary user data folder path is added to the base wizard class. Additionally, type corrections are made in a method handling regex matches for XPath locator generation.

Changes

File(s) Change Summary
.../POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs Integrated Microsoft WebView2 control; added async initialization method with error handling; invoked during init.
.../POMWizardLib/LearnWizard/BasePOMWizard.cs Added public property userTempDataFolderPath for user-specific temp data folder.
.../Drivers/CoreDrivers/Web/POM/POMLearner.cs Changed regex match handling from var/string? to explicit MatchCollection/Match for correct extraction.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Wizard
    participant AIGeneratedPreviewWizardPage
    participant WebView2

    User->>Wizard: Start wizard
    Wizard->>AIGeneratedPreviewWizardPage: Trigger Init event
    AIGeneratedPreviewWizardPage->>AIGeneratedPreviewWizardPage: InitializeWebView()
    AIGeneratedPreviewWizardPage->>WebView2: Create environment with user temp folder
    WebView2-->>AIGeneratedPreviewWizardPage: Environment initialized
    AIGeneratedPreviewWizardPage-->>Wizard: Initialization complete
Loading

Suggested reviewers

  • Maheshkale447

Poem

🐇
A web view now shines in the wizard’s bright hall,
With folders for temp files, neat and small.
Regex matches fixed, no more confusion—
The code hops ahead, with less illusion!
WebView2’s ready, the preview’s in sight,
This bunny’s quite pleased—code changes feel right!
🌱

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ 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 or @coderabbitai title 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.

@prashelke
prashelke requested a review from Maheshkale447 May 15, 2025 09:22

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs (1)

147-150: 💡 Verification agent

🧩 Analysis chain

Verify WebView2 initialization completion

The code sets the WebView source right after initialization, but there's no verification that the initialization has actually completed. Since InitializeWebView() is async, it might not have finished when this line executes.

Consider adding a way to ensure the WebView2 control is fully initialized before trying to navigate to content:


🏁 Script executed:

#!/bin/bash
# Look for any checks for WebView2 initialization status before navigation
rg -A 3 "MyWebView.Source" --glob "*.cs" 

# Check for any await patterns with WebView2 initialization across the codebase
rg -A 5 "EnsureCoreWebView2Async" --glob "*.cs"

Length of output: 1663


🏁 Script executed:

#!/bin/bash
sed -n '1,300p' Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs

Length of output: 11414


Ensure WebView2 is fully initialized before setting Source

The current async void InitializeWebView() is fire-and-forget, so GenerateHtmlAsync may call MyWebView.Source = … before EnsureCoreWebView2Async has completed. This can lead to intermittent navigation failures.

Suggested fixes:

  • Change initialization to return a Task and await it:
    • In AIGeneratedPreviewWizardPage.xaml.cs, rename and update:
      - public async void InitializeWebView()
      + public async Task InitializeWebViewAsync()
    • In the WizardEvent(EventType.Init) handler:
      case EventType.Init:
          mWizard = (AddPOMFromScreenshotWizard)WizardEventArgs.Wizard;
  •   InitializeWebView();
    
  •   await InitializeWebViewAsync();
      ApiSettings = LoadApiSettings();
      …
    
  • Or guard the navigation in GenerateHtmlAsync by awaiting initialization if needed:
    // before navigating:
    if (MyWebView.CoreWebView2 == null)
        await MyWebView.EnsureCoreWebView2Async();
    MyWebView.Source = new Uri(mWizard.HtmlFilePath);

Both approaches ensure the WebView2 control is ready before attempting to load the HTML.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5f2c4b8 and 2ca2e1c.

📒 Files selected for processing (3)
  • Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs (2 hunks)
  • Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/BasePOMWizard.cs (1 hunks)
  • Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/POM/POMLearner.cs (1 hunks)
🔇 Additional comments (4)
Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/POM/POMLearner.cs (1)

690-699: Good type correction for regex matches

The changes correctly type the regex match collection and iteration, ensuring proper handling of match objects.

Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs (3)

25-26: Appropriate imports for WebView2 integration

The added imports for WebView2 components are necessary for the new functionality.


54-72: WebView2 initialization with error handling

Good implementation of the WebView2 initialization with proper error handling. This addresses the PR goal of adding WebView2 to a temporary location.

Some considerations:

  1. The temp folder path could be customized or configurable for different environments
  2. You might want to add cleanup logic somewhere (perhaps in a Dispose method) to remove temporary files when no longer needed

81-81: Good integration point for WebView2 initialization

Calling InitializeWebView() during the Init event ensures the WebView2 environment is prepared before it's needed.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

♻️ Duplicate comments (1)
Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs (1)

54-72: 🧹 Nitpick (assertive)

WebView2 initialization logic looks good, but the comment needs correction

The implementation for WebView2 initialization with a temporary user data folder is well structured with proper error handling. However, there's a comment inconsistency.

-                // Define the path to the local application data folder
+                // Define the path to the system temp folder
                 mWizard.userTempDataFolderPath = Path.Combine(Path.GetTempPath(), "GingerWebView2");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2ca2e1c and 69d5b2a.

📒 Files selected for processing (1)
  • Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs (2 hunks)
🔇 Additional comments (1)
Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs (1)

25-26: Appropriate WebView2 dependencies added

Good addition of the necessary WebView2 namespaces for integrating the Edge-based web view control.

{
case EventType.Init:
mWizard = (AddPOMFromScreenshotWizard)WizardEventArgs.Wizard;
InitializeWebView();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Properly handle WebView2 initialization

Calling the async method without awaiting it may lead to race conditions. Consider either awaiting the result or handling the initialization completion differently.

- InitializeWebView();
+ // Option 1: For simplest implementation
+ await InitializeWebView();
+ 
+ // Option 2: For non-async context
+ _ = InitializeWebView().ContinueWith(t => 
+ {
+     if (t.IsFaulted)
+     {
+         Application.Current.Dispatcher.Invoke(() => 
+             Reporter.ToUser(eUserMsgKey.StaticErrorMessage, "Failed to initialize web preview"));
+     }
+ });

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In
Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs
at line 81, the async method InitializeWebView is called without awaiting it,
which can cause race conditions. Modify the code to await the InitializeWebView
call properly or implement a continuation to handle completion, ensuring the
WebView2 initialization finishes before proceeding.

Comment on lines +54 to +72
public async void InitializeWebView()
{
try
{
// Define the path to the local application data folder
mWizard.userTempDataFolderPath = Path.Combine(Path.GetTempPath(), "GingerWebView2");

// Create the directory if it doesn't exist
Directory.CreateDirectory(mWizard.userTempDataFolderPath);

// Initialize WebView2 with the custom user data folder
var environment = await CoreWebView2Environment.CreateAsync(null, mWizard.userTempDataFolderPath);
await MyWebView.EnsureCoreWebView2Async(environment);
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Failed to load preview",ex);
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider using async Task instead of async void

The async void pattern should generally be reserved for event handlers. For better error propagation and testability, consider changing to async Task:

- public async void InitializeWebView()
+ public async Task InitializeWebView()

Then update the caller to await this task or handle it properly.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public async void InitializeWebView()
{
try
{
// Define the path to the local application data folder
mWizard.userTempDataFolderPath = Path.Combine(Path.GetTempPath(), "GingerWebView2");
// Create the directory if it doesn't exist
Directory.CreateDirectory(mWizard.userTempDataFolderPath);
// Initialize WebView2 with the custom user data folder
var environment = await CoreWebView2Environment.CreateAsync(null, mWizard.userTempDataFolderPath);
await MyWebView.EnsureCoreWebView2Async(environment);
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Failed to load preview",ex);
}
}
public async Task InitializeWebView()
{
try
{
// Define the path to the local application data folder
mWizard.userTempDataFolderPath = Path.Combine(Path.GetTempPath(), "GingerWebView2");
// Create the directory if it doesn't exist
Directory.CreateDirectory(mWizard.userTempDataFolderPath);
// Initialize WebView2 with the custom user data folder
var environment = await CoreWebView2Environment.CreateAsync(null, mWizard.userTempDataFolderPath);
await MyWebView.EnsureCoreWebView2Async(environment);
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Failed to load preview", ex);
}
}
🤖 Prompt for AI Agents
In
Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs
between lines 54 and 72, the method InitializeWebView is declared as async void,
which should be avoided except for event handlers. Change the method signature
to async Task to allow proper error propagation and awaiting. Then update all
callers of InitializeWebView to await the returned Task or handle it
appropriately to ensure exceptions are caught and the asynchronous operation
completes correctly.

🧹 Nitpick (assertive)

Add cleanup mechanism for temporary WebView2 data folder

The code creates a temporary folder for WebView2 but doesn't include logic to clean it up when no longer needed. Consider adding a cleanup method to remove these temporary files.

// Add a new method to clean up temporary WebView2 data
+ public void CleanupWebViewData()
+ {
+     try
+     {
+         if (!string.IsNullOrEmpty(mWizard.userTempDataFolderPath) && Directory.Exists(mWizard.userTempDataFolderPath))
+         {
+             Directory.Delete(mWizard.userTempDataFolderPath, true);
+         }
+     }
+     catch (Exception ex)
+     {
+         Reporter.ToLog(eLogLevel.ERROR, "Failed to cleanup WebView2 data", ex);
+     }
+ }

And call this method during wizard cleanup or application exit.

🤖 Prompt for AI Agents
In
Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs
around lines 54 to 72, the InitializeWebView method creates a temporary folder
for WebView2 user data but lacks a cleanup mechanism. Add a new method to delete
the mWizard.userTempDataFolderPath directory and its contents safely, and ensure
this cleanup method is called during the wizard's disposal or when the
application exits to prevent leftover temporary files.

🧹 Nitpick (assertive)

Consider adding WebView2 runtime availability check

The code assumes WebView2 runtime is available on the user's system. Consider adding a check to verify WebView2 availability and provide guidance if it's not installed.

public async void InitializeWebView()
{
    try
    {
+        // Check if WebView2 is available
+        try
+        {
+            var version = CoreWebView2Environment.GetAvailableCoreWebView2Version();
+            if (string.IsNullOrEmpty(version))
+            {
+                Reporter.ToUser(eUserMsgKey.StaticWarningMessage, "WebView2 Runtime not found. Some features may not work properly. Please install WebView2 Runtime.");
+                return;
+            }
+        }
+        catch
+        {
+            Reporter.ToUser(eUserMsgKey.StaticWarningMessage, "WebView2 Runtime not found. Some features may not work properly. Please install WebView2 Runtime.");
+            return;
+        }
+
        // Define the path to the local application data folder
        mWizard.userTempDataFolderPath = Path.Combine(Path.GetTempPath(), "GingerWebView2");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public async void InitializeWebView()
{
try
{
// Define the path to the local application data folder
mWizard.userTempDataFolderPath = Path.Combine(Path.GetTempPath(), "GingerWebView2");
// Create the directory if it doesn't exist
Directory.CreateDirectory(mWizard.userTempDataFolderPath);
// Initialize WebView2 with the custom user data folder
var environment = await CoreWebView2Environment.CreateAsync(null, mWizard.userTempDataFolderPath);
await MyWebView.EnsureCoreWebView2Async(environment);
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Failed to load preview",ex);
}
}
public async void InitializeWebView()
{
try
{
// Check if WebView2 runtime is available
try
{
var version = CoreWebView2Environment.GetAvailableCoreWebView2Version();
if (string.IsNullOrEmpty(version))
{
Reporter.ToUser(eUserMsgKey.StaticWarningMessage,
"WebView2 Runtime not found. Some features may not work properly. Please install WebView2 Runtime.");
return;
}
}
catch
{
Reporter.ToUser(eUserMsgKey.StaticWarningMessage,
"WebView2 Runtime not found. Some features may not work properly. Please install WebView2 Runtime.");
return;
}
// Define the path to the local application data folder
mWizard.userTempDataFolderPath = Path.Combine(Path.GetTempPath(), "GingerWebView2");
// Create the directory if it doesn't exist
Directory.CreateDirectory(mWizard.userTempDataFolderPath);
// Initialize WebView2 with the custom user data folder
var environment = await CoreWebView2Environment.CreateAsync(null, mWizard.userTempDataFolderPath);
await MyWebView.EnsureCoreWebView2Async(environment);
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Failed to load preview", ex);
}
}
🤖 Prompt for AI Agents
In
Ginger/Ginger/ApplicationModelsLib/POMModels/POMWizardLib/LearnWizard/AIGeneratedPreviewWizardPage.xaml.cs
around lines 54 to 72, the InitializeWebView method assumes the WebView2 runtime
is installed. Add a check before initializing WebView2 to verify if the runtime
is available on the user's system. If not available, provide a user-friendly
message or guidance on how to install the WebView2 runtime to prevent runtime
errors and improve user experience.

@Maheshkale447
Maheshkale447 merged commit 7d54139 into Releases/Official-Release May 15, 2025
@Maheshkale447
Maheshkale447 deleted the BugFix/AddedWebView2Temp branch May 15, 2025 12:39
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.

2 participants