-
Notifications
You must be signed in to change notification settings - Fork 0
feat(embedded-assistant): add a C# example using WPF #13
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
Open
Zoltan Hricz (hriczzoli)
wants to merge
4
commits into
main
Choose a base branch
from
add-c-sharp-example-to-assistant
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2800866
feat(embedded-assistant): add a C# example using WPF
hriczzoli 60d4880
fix(embedded-assistant): harden WPF WebView bootstrap and permissions
hriczzoli 4b62174
fix: correct main directory name
hriczzoli 40bf462
chore: correct dependencies
hriczzoli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| CORTI_ENVIRONMENT=eu | ||
| CORTI_TENANT_NAME=your-tenant | ||
| CORTI_CLIENT_ID=assistant | ||
| CORTI_USER_EMAIL=user@example.com | ||
| CORTI_USER_PASSWORD=replace-me |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| .env | ||
| .dotnet/ | ||
| bin/ | ||
| obj/ | ||
| artifacts/ | ||
| .vs/ | ||
| *.user | ||
| *.csproj.user | ||
| WebAssets/dist/ | ||
| WebAssets/node_modules/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| <Application x:Class="CortiAssistantApp.App" | ||
| xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" | ||
| xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | ||
| xmlns:local="clr-namespace:CortiAssistantApp" | ||
| StartupUri="MainWindow.xaml"> | ||
| <Application.Resources> | ||
|
|
||
| </Application.Resources> | ||
| </Application> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| using System.Configuration; | ||
| using System.Data; | ||
| using System.Windows; | ||
|
|
||
| namespace CortiAssistantApp | ||
| { | ||
| /// <summary> | ||
| /// Interaction logic for App.xaml | ||
| /// </summary> | ||
| public partial class App : Application | ||
| { | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| using System.Windows; | ||
|
|
||
| [assembly: ThemeInfo( | ||
| ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located | ||
| //(used if a resource is not found in the page, | ||
| // or application resource dictionaries) | ||
| ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located | ||
| //(used if a resource is not found in the page, | ||
| // app, or any theme specific resource dictionaries) | ||
| )] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>WinExe</OutputType> | ||
| <TargetFramework>net10.0-windows</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <UseWPF>true</UseWPF> | ||
| </PropertyGroup> | ||
|
|
||
| <Target Name="ValidateWebAssets" BeforeTargets="Build"> | ||
| <Error Condition="!Exists('WebAssets\dist\index.html')" | ||
| Text="Missing built WebAssets. Run 'npm install' and 'npm run build' in embedded-assistant/c-sharp-wpf/WebAssets before building the WPF app." /> | ||
| </Target> | ||
|
|
||
| <Target Name="CopyWebAssets" AfterTargets="Build"> | ||
| <ItemGroup> | ||
| <WebAssetFiles Include="WebAssets\dist\**\*" /> | ||
| </ItemGroup> | ||
| <Copy SourceFiles="@(WebAssetFiles)" DestinationFiles="@(WebAssetFiles->'$(OutDir)WebAssets\%(RecursiveDir)%(Filename)%(Extension)')" /> | ||
| </Target> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="DotNetEnv" Version="3.1.1" /> | ||
| <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.3856.49" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| <Solution> | ||
| <Project Path="CortiAssistantApp.csproj" /> | ||
| </Solution> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| <Window x:Class="CortiAssistantApp.MainWindow" | ||
| xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" | ||
| xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | ||
| xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf" | ||
| Title="Corti Assistant" Height="800" Width="1200"> | ||
| <Grid> | ||
| <Grid.RowDefinitions> | ||
| <RowDefinition Height="Auto"/> | ||
| <RowDefinition Height="*"/> | ||
| </Grid.RowDefinitions> | ||
|
|
||
| <Button x:Name="AuthButton" | ||
| Grid.Row="0" | ||
| Content="Authenticate" | ||
| Click="AuthButton_Click" | ||
| Margin="10" | ||
| Padding="10,5" | ||
| IsEnabled="False"/> | ||
|
|
||
| <wv2:WebView2 x:Name="CortiWebView" | ||
| Grid.Row="1"/> | ||
| </Grid> | ||
| </Window> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,284 @@ | ||
| using CortiAssistantApp.Services; | ||
| using Microsoft.Web.WebView2.Core; | ||
| using System.IO; | ||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization; | ||
| using System.Windows; | ||
|
|
||
| namespace CortiAssistantApp | ||
| { | ||
| public partial class MainWindow : Window | ||
| { | ||
| private const string LocalHostOrigin = "https://corti.local"; | ||
|
|
||
| private readonly CortiSettings _settings = null!; | ||
| private readonly CortiAuthService _authService = null!; | ||
| private readonly JsonSerializerOptions _jsonOptions = new() | ||
| { | ||
| PropertyNameCaseInsensitive = true, | ||
| }; | ||
|
|
||
| private AuthTokens _authTokens = null!; | ||
| private TaskCompletionSource<bool>? _bootstrapPending; | ||
| private BootstrapMessage? _pendingBootstrapMessage; | ||
|
|
||
| public MainWindow() | ||
| { | ||
| InitializeComponent(); | ||
|
|
||
| try | ||
| { | ||
| _settings = CortiSettings.LoadFromProjectEnv(); | ||
| _authService = new CortiAuthService(_settings); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| MessageBox.Show(ex.Message, "Configuration Error", MessageBoxButton.OK, MessageBoxImage.Error); | ||
| Close(); | ||
| return; | ||
| } | ||
|
|
||
| Loaded += MainWindow_Loaded; | ||
| } | ||
|
|
||
| private async void MainWindow_Loaded(object sender, RoutedEventArgs e) | ||
| { | ||
| Loaded -= MainWindow_Loaded; | ||
| await InitializeWebViewAsync(); | ||
| } | ||
|
|
||
| private async Task InitializeWebViewAsync() | ||
| { | ||
| try | ||
| { | ||
| var userDataFolder = Path.Combine( | ||
| Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), | ||
| "CortiAssistantApp", | ||
| "WebView2" | ||
| ); | ||
|
|
||
| var environment = await CoreWebView2Environment.CreateAsync( | ||
| null, | ||
| userDataFolder, | ||
| new CoreWebView2EnvironmentOptions | ||
| { | ||
| AdditionalBrowserArguments = "--enable-features=WebRTC " + | ||
| "--enable-media-stream " + | ||
| "--autoplay-policy=no-user-gesture-required" | ||
| } | ||
|
hriczzoli marked this conversation as resolved.
|
||
| ); | ||
|
|
||
| await CortiWebView.EnsureCoreWebView2Async(environment); | ||
|
|
||
| var webAssetsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WebAssets"); | ||
| var webAssetsIndexPath = Path.Combine(webAssetsPath, "index.html"); | ||
| if (!File.Exists(webAssetsIndexPath)) | ||
| { | ||
| throw new FileNotFoundException( | ||
| "Built WebAssets were not found. Run 'npm install' and 'npm run build' in the WebAssets folder, then rebuild the WPF app.", | ||
| webAssetsIndexPath | ||
| ); | ||
| } | ||
|
|
||
| CortiWebView.CoreWebView2.SetVirtualHostNameToFolderMapping( | ||
| "corti.local", | ||
| webAssetsPath, | ||
| CoreWebView2HostResourceAccessKind.Allow | ||
| ); | ||
|
|
||
| CortiWebView.CoreWebView2.Settings.AreDevToolsEnabled = | ||
| #if DEBUG | ||
| true; | ||
| #else | ||
| false; | ||
| #endif | ||
| CortiWebView.CoreWebView2.Settings.AreDefaultScriptDialogsEnabled = false; | ||
| CortiWebView.CoreWebView2.Settings.IsWebMessageEnabled = true; | ||
| CortiWebView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false; | ||
| CortiWebView.CoreWebView2.Settings.IsStatusBarEnabled = false; | ||
|
|
||
| CortiWebView.CoreWebView2.PermissionRequested += CoreWebView2_PermissionRequested; | ||
| CortiWebView.CoreWebView2.WebMessageReceived += WebView_WebMessageReceived; | ||
|
|
||
| AuthButton.IsEnabled = true; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| MessageBox.Show(ex.Message, "WebView Initialization Error", MessageBoxButton.OK, MessageBoxImage.Error); | ||
| } | ||
| } | ||
|
|
||
| private async void AuthButton_Click(object sender, RoutedEventArgs e) | ||
| { | ||
| try | ||
| { | ||
| AuthButton.IsEnabled = false; | ||
| AuthButton.Content = "Authenticating..."; | ||
|
|
||
| _authTokens = await _authService.AuthenticateAsync(); | ||
| await LoadCortiAssistant(); | ||
|
|
||
| AuthButton.Visibility = Visibility.Collapsed; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| MessageBox.Show($"Authentication failed: {ex.Message}", "Error", | ||
| MessageBoxButton.OK, MessageBoxImage.Error); | ||
| AuthButton.IsEnabled = true; | ||
| AuthButton.Content = "Authenticate"; | ||
| } | ||
| } | ||
|
|
||
| private async Task LoadCortiAssistant() | ||
| { | ||
| if (CortiWebView.CoreWebView2 is null) | ||
| { | ||
| throw new InvalidOperationException("WebView2 is not ready yet."); | ||
| } | ||
|
|
||
| var navigationCompleted = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); | ||
| _bootstrapPending = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); | ||
| _pendingBootstrapMessage = new BootstrapMessage | ||
| { | ||
| AccessToken = _authTokens.AccessToken, | ||
| RefreshToken = _authTokens.RefreshToken, | ||
| IdToken = _authTokens.IdToken, | ||
| TokenType = _authTokens.JsonTokenType, | ||
| ExpiresIn = _authTokens.ExpiresIn, | ||
| BaseUrl = $"https://assistant.{_settings.EnvironmentName}.corti.app" | ||
| }; | ||
|
|
||
| void OnNavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e) | ||
| { | ||
| navigationCompleted.TrySetResult(e.IsSuccess); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| CortiWebView.CoreWebView2.NavigationCompleted += OnNavigationCompleted; | ||
| CortiWebView.CoreWebView2.Navigate("https://corti.local/index.html"); | ||
|
|
||
| var success = await navigationCompleted.Task; | ||
| if (!success) | ||
| { | ||
| throw new Exception("Failed to load the Corti Assistant page."); | ||
| } | ||
|
|
||
| var bootstrapCompleted = await Task.WhenAny(_bootstrapPending.Task, Task.Delay(TimeSpan.FromSeconds(10))); | ||
| if (bootstrapCompleted != _bootstrapPending.Task || !_bootstrapPending.Task.Result) | ||
| { | ||
| throw new TimeoutException("Timed out waiting for the embedded page to request bootstrap data."); | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| CortiWebView.CoreWebView2.NavigationCompleted -= OnNavigationCompleted; | ||
| _pendingBootstrapMessage = null; | ||
| _bootstrapPending = null; | ||
| } | ||
| } | ||
|
|
||
| private void CoreWebView2_PermissionRequested(object? sender, CoreWebView2PermissionRequestedEventArgs args) | ||
| { | ||
| if (args.PermissionKind == CoreWebView2PermissionKind.Microphone && | ||
| IsTrustedMicrophoneOrigin(args.Uri)) | ||
| { | ||
| args.State = CoreWebView2PermissionState.Allow; | ||
| return; | ||
| } | ||
|
|
||
| args.State = CoreWebView2PermissionState.Deny; | ||
| } | ||
|
|
||
| private bool IsTrustedMicrophoneOrigin(string? uri) | ||
| { | ||
| if (string.IsNullOrWhiteSpace(uri)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| if (!Uri.TryCreate(uri, UriKind.Absolute, out var requestUri)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| var origin = requestUri.GetLeftPart(UriPartial.Authority); | ||
| if (string.Equals(origin, LocalHostOrigin, StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| var assistantOrigin = $"https://assistant.{_settings.EnvironmentName}.corti.app"; | ||
| return string.Equals(origin, assistantOrigin, StringComparison.OrdinalIgnoreCase); | ||
| } | ||
|
|
||
| private void WebView_WebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e) | ||
| { | ||
| var message = e.TryGetWebMessageAsString(); | ||
| if (string.IsNullOrWhiteSpace(message)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var eventData = JsonSerializer.Deserialize<HostMessage>(message, _jsonOptions); | ||
| if (eventData is not null) | ||
| { | ||
| HandleHostMessage(eventData); | ||
| } | ||
|
hriczzoli marked this conversation as resolved.
|
||
| } | ||
|
|
||
| private void HandleHostMessage(HostMessage eventData) | ||
| { | ||
| switch (eventData.Type) | ||
| { | ||
| case "host.ready": | ||
| if (CortiWebView.CoreWebView2 is not null && _pendingBootstrapMessage is not null) | ||
| { | ||
| CortiWebView.CoreWebView2.PostWebMessageAsJson( | ||
| JsonSerializer.Serialize(_pendingBootstrapMessage, _jsonOptions) | ||
| ); | ||
| _bootstrapPending?.TrySetResult(true); | ||
| } | ||
| break; | ||
| case "session.started": | ||
| break; | ||
| case "error": | ||
| var errorMessage = eventData.Payload.ValueKind == JsonValueKind.String | ||
| ? eventData.Payload.GetString() | ||
| : eventData.Payload.GetRawText(); | ||
| MessageBox.Show($"Error: {errorMessage}", "Assistant Error"); | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| private sealed class HostMessage | ||
| { | ||
| [JsonPropertyName("type")] | ||
| public string Type { get; set; } = string.Empty; | ||
|
|
||
| [JsonPropertyName("payload")] | ||
| public JsonElement Payload { get; set; } | ||
| } | ||
|
|
||
| private sealed class BootstrapMessage | ||
| { | ||
| [JsonPropertyName("access_token")] | ||
| public string AccessToken { get; set; } = string.Empty; | ||
|
|
||
| [JsonPropertyName("refresh_token")] | ||
| public string RefreshToken { get; set; } = string.Empty; | ||
|
|
||
| [JsonPropertyName("id_token")] | ||
| public string IdToken { get; set; } = string.Empty; | ||
|
|
||
| [JsonPropertyName("token_type")] | ||
| public string TokenType { get; set; } = string.Empty; | ||
|
|
||
| [JsonPropertyName("expires_in")] | ||
| public int ExpiresIn { get; set; } | ||
|
|
||
| [JsonPropertyName("baseUrl")] | ||
| public string BaseUrl { get; set; } = string.Empty; | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
CopyWebAssetssilently does nothing ifWebAssets/disthasn't been built yet, which can lead to a successful build but a broken runtime experience (noindex.htmlunder the virtual host mapping). Consider failing the build whenWebAssets/distis missing, or adding an MSBuild step that runsnpm ci && npm run buildfor this sample.