Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions embedded-assistant/c-sharp-wpf/.env.example
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
10 changes: 10 additions & 0 deletions embedded-assistant/c-sharp-wpf/.gitignore
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/
9 changes: 9 additions & 0 deletions embedded-assistant/c-sharp-wpf/App.xaml
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>
14 changes: 14 additions & 0 deletions embedded-assistant/c-sharp-wpf/App.xaml.cs
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
{
}

}
10 changes: 10 additions & 0 deletions embedded-assistant/c-sharp-wpf/AssemblyInfo.cs
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)
)]
28 changes: 28 additions & 0 deletions embedded-assistant/c-sharp-wpf/CortiAssistantApp.csproj
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>
Comment on lines +16 to +21
Copy link

Copilot AI Mar 20, 2026

Choose a reason for hiding this comment

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

CopyWebAssets silently does nothing if WebAssets/dist hasn't been built yet, which can lead to a successful build but a broken runtime experience (no index.html under the virtual host mapping). Consider failing the build when WebAssets/dist is missing, or adding an MSBuild step that runs npm ci && npm run build for this sample.

Copilot uses AI. Check for mistakes.

<ItemGroup>
<PackageReference Include="DotNetEnv" Version="3.1.1" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.3856.49" />
</ItemGroup>

</Project>
3 changes: 3 additions & 0 deletions embedded-assistant/c-sharp-wpf/CortiAssistantApp.slnx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<Solution>
<Project Path="CortiAssistantApp.csproj" />
</Solution>
23 changes: 23 additions & 0 deletions embedded-assistant/c-sharp-wpf/MainWindow.xaml
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>
284 changes: 284 additions & 0 deletions embedded-assistant/c-sharp-wpf/MainWindow.xaml.cs
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"
}
Comment thread
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);
}
Comment thread
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;
}
}
}
Loading
Loading