From c402f4a5e917c382ba0cc2e51366fcafe097e860 Mon Sep 17 00:00:00 2001 From: Gerald Versluis Date: Sun, 22 Mar 2026 21:55:31 +0100 Subject: [PATCH 1/8] Add AI-assisted development documentation section New section with 6 guides covering: - Overview of AI tooling for MAUI development - Writing effective copilot-instructions.md - Custom instruction files (.github/instructions/) - .NET Agent Skills marketplace - MauiDevFlow for AI-assisted debugging - Best practices for AI-friendly project structure Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/TOC.yml | 14 + docs/ai-development/best-practices.md | 397 ++++++++++++++++++++ docs/ai-development/copilot-instructions.md | 361 ++++++++++++++++++ docs/ai-development/custom-instructions.md | 247 ++++++++++++ docs/ai-development/devflow.md | 221 +++++++++++ docs/ai-development/index.md | 62 +++ docs/ai-development/skills.md | 211 +++++++++++ 7 files changed, 1513 insertions(+) create mode 100644 docs/ai-development/best-practices.md create mode 100644 docs/ai-development/copilot-instructions.md create mode 100644 docs/ai-development/custom-instructions.md create mode 100644 docs/ai-development/devflow.md create mode 100644 docs/ai-development/index.md create mode 100644 docs/ai-development/skills.md diff --git a/docs/TOC.yml b/docs/TOC.yml index 11e30f3566..848065af31 100644 --- a/docs/TOC.yml +++ b/docs/TOC.yml @@ -1252,6 +1252,20 @@ href: data-cloud/local-web-services.md - name: Artificial intelligence href: ai/TOC.yml + - name: AI-assisted development + items: + - name: Overview + href: ai-development/index.md + - name: Copilot instructions + href: ai-development/copilot-instructions.md + - name: Custom instruction files + href: ai-development/custom-instructions.md + - name: Agent skills + href: ai-development/skills.md + - name: MauiDevFlow + href: ai-development/devflow.md + - name: Best practices + href: ai-development/best-practices.md - name: Deployment & testing items: - name: Overview diff --git a/docs/ai-development/best-practices.md b/docs/ai-development/best-practices.md new file mode 100644 index 0000000000..adf33faaf1 --- /dev/null +++ b/docs/ai-development/best-practices.md @@ -0,0 +1,397 @@ +--- +title: Best practices for AI-assisted .NET MAUI development +description: Learn how to structure your .NET MAUI projects and write code that AI coding assistants can understand, navigate, and extend effectively. +ms.topic: concept +ms.date: 03/22/2026 +no-loc: [".NET MAUI"] +--- + +# Best practices for AI-assisted .NET MAUI development + +AI coding assistants work best when your project follows clear, consistent patterns. The way you organize files, name classes, document APIs, and configure builds directly affects the quality of AI-generated code. This article covers practical techniques to help AI assistants understand your .NET MAUI codebase and produce correct, platform-aware code. + +## Project structure + +A predictable folder layout helps AI assistants locate relevant code and understand the relationships between components. The standard .NET MAUI template provides a solid starting point: + +```text +MyApp/ +├── Platforms/ +│ ├── Android/ +│ ├── iOS/ +│ ├── MacCatalyst/ +│ └── Windows/ +├── Resources/ +│ ├── Fonts/ +│ ├── Images/ +│ └── Styles/ +├── Views/ +├── ViewModels/ +├── Models/ +├── Services/ +├── Converters/ +├── App.xaml +├── App.xaml.cs +├── AppShell.xaml +├── MauiProgram.cs +└── MyApp.csproj +``` + +> [!TIP] +> When an AI assistant asks "where should I put this code?", a well-organized folder structure gives it a clear answer. Consistent structure across your team's projects means the AI learns the pattern once and applies it everywhere. + +Follow these guidelines: + +- **Keep platform-specific code in `Platforms/` folders.** This is where Android activities, iOS app delegates, and Windows app lifecycle code belong. +- **Group by feature or role.** Use folders like `Views/`, `ViewModels/`, `Services/`, and `Models/` so that AI assistants can infer a file's purpose from its location. +- **Separate shared logic from platform code.** Business logic and shared services should live outside `Platforms/` so AI assistants don't accidentally mix platform-specific APIs into shared code. +- **Use a consistent structure across projects.** If your team has multiple .NET MAUI apps, use the same folder layout in each. AI assistants carry learned patterns between projects. + +## Platform-specific code patterns + +.NET MAUI targets multiple platforms from a single project. AI assistants need to understand how your code handles platform differences — getting this wrong causes build failures that can be difficult to diagnose. + +### File naming conventions + +Use platform-specific file name suffixes to compile code only on the target platform: + +```text +Services/ +├── DeviceService.cs # Shared interface +├── DeviceService.android.cs # Android implementation +├── DeviceService.ios.cs # iOS implementation +├── DeviceService.maccatalyst.cs # Mac Catalyst implementation +└── DeviceService.windows.cs # Windows implementation +``` + +The .NET MAUI build system automatically compiles `.android.cs` files only for Android, `.ios.cs` files only for iOS, and so on. + +> [!WARNING] +> The `.ios.cs` and `.maccatalyst.cs` files compile independently — they do **not** share code. AI assistants frequently assume that iOS code also runs on Mac Catalyst because both use Apple frameworks. If your iOS and Mac Catalyst implementations are identical, you must duplicate the code in both files or use a shared base class. + +### Partial classes with platform implementations + +Partial classes let you split a type across shared and platform-specific files: + +```csharp +// Services/DeviceService.cs (shared) +public partial class DeviceService +{ + public partial string GetDeviceIdentifier(); +} + +// Services/DeviceService.android.cs +public partial class DeviceService +{ + public partial string GetDeviceIdentifier() + { + return Android.Provider.Settings.Secure.GetString( + Android.App.Application.Context.ContentResolver, + Android.Provider.Settings.Secure.AndroidId) ?? "unknown"; + } +} +``` + +### Conditional compilation + +For small platform differences, use `#if` directives: + +```csharp +public string GetDefaultCacheSize() +{ +#if ANDROID + return "150MB"; +#elif IOS || MACCATALYST + return "100MB"; +#elif WINDOWS + return "200MB"; +#else + return "100MB"; +#endif +} +``` + +> [!NOTE] +> Prefer partial classes or platform-specific files over `#if` directives when the platform-specific code is more than a few lines. Large blocks of conditional compilation are harder for AI assistants to reason about because they must mentally track which branches are active for each platform. + +### Dependency injection for platform services + +Register platform-specific implementations in `MauiProgram.cs`: + +```csharp +public static MauiApp CreateMauiApp() +{ + var builder = MauiApp.CreateBuilder(); + builder.UseMauiApp(); + + // Register shared services + builder.Services.AddSingleton(); + builder.Services.AddTransient(); + + return builder.Build(); +} +``` + +Document service registrations in your repository instructions file so AI assistants know which interfaces are available and how they're resolved. + +## Documentation that helps AI + +AI assistants read your documentation to understand intent, architecture, and constraints. Well-placed documentation dramatically improves code generation quality. + +### XML documentation comments + +AI assistants read XML documentation comments to understand what a method does, what its parameters mean, and what callers should expect: + +```csharp +/// +/// Synchronizes local data with the remote API. +/// +/// +/// This method is safe to call from any thread. It acquires a lock +/// to prevent concurrent sync operations. On iOS, ensure the app +/// has background fetch capability enabled if calling from a +/// background task. +/// +/// +/// When , syncs all records regardless of +/// their last-modified timestamp. +/// +/// The number of records synchronized. +/// +/// Thrown when the device is offline or the API is unreachable. +/// +public async Task SyncDataAsync(bool force = false) +``` + +> [!TIP] +> Focus XML documentation on public APIs, especially interfaces that have platform-specific implementations. AI assistants use these comments as a specification when generating implementation code. + +### README and architecture documentation + +Include a `README.md` at the repository root with: + +- **Build instructions** for each platform (`dotnet build -f net10.0-android`, `dotnet build -f net10.0-ios`) +- **Architecture overview** describing the patterns used (MVVM, dependency injection, messaging) +- **Key dependencies** and their purpose +- **Platform-specific setup** requirements (Xcode version, Android SDK levels, Windows SDK) + +### Architecture Decision Records + +For non-obvious design choices, create Architecture Decision Records (ADRs). AI assistants can read these to understand why your code is structured in a particular way: + +```markdown +# ADR-003: Use SQLite instead of LiteDB + +## Context +We need a local database for offline data storage. + +## Decision +Use sqlite-net-pcl because it has better trimmer +compatibility and smaller binary size on iOS. + +## Consequences +Must write SQL queries manually instead of using +LINQ-based document queries. +``` + +### Inline comments for platform workarounds + +When you work around platform-specific behavior, explain **why** the workaround exists: + +```csharp +// Android: WebView.EvaluateJavaScriptAsync can deadlock if called +// before the page finishes loading. Wait for Navigated event first. +// See: https://github.com/dotnet/maui/issues/12345 +webView.Navigated += async (s, e) => +{ + var result = await webView.EvaluateJavaScriptAsync("getData()"); +}; +``` + +## Common pitfalls AI should know about + +These are mistakes AI assistants frequently make with .NET MAUI code. Document these patterns in your [repository instructions file](copilot-instructions.md) so the AI avoids them. + +### Static fields that call platform APIs + +Platform APIs like `FileSystem.AppDataDirectory` aren't available during type initialization. Static readonly fields are evaluated at type load time, which can happen before the .NET MAUI platform is initialized: + +```csharp +// ❌ WRONG — evaluated during type initialization, before MAUI platform is ready +private static readonly string CachePath = + Path.Combine(FileSystem.AppDataDirectory, "cache"); + +// ✅ CORRECT — lazy evaluation defers the call until first access +private static string? _cachePath; +private static string CachePath => + _cachePath ??= Path.Combine(FileSystem.AppDataDirectory, "cache"); +``` + +### Linker and trimmer safety + +The .NET trimmer removes code that appears unused at build time. Types accessed only through reflection — such as dependency injection registrations or XAML type references — can be trimmed away: + +```xml + + + + +``` + +Alternatively, use the `[DynamicallyAccessedMembers]` or `[RequiresUnreferencedCode]` attributes to annotate methods that use reflection. + +### iOS file system paths + +On iOS, `Environment.SpecialFolder.LocalApplicationData` maps to a **cache** directory that the OS can purge at any time. For persistent data, always use the .NET MAUI file system API: + +```csharp +// ❌ WRONG on iOS — this path can be purged by the OS +var path = Environment.GetFolderPath( + Environment.SpecialFolder.LocalApplicationData); + +// ✅ CORRECT — guaranteed persistent across app launches +var path = FileSystem.AppDataDirectory; +``` + +### Android edge-to-edge display + +Starting with .NET 10, Android apps default to edge-to-edge display with `SafeAreaEdges` set to `None`. UI elements can render behind the system status bar and navigation bar. Account for safe areas in your layouts: + +```xml + + + +``` + +### XAML Hot Reload limitations + +Not all XAML changes apply through Hot Reload. These changes require a full rebuild: + +- Adding or removing resource dictionaries +- Changing `x:Class` declarations +- Modifying the class hierarchy +- Adding new custom controls for the first time + +> [!IMPORTANT] +> Document XAML Hot Reload limitations in your repository instructions so AI assistants don't suggest iterating on changes that require a full rebuild. + +## Build and test configuration + +AI assistants need to know how to build and test your project for each platform. Document these details in your `README.md` or repository instructions file. + +### Build commands + +Provide explicit build commands for each target framework: + +```bash +# Build for Android +dotnet build -f net10.0-android + +# Build for iOS (requires macOS) +dotnet build -f net10.0-ios + +# Build for Windows +dotnet build -f net10.0-windows10.0.19041.0 + +# Run on a specific platform +dotnet build -f net10.0-android -t:Run +``` + +### Test configuration + +Specify your test framework and how to run tests: + +```bash +# Run unit tests +dotnet test MyApp.Tests/MyApp.Tests.csproj + +# Run with specific verbosity +dotnet test --verbosity normal --logger "console;verbosity=detailed" +``` + +List required workloads, emulators, or simulators so AI assistants can troubleshoot build failures: + +```bash +# Required workloads +dotnet workload install maui-android maui-ios maui-maccatalyst + +# List available Android emulators +emulator -list-avds +``` + +## Dependency management + +### Central Package Management + +Use `Directory.Packages.props` to centralize NuGet package versions across your solution. This prevents version conflicts and gives AI assistants a single location to check for available packages: + +```xml + + + true + + + + + + + + +``` + +> [!NOTE] +> When using Central Package Management, individual project files use `` without specifying a version. AI assistants sometimes add version attributes anyway — document this convention in your repository instructions to prevent it. + +### Platform-specific packages + +Some NuGet packages behave differently per platform or are only available on certain platforms. Document these in your instructions: + +```markdown +## Key packages +- **CommunityToolkit.Maui** — cross-platform, but MediaElement + has different codec support per platform +- **sqlite-net-pcl** — requires SQLitePCLRaw.bundle_green on + all platforms for native SQLite binaries +- **SkiaSharp** — GPU acceleration available on Android/iOS, + software rendering on some Windows configurations +``` + +## .editorconfig and code formatting + +AI assistants read `.editorconfig` files and use them to match your code style. Include one in your repository root: + +```ini +[*.cs] +indent_style = space +indent_size = 4 +charset = utf-8 + +# Naming conventions +dotnet_naming_rule.private_fields.symbols = private_fields +dotnet_naming_rule.private_fields.style = prefix_underscore +dotnet_naming_rule.private_fields.severity = suggestion + +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private + +dotnet_naming_style.prefix_underscore.capitalization = camel_case +dotnet_naming_style.prefix_underscore.required_prefix = _ + +# Code style +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_expression_bodied_methods = when_on_single_line:suggestion +csharp_prefer_braces = true:suggestion + +[*.xaml] +indent_style = space +indent_size = 4 +``` + +> [!TIP] +> If your team uses non-standard naming conventions (such as `m_` prefixes for member fields or `I` prefixes for all interfaces), document these explicitly in your `.editorconfig` and repository instructions. AI assistants default to standard .NET naming conventions and need explicit guidance to deviate. + +## See also + +- [Repository instructions for .NET MAUI](copilot-instructions.md) +- [Custom instruction files](custom-instructions.md) +- [.NET Agent Skills for .NET MAUI](skills.md) diff --git a/docs/ai-development/copilot-instructions.md b/docs/ai-development/copilot-instructions.md new file mode 100644 index 0000000000..cc84b82fdb --- /dev/null +++ b/docs/ai-development/copilot-instructions.md @@ -0,0 +1,361 @@ +--- +title: Write a copilot-instructions.md file for .NET MAUI projects +description: Learn how to create an effective .github/copilot-instructions.md file that gives GitHub Copilot context about your .NET MAUI project structure, platform targets, and coding conventions. +ms.topic: how-to +ms.date: 03/22/2026 +no-loc: [".NET MAUI"] +--- + +# Write a copilot-instructions.md file for .NET MAUI projects + +GitHub Copilot reads a `.github/copilot-instructions.md` file from your repository to understand your project's context. For .NET MAUI projects, this file is especially valuable because MAUI apps have cross-platform complexity that AI assistants frequently get wrong — platform-specific file naming conventions, conditional compilation symbols, and multi-target build commands all benefit from explicit documentation. + +When you provide a well-written instructions file, Copilot generates code that follows your project's actual patterns instead of guessing. This means fewer corrections for platform-specific code, correct build commands on the first try, and suggestions that match your MVVM framework, dependency injection setup, and navigation model. + +> [!TIP] +> The `.github/copilot-instructions.md` file is automatically loaded by GitHub Copilot in Visual Studio Code, Visual Studio, and the GitHub Copilot CLI. You don't need to reference it manually. + +## Create the file + +Create a file named `copilot-instructions.md` in the `.github` directory at the root of your repository: + +``` +your-maui-project/ +├── .github/ +│ └── copilot-instructions.md ← Create this file +├── Platforms/ +├── Resources/ +├── MauiProgram.cs +└── YourApp.csproj +``` + +If the `.github` directory doesn't exist, create it. This directory is also used for GitHub Actions workflows, issue templates, and other GitHub configuration files. + +## Essential sections for .NET MAUI projects + +The following sections cover what to include in your instructions file. Adapt each section to match your specific project. + +### Project overview + +Start with the fundamentals: framework version, target platforms, architecture pattern, and app type. This helps Copilot understand the overall shape of your project. + +```markdown +## Project Overview + +This is a .NET MAUI app targeting .NET 9, built with Shell navigation. +Targets: Android, iOS, Mac Catalyst, Windows. +Uses MVVM with CommunityToolkit.Mvvm. +UI is built with XAML and code-behind files. +Dependency injection is configured in MauiProgram.cs. +``` + +If your app uses Blazor Hybrid, mention that explicitly — the code patterns differ significantly from pure XAML apps: + +```markdown +## Project Overview + +This is a .NET MAUI Blazor Hybrid app targeting .NET 9. +Targets: Android, iOS, Mac Catalyst, Windows. +UI is built with Razor components in the /Components directory. +Native MAUI pages are used for platform integration only. +``` + +### Build and run commands + +.NET MAUI projects use target framework monikers (TFMs) to build for specific platforms. Include the exact commands so Copilot can suggest the correct build invocation: + +```markdown +## Build Commands + +- All platforms: `dotnet build` +- Android: `dotnet build -f net9.0-android -t:Install` +- iOS Simulator: `dotnet build -f net9.0-ios -t:Run` +- Mac Catalyst: `dotnet build -f net9.0-maccatalyst` +- Windows: `dotnet build -f net9.0-windows10.0.19041.0` + +## Run Commands + +- Android emulator: `dotnet build -f net9.0-android -t:Run` +- iOS Simulator: `dotnet build -f net9.0-ios -t:Run -p:_DeviceName=:v2:udid=SIMULATOR_UDID` +- Mac Catalyst: `dotnet build -f net9.0-maccatalyst -t:Run` +- Windows: `dotnet run -f net9.0-windows10.0.19041.0` +``` + +> [!NOTE] +> If your project uses a specific Windows SDK version other than `10.0.19041.0`, update the TFM accordingly. Check your `.csproj` file for the exact `TargetFrameworks` value. + +### Platform-specific code organization + +This is the most critical section for .NET MAUI projects. AI assistants frequently generate platform-specific code incorrectly because the file naming and compilation rules are unintuitive. + +```markdown +## Platform-Specific Code + +### File naming conventions +- Files ending in `.android.cs` compile only for Android +- Files ending in `.ios.cs` compile for BOTH iOS AND Mac Catalyst +- Files ending in `.maccatalyst.cs` compile ONLY for Mac Catalyst +- Files ending in `.windows.cs` compile only for Windows + +### IMPORTANT: iOS and Mac Catalyst overlap +Both `.ios.cs` and `.maccatalyst.cs` files compile for Mac Catalyst targets. +There is NO precedence mechanism — if both exist with the same partial class, +you will get compilation errors on Mac Catalyst. + +### Platform folders +- `Platforms/Android/` — Android-specific code (Activities, Services) +- `Platforms/iOS/` — iOS-specific code (AppDelegate, SceneDelegate) +- `Platforms/MacCatalyst/` — Mac Catalyst code (AppDelegate, SceneDelegate) +- `Platforms/Windows/` — Windows code (App.xaml.cs, Package.appxmanifest) +- `Platforms/Tizen/` — Tizen code (if targeting Tizen) + +### Conditional compilation symbols +Use these preprocessor directives for platform-specific code in shared files: +- `#if ANDROID` — Android only +- `#if IOS` — iOS only (does NOT include Mac Catalyst) +- `#if MACCATALYST` — Mac Catalyst only +- `#if WINDOWS` — Windows only +- `#if IOS || MACCATALYST` — Both Apple mobile platforms +``` + +> [!IMPORTANT] +> The `.ios.cs` and Mac Catalyst double-compilation behavior is the single most common source of AI-generated build errors in .NET MAUI projects. Always include this information in your instructions file. + +### Project structure + +Document your directory layout so Copilot understands where to place new files: + +```markdown +## Project Structure + +``` +src/MyApp/ +├── App.xaml(.cs) — Application entry, resource loading +├── AppShell.xaml(.cs) — Shell navigation structure +├── MauiProgram.cs — DI container, service registration +├── Models/ — Data models and DTOs +├── ViewModels/ — MVVM view models +├── Views/ — XAML pages and controls +├── Services/ — Business logic and data access +├── Converters/ — IValueConverter implementations +├── Handlers/ — Custom handler implementations +├── Resources/ +│ ├── Fonts/ — Custom fonts (.ttf, .otf) +│ ├── Images/ — SVG and PNG images +│ ├── Raw/ — Raw assets (JSON, HTML) +│ └── Styles/ — XAML resource dictionaries +└── Platforms/ — Platform-specific code +``` +``` + +### Testing patterns + +Describe your test setup so Copilot can generate tests that match your infrastructure: + +```markdown +## Testing + +- Unit tests: `tests/MyApp.Tests/` using xUnit +- Run tests: `dotnet test tests/MyApp.Tests/` +- UI tests: `tests/MyApp.UITests/` using Appium with .NET +- Mocking framework: NSubstitute +- View model tests should not reference any MAUI types directly +- Use `IDispatcher` abstraction instead of `MainThread.InvokeOnMainThreadAsync` +``` + +### NuGet packages and dependencies + +List key packages so Copilot understands what APIs are available: + +```markdown +## Key NuGet Packages + +- `CommunityToolkit.Mvvm` (v8.4.0) — Source generators for MVVM: + [ObservableProperty], [RelayCommand], ObservableObject +- `CommunityToolkit.Maui` (v10.0.0) — Extra controls, converters, behaviors +- `Microsoft.Extensions.Http` — Typed HttpClient via DI +- `SQLite-net-pcl` — Local database with SQLiteAsyncConnection +- `SkiaSharp.Views.Maui.Controls` — 2D graphics rendering + +Do NOT suggest packages we don't use. If a task requires a new package, +mention it explicitly before adding it. +``` + +### Coding conventions + +Document your team's patterns so generated code is consistent: + +```markdown +## Coding Conventions + +- Use file-scoped namespaces +- Use primary constructors for dependency injection +- ViewModels inherit from ObservableObject (CommunityToolkit.Mvvm) +- Use [ObservableProperty] instead of manual INotifyPropertyChanged +- Use [RelayCommand] instead of manual ICommand implementations +- XAML pages use x:DataType for compiled bindings +- All async methods should use ConfigureAwait(false) except in UI code +- Services are registered in MauiProgram.cs using extension methods +- Use SemanticProperties for accessibility on all interactive elements +``` + +## .NET MAUI-specific tips + +Beyond the sections above, consider documenting these patterns that AI assistants frequently handle incorrectly. + +### Handlers vs. renderers + +.NET MAUI uses the handler architecture, not the legacy Xamarin.Forms renderer pattern: + +```markdown +## Platform Customization + +This project uses the .NET MAUI handler architecture. Do NOT use or suggest +Xamarin.Forms custom renderers. When customizing native controls: + +1. Use handler mapping in MauiProgram.cs: + `handlers.AddHandler()` +2. Or use handler lifecycle methods: + `Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping(...)` +``` + +### App entry point + +```markdown +## App Entry Point + +MauiProgram.cs is the single entry point. Platform-specific startup code goes in: +- Android: Platforms/Android/MainApplication.cs +- iOS: Platforms/iOS/AppDelegate.cs +- Mac Catalyst: Platforms/MacCatalyst/AppDelegate.cs +- Windows: Platforms/Windows/App.xaml.cs +``` + +### XAML and resource dictionaries + +```markdown +## XAML Patterns + +- All styles are defined in Resources/Styles/Styles.xaml +- App-wide resources are in App.xaml +- Use StaticResource for styles, DynamicResource for theme-aware values +- Custom colors are defined in Resources/Styles/Colors.xaml +- Use compiled bindings with x:DataType on every page +``` + +### Shell navigation + +If your app uses Shell, document the routing pattern: + +```markdown +## Navigation + +This app uses Shell navigation. Routes are registered in AppShell.xaml.cs: +- `Routing.RegisterRoute(nameof(DetailPage), typeof(DetailPage));` +- Navigate with: `await Shell.Current.GoToAsync(nameof(DetailPage));` +- Pass parameters with: `await Shell.Current.GoToAsync($"{nameof(DetailPage)}?id={itemId}");` +- Receive parameters with [QueryProperty] attribute or IQueryAttributable +``` + +## Template + +Use the following template as a starting point for your own `.github/copilot-instructions.md` file. Remove sections that don't apply and add details specific to your project. + +```markdown +# Copilot Instructions for [Your App Name] + +## Project Overview + +This is a .NET MAUI app targeting .NET 9. +Architecture: MVVM with CommunityToolkit.Mvvm. +Navigation: Shell-based. +Target platforms: Android, iOS, Mac Catalyst, Windows. + +## Build Commands + +- All platforms: `dotnet build` +- Android: `dotnet build -f net9.0-android` +- iOS Simulator: `dotnet build -f net9.0-ios` +- Mac Catalyst: `dotnet build -f net9.0-maccatalyst` +- Windows: `dotnet build -f net9.0-windows10.0.19041.0` + +## Platform-Specific Code + +### File naming +- `.android.cs` → Android only +- `.ios.cs` → iOS AND Mac Catalyst +- `.maccatalyst.cs` → Mac Catalyst only +- `.windows.cs` → Windows only + +IMPORTANT: `.ios.cs` files compile for Mac Catalyst too. +Do not create both `.ios.cs` and `.maccatalyst.cs` for the same partial class. + +### Conditional compilation +- `#if ANDROID`, `#if IOS`, `#if MACCATALYST`, `#if WINDOWS` +- `#if IOS || MACCATALYST` for both Apple platforms + +### Platform folders +- `Platforms/Android/` — Android entry points, services +- `Platforms/iOS/` — iOS AppDelegate, scene configuration +- `Platforms/MacCatalyst/` — Mac Catalyst AppDelegate +- `Platforms/Windows/` — Windows App.xaml.cs + +## Project Structure + +- `MauiProgram.cs` — App entry point, DI registration +- `App.xaml(.cs)` — Application lifecycle +- `AppShell.xaml(.cs)` — Navigation structure +- `Models/` — Data models +- `ViewModels/` — ObservableObject-based view models +- `Views/` — XAML pages +- `Services/` — Business logic, data access +- `Resources/Styles/` — Colors.xaml, Styles.xaml + +## Key Packages + +- CommunityToolkit.Mvvm — [ObservableProperty], [RelayCommand] +- CommunityToolkit.Maui — Additional controls and converters + +## Coding Conventions + +- File-scoped namespaces +- Primary constructors for DI +- [ObservableProperty] for bindable properties +- [RelayCommand] for commands +- Compiled bindings with x:DataType +- SemanticProperties on interactive elements + +## Testing + +- Framework: xUnit +- Run: `dotnet test` +- ViewModels must not depend on MAUI types directly + +## App Entry Point + +- Shared: MauiProgram.cs +- Android: Platforms/Android/MainApplication.cs +- iOS: Platforms/iOS/AppDelegate.cs +- Mac Catalyst: Platforms/MacCatalyst/AppDelegate.cs +- Windows: Platforms/Windows/App.xaml.cs + +## XAML Patterns + +- Styles: Resources/Styles/Styles.xaml +- Colors: Resources/Styles/Colors.xaml +- Use StaticResource for styles +- Use DynamicResource for theme-aware values + +## Navigation + +- Shell-based navigation +- Register routes in AppShell.xaml.cs +- Navigate: `await Shell.Current.GoToAsync(nameof(Page))` +- Parameters: use [QueryProperty] or IQueryAttributable +``` + +## See also + +- [Create custom instructions for GitHub Copilot](custom-instructions.md) +- [Best practices for AI-assisted .NET MAUI development](best-practices.md) +- [Use Copilot skills with .NET MAUI](skills.md) diff --git a/docs/ai-development/custom-instructions.md b/docs/ai-development/custom-instructions.md new file mode 100644 index 0000000000..daf437129b --- /dev/null +++ b/docs/ai-development/custom-instructions.md @@ -0,0 +1,247 @@ +--- +title: Custom instruction files and AGENTS.md +description: Learn how to use task-specific instruction files and AGENTS.md to give AI assistants focused guidance for .NET MAUI development tasks. +ms.topic: how-to +ms.date: 03/22/2026 +no-loc: [".NET MAUI"] +--- + +# Custom instruction files and AGENTS.md + +While `copilot-instructions.md` provides project-wide context, custom instruction files let you provide focused guidance for specific tasks or file types. These files live in `.github/instructions/` and are loaded automatically based on file glob patterns. For project-wide setup, see [Custom instructions for GitHub Copilot](copilot-instructions.md). + +This article covers how to create task-specific instruction files and how to use `AGENTS.md` for repository-level agent policies. + +## Custom instruction files + +Custom instruction files use the naming convention `.github/instructions/.instructions.md`. Each file contains YAML front matter with an `applyTo` field that specifies a glob pattern. When you work on files matching that pattern, the AI assistant automatically includes the corresponding instructions in its context. + +```text +.github/ + instructions/ + safe-area-ios.instructions.md + uitests.instructions.md + xaml.instructions.md + android-handlers.instructions.md +``` + +### File format + +Every custom instruction file starts with YAML front matter containing the `applyTo` glob pattern, followed by Markdown content: + +```markdown +--- +applyTo: "**/*.xaml" +--- + +Your instructions here in Markdown format. +``` + +The `applyTo` field accepts comma-separated glob patterns to match multiple file types or directories. + +> [!TIP] +> Keep each instruction file focused on a single concern. Multiple small files are easier to maintain than one large file covering everything. + +## .NET MAUI instruction file examples + +The following examples show instruction files for common .NET MAUI development scenarios. Use them as starting points and adapt them to your project's conventions. + +### iOS and Mac Catalyst safe area handling + +Create `.github/instructions/safe-area-ios.instructions.md` to provide guidance when working on iOS or Mac Catalyst platform code: + +```markdown +--- +applyTo: "**/Platforms/iOS/**,**/Platforms/MacCatalyst/**,**/*.ios.cs,**/*.maccatalyst.cs" +--- + +# iOS and Mac Catalyst platform guidance + +## Safe area insets +- Always account for safe area insets when positioning UI elements. + Use `UIApplication.SharedApplication.ConnectedScenes` to get the + active window scene and read `SafeAreaInsets` from the root view. +- Never hardcode status bar or home indicator heights. Device + geometry varies across iPhone and iPad models. + +## UIKit interop +- When accessing UIKit types from handlers or platform code, use + `MainThread.BeginInvokeOnMainThread` to ensure UI updates run on + the main thread. +- Prefer `PlatformView` properties on handlers over direct + `UIView` manipulation when possible. + +## Platform-specific adjustments +- Use compiler directives (`#if IOS || MACCATALYST`) only in + platform-shared files. Code under `Platforms/iOS/` or + `Platforms/MacCatalyst/` doesn't need them. +- Register platform services in `MauiProgram.cs` using + `ConfigureLifecycleEvents` for iOS-specific lifecycle hooks. +``` + +### UI test writing + +Create `.github/instructions/uitests.instructions.md` to guide AI assistants when writing or modifying tests: + +```markdown +--- +applyTo: "**/*Test*/**,**/*test*/**" +--- + +# UI test conventions + +## Test structure +- Use the Arrange-Act-Assert pattern for all tests. +- Name test methods using the pattern: `MethodName_Scenario_ExpectedResult`. +- One assertion per test method when possible. + +## Appium tests +- Use `FindElement` with `By.Id` using AutomationId values set in XAML. +- Add explicit waits with `WebDriverWait` instead of `Thread.Sleep`. +- Use the page object pattern to encapsulate screen interactions. + +## Device test infrastructure +- Tests must run on both Android and iOS targets. +- Use conditional attributes (`[Trait("Platform", "iOS")]`) to mark + platform-specific tests. +- Store test app bundle identifiers and paths in a shared + configuration file, not inline in test code. +``` + +### XAML patterns + +Create `.github/instructions/xaml.instructions.md` for guidance when editing XAML files and their code-behind: + +```markdown +--- +applyTo: "**/*.xaml,**/*.xaml.cs" +--- + +# XAML conventions + +## Data binding +- Use `x:DataType` on every XAML page and template for compiled + bindings. This enables compile-time checking and improves + performance. +- Bind to view model properties, not code-behind properties. +- Use `CommunityToolkit.Mvvm` source generators for + `ObservableProperty` and `RelayCommand`. + +## Resources and styles +- Define reusable colors and styles in `Resources/Styles/`. +- Use `StaticResource` for values that don't change at runtime and + `DynamicResource` for theme-aware values. +- Follow the naming convention: `PrimaryColor`, `HeaderStyle`, + `DefaultSpacing`. + +## Layout +- Prefer `Grid` and `VerticalStackLayout`/`HorizontalStackLayout` + over nested `StackLayout` for better performance. +- Always set `AutomationId` on interactive controls to support + UI testing. +``` + +### Android handler customization + +Create `.github/instructions/android-handlers.instructions.md` for Android platform code: + +```markdown +--- +applyTo: "**/Platforms/Android/**,**/*.android.cs" +--- + +# Android platform guidance + +## Handlers +- Customize controls by modifying the handler mapper in + `MauiProgram.cs` rather than creating custom renderers. +- Access the native Android view through `PlatformView` on the + handler. +- Call `Invalidate()` on the handler when the cross-platform + property changes need to trigger a native view update. + +## Android lifecycle +- Use `ConfigureLifecycleEvents` in `MauiProgram.cs` to hook into + `OnCreate`, `OnResume`, and `OnDestroy`. +- Request runtime permissions through `Permissions.RequestAsync()` + instead of platform-specific permission APIs. + +## Performance +- Avoid allocations in frequently called handler methods. +- Use `RecyclerView` patterns when working with list-heavy native + views. +``` + +## AGENTS.md + +`AGENTS.md` is a file placed at the root of your repository that provides high-level instructions for AI agents performing autonomous workflows. While `copilot-instructions.md` is optimized for interactive coding assistance, `AGENTS.md` targets agents that work independently, such as those that create pull requests, run builds, or perform multi-step tasks. + +### When to use AGENTS.md + +Use `AGENTS.md` to define repository-wide policies that autonomous agents should follow: + +- **Git workflow** — branch naming conventions, commit message format, when to squash commits. +- **PR requirements** — required reviewers, CI checks that must pass, PR description templates. +- **Build system** — how to build and test the project, which commands to run, expected output. +- **Code standards** — linting rules, formatting requirements, naming conventions. + +### Example AGENTS.md for a .NET MAUI project + +```markdown +# AGENTS.md + +## Build and test +- Build: `dotnet build src/MyApp.sln` +- Test: `dotnet test src/MyApp.sln --no-build` +- All tests must pass before submitting a PR. + +## Git workflow +- Create branches from `main` using the format `feature/` + or `fix/`. +- Write commit messages in imperative mood: "Add feature" not + "Added feature". +- Squash commits before merging. + +## PR requirements +- Include a summary of changes and link to the related issue. +- Add screenshots for any visual changes. +- Ensure CI passes on both Android and iOS targets. + +## Code standards +- Run `dotnet format` before committing. +- Follow the existing naming conventions in the codebase. +- Add XML documentation comments to all public APIs. +``` + +> [!NOTE] +> `AGENTS.md` and `copilot-instructions.md` are complementary. Use both in your project — `copilot-instructions.md` for interactive coding context and `AGENTS.md` for autonomous agent policies. + +## When to use which file + +Use the following table to decide where to put your AI guidance: + +| Scenario | Recommended file | +|---|---| +| Project overview, build commands, architecture | `copilot-instructions.md` | +| Platform-specific coding patterns (iOS, Android) | `.github/instructions/*.instructions.md` | +| File-type guidance (XAML, tests) | `.github/instructions/*.instructions.md` | +| Repository-wide agent policies | `AGENTS.md` | +| Git workflow and PR requirements | `AGENTS.md` | +| Task-specific guidance (testing, accessibility) | `.github/instructions/*.instructions.md` | + +> [!IMPORTANT] +> Custom instruction files are most effective when they are concise and specific. If an instruction file grows beyond a few hundred lines, consider splitting it into multiple files with narrower `applyTo` patterns. + +## Tips for effective instruction files + +Follow these practices to get the most value from your instruction files: + +- **Be specific** — instructions like "use compiled bindings" are more actionable than "follow best practices." +- **Include code patterns** — show the preferred way to write code, not just rules to follow. +- **Update regularly** — review instruction files when your project conventions change. +- **Test with the AI** — ask the AI assistant to write code for a matching file and verify it follows your instructions. + +## See also + +- [Custom instructions for GitHub Copilot](copilot-instructions.md) +- [Best practices for AI-assisted .NET MAUI development](best-practices.md) diff --git a/docs/ai-development/devflow.md b/docs/ai-development/devflow.md new file mode 100644 index 0000000000..3282112d01 --- /dev/null +++ b/docs/ai-development/devflow.md @@ -0,0 +1,221 @@ +--- +title: AI-assisted UI debugging with MauiDevFlow +description: Learn how to use MauiDevFlow to inspect the visual tree, capture screenshots, and debug UI issues in .NET MAUI apps with AI coding assistants. +ms.topic: how-to +ms.date: 03/22/2026 +no-loc: [".NET MAUI"] +--- + +# AI-assisted UI debugging with MauiDevFlow + +MauiDevFlow is an experimental toolkit from maui-labs that provides an HTTP API and CLI for visual tree inspection, element interaction, screenshots, and more in .NET MAUI apps. It's particularly powerful when combined with AI coding assistants, enabling them to inspect your running app's UI and diagnose layout and rendering issues in real time. + +> [!WARNING] +> MauiDevFlow is experimental and its APIs may change without notice. The source is available at [github.com/dotnet/maui-labs](https://github.com/dotnet/maui-labs). + +## What MauiDevFlow provides + +MauiDevFlow exposes a rich set of capabilities for inspecting and interacting with a running .NET MAUI app: + +- **Visual tree inspection** — query the full element hierarchy, including layout properties, binding contexts, and rendered bounds. +- **Element interaction** — programmatically tap, fill text fields, and scroll within your running app. +- **Screenshots** — capture the current state of the app as an image, useful for verifying layout changes. +- **Network monitoring** — observe outgoing HTTP requests and responses from the app. +- **Performance profiling** — collect timing data for rendering and layout passes. +- **Blazor WebView CDP bridge** — connect to Blazor Hybrid WebViews through the Chrome DevTools Protocol for DOM inspection and JavaScript evaluation. +- **MCP server** — exposes 50+ structured tools through the [Model Context Protocol](https://modelcontextprotocol.io), allowing AI agents to call DevFlow capabilities directly. + +## Platform support + +| Platform | Status | +|---|---| +| Mac Catalyst | ✅ Supported | +| iOS Simulator | ✅ Supported | +| Linux/GTK | ✅ Supported | +| Android | 🔄 In progress | +| Windows | 🔄 In progress | + +## Prerequisites + +Before setting up MauiDevFlow, ensure you have the following: + +- .NET 9 SDK or later +- A .NET MAUI project targeting a supported platform +- The .NET CLI available in your terminal + +For AI assistant integration, you also need an AI coding tool that supports MCP, such as GitHub Copilot, Claude, or Cursor. + +## Set up MauiDevFlow + +Setting up MauiDevFlow involves three steps: adding NuGet packages to your project, registering the agent in your app startup code, and installing the CLI tool. + +### Install the NuGet packages + +Add the DevFlow NuGet packages to your project file. Wrapping them in a `Debug` condition ensures they're excluded from release builds: + +```xml + + + + +``` + +> [!TIP] +> The `*-*` version pattern pulls the latest prerelease package. Pin to a specific version if you need reproducible builds. + +### Register the agent + +In your `MauiProgram.cs`, register the DevFlow agent inside a `#if DEBUG` directive so it's stripped from release builds: + +```csharp +var builder = MauiApp.CreateBuilder(); +builder.UseMauiApp(); + +#if DEBUG +builder.AddMauiDevFlowAgent(); +#endif +``` + +### Install the CLI tool + +Install the DevFlow CLI as a global .NET tool: + +```dotnetcli +dotnet tool install -g Microsoft.Maui.DevFlow.CLI +``` + +After installation, the `maui-devflow` command is available in your terminal. + +### Verify the setup + +Build and run your app in `Debug` configuration, then confirm that the agent is reachable: + +```bash +maui-devflow agent status +``` + +If the connection is successful, the command reports the agent version and the platform the app is running on. + +## Key CLI commands + +The CLI communicates with the DevFlow agent running inside your app. The following commands cover the most common workflows: + +### Agent commands + +```bash +maui-devflow agent status # Check agent connection +maui-devflow agent tree # Visual tree inspection +maui-devflow agent screenshot # Capture screenshot +maui-devflow agent interact tap # Interact with elements +maui-devflow agent logs # Application ILogger output +``` + +### Blazor WebView (CDP) commands + +```bash +maui-devflow cdp status # Blazor WebView connection status +maui-devflow cdp snapshot # DOM snapshot (useful for AI) +``` + +> [!NOTE] +> Run `maui-devflow --help` for a full list of commands and options. + +## Platform-specific setup notes + +Most platforms work without additional configuration, but some require extra steps. + +### Android + +After deploying your app to a device or emulator, set up port forwarding so the CLI can reach the agent: + +```bash +adb reverse tcp:9223 tcp:9223 +``` + +> [!IMPORTANT] +> You must run the `adb reverse` command each time you redeploy to the device or restart the emulator. + +Once port forwarding is active, verify the connection: + +```bash +maui-devflow agent status +``` + +### Mac Catalyst + +No additional configuration is required. The agent is accessible over localhost once the app is running. Launch your app from Visual Studio or the terminal and use the CLI immediately. + +### iOS Simulator + +No additional configuration is required. The agent is accessible over localhost once the app is running in the simulator. If you're running multiple simulators, the agent binds to the default port on each instance. + +## Using with AI assistants + +MauiDevFlow is designed to work with AI coding assistants such as GitHub Copilot. When an AI agent has access to DevFlow (for example, through the MCP server), it can perform the following actions against your running app. + +### Typical AI debugging workflow + +A typical AI-assisted debugging session with MauiDevFlow follows this pattern: + +1. You describe a visual or layout issue to the AI assistant (for example, "the login button is hidden behind the keyboard"). +1. The AI agent calls `maui-devflow agent tree` to inspect the visual hierarchy and identify the element. +1. The agent calls `maui-devflow agent screenshot` to see the current rendered state. +1. The agent analyzes the tree data and screenshot, identifies the root cause, and proposes a code fix. +1. After you apply the fix, the agent takes another screenshot to verify the result. + +### Inspect the visual tree + +The agent can query the full element hierarchy to understand the current UI state. This is useful when the AI needs to determine why an element isn't visible, why a layout isn't rendering as expected, or which element a user is referring to. + +### Take screenshots + +The agent can capture a screenshot of the running app to verify layout changes visually. This allows the AI to confirm that a code change produced the intended result without requiring you to describe the screen manually. + +### Read DOM snapshots for Blazor Hybrid apps + +For apps using Blazor Hybrid, the agent can capture a DOM snapshot through the CDP bridge. This gives the AI full visibility into the HTML structure rendered inside the `BlazorWebView`, which is especially helpful for diagnosing CSS or component rendering issues. + +### Check logs for runtime errors + +The agent can read `ILogger` output from the running app. This enables the AI to correlate UI issues with runtime exceptions, binding errors, or other diagnostic messages. + +### MCP server integration + +The MCP server exposes 50+ structured tools that AI agents can call directly. When configured as an MCP tool provider, DevFlow gives the AI agent the ability to autonomously inspect, interact with, and diagnose issues in your running app. This transforms the AI from a code-only assistant into one that understands your app's live runtime state. + +To use DevFlow as an MCP server, point your AI tool's MCP configuration at the DevFlow CLI. The exact configuration depends on your AI tool. For example, in a `.json` configuration file: + +```json +{ + "mcpServers": { + "maui-devflow": { + "command": "maui-devflow", + "args": ["mcp"] + } + } +} +``` + +> [!TIP] +> For best results, describe the visual problem you're seeing and let the AI agent use DevFlow to investigate. The agent can combine tree inspection, screenshots, and log reading to diagnose issues faster than manual debugging. + +## Troubleshooting + +If the CLI can't connect to the agent, verify the following: + +- The app is running in `Debug` configuration. +- The `AddMauiDevFlowAgent()` call is present in `MauiProgram.cs`. +- For Android, the `adb reverse` command has been run after deployment. +- No firewall or network policy is blocking localhost on port 9223. + +If the CLI connects but returns empty or unexpected results: + +- Ensure the page you want to inspect has fully loaded before querying the visual tree. +- For Blazor Hybrid apps, confirm that the `Microsoft.Maui.DevFlow.Blazor` package is installed and the `BlazorWebView` has finished rendering. +- Check the app's debug output for DevFlow-related error messages. + +## See also + +- [Best practices for AI-assisted .NET MAUI development](best-practices.md) +- [Configure Copilot instructions for .NET MAUI projects](copilot-instructions.md) +- [MauiDevFlow source and documentation (github.com/dotnet/maui-labs)](https://github.com/dotnet/maui-labs) diff --git a/docs/ai-development/index.md b/docs/ai-development/index.md new file mode 100644 index 0000000000..f3a7be9a0b --- /dev/null +++ b/docs/ai-development/index.md @@ -0,0 +1,62 @@ +--- +title: "AI-assisted development" +description: "Learn how to configure your .NET MAUI projects so AI coding assistants like GitHub Copilot and Claude Code can help you build cross-platform apps more effectively." +ms.topic: concept +ms.date: 03/22/2026 +no-loc: [".NET MAUI"] +--- + +# AI-assisted development for .NET MAUI + +AI coding assistants such as GitHub Copilot and Claude Code can dramatically accelerate .NET MAUI development. From generating XAML layouts and platform-specific code to diagnosing build errors and suggesting API usage, these tools reduce the time you spend on repetitive tasks and help you explore unfamiliar platform APIs faster. + +However, .NET MAUI's cross-platform nature introduces complexity that general-purpose AI models don't always handle well. A single .NET MAUI project can target up to six platforms (Android, iOS, Mac Catalyst, macOS, Windows, and Tizen), each with its own APIs, lifecycle, permissions model, and build tooling. Platform-specific code patterns (such as conditional compilation and platform-specific files), multi-targeted MSBuild configurations, and the interplay between XAML and C# all require context that an AI assistant won't have by default. + +This section covers how to configure your repository and development workflow so that AI assistants understand your .NET MAUI project structure, follow your team's conventions, and produce code that builds and runs correctly across platforms. + +## What's available + +The following tools and techniques help AI assistants work effectively with .NET MAUI projects: + +### Repository instructions + +A [repository instructions file](copilot-instructions.md) (`.github/copilot-instructions.md`) teaches AI assistants about your project's structure, build commands, target frameworks, and coding conventions. This is the single most impactful step you can take to improve AI-generated code quality. + +### Custom instruction files + +[Custom instruction files](custom-instructions.md) provide task-specific guidance that AI assistants can apply in the right context. You can create separate instruction files for iOS-specific patterns, XAML best practices, testing strategies, accessibility guidelines, and more. + +### Agent skills + +[Agent skills](agent-skills.md) are pre-built capabilities from the skills marketplace that give AI assistants specialized knowledge about .NET MAUI. The `dotnet-maui` skill, for example, provides MAUI-specific diagnostics, API guidance, and awareness of common pitfalls. + +### MauiDevFlow + +[MauiDevFlow](mauidevflow.md) is an experimental tool that connects AI assistants to your running app's visual tree. It enables AI-assisted UI debugging by letting the assistant inspect the live element hierarchy, identify layout issues, and suggest fixes based on actual runtime state. + +### Best practices + +[Best practices for AI-assisted development](best-practices.md) covers project structure patterns, code organization, and documentation habits that help AI assistants understand your codebase. Small changes — like consistent file naming and clear XML documentation comments — can significantly improve the quality of AI-generated code. + +## Quick-start checklist + +Follow these steps to make your .NET MAUI repository AI-ready: + +1. **Add repository instructions.** Create a `.github/copilot-instructions.md` file with your project overview, build commands (`dotnet build`, `dotnet run`), and target frameworks. +2. **Document platform-specific conventions.** List your file naming patterns for platform code (`.ios.cs`, `.android.cs`, `.windows.cs`) and any conditional compilation symbols you use. +3. **Install the `dotnet-maui` agent skill.** This gives AI assistants MAUI-specific diagnostics and API knowledge out of the box. +4. **Consider adding MauiDevFlow.** If you frequently debug layout or visual tree issues, this experimental tool lets AI assistants inspect your running UI. +5. **Document your testing and CI setup.** Include instructions for running unit tests, UI tests, and any platform-specific test configurations so AI assistants can help you write and debug tests. + +> [!TIP] +> Start with step 1. A well-written repository instructions file alone can eliminate most incorrect suggestions from AI assistants, such as using deprecated APIs or targeting the wrong platform. + +## See also + +- [Repository instructions for .NET MAUI](copilot-instructions.md) +- [Custom instruction files](custom-instructions.md) +- [Agent skills for .NET MAUI](agent-skills.md) +- [MauiDevFlow](mauidevflow.md) +- [Best practices for AI-assisted development](best-practices.md) +- [Microsoft.Extensions.AI overview](/dotnet/ai/ai-extensions) +- [Microsoft.Maui.Essentials.AI](../ai/index.md) diff --git a/docs/ai-development/skills.md b/docs/ai-development/skills.md new file mode 100644 index 0000000000..a6368b8729 --- /dev/null +++ b/docs/ai-development/skills.md @@ -0,0 +1,211 @@ +--- +title: ".NET Agent Skills for .NET MAUI development" +description: "Learn how to install and use .NET Agent Skills plugins to extend AI coding assistants with specialized .NET MAUI knowledge." +ms.topic: how-to +ms.date: 03/22/2026 +no-loc: [".NET MAUI"] +--- + +# .NET Agent Skills for .NET MAUI development + +Agent skills are pre-built capabilities that extend AI coding assistants with specialized .NET knowledge. Rather than relying on general-purpose AI models alone, skills provide curated, domain-specific guidance that helps your AI assistant understand .NET MAUI project structures, platform requirements, build systems, and common troubleshooting patterns. + +The [.NET Agent Skills marketplace](https://github.com/dotnet/skills) is a collection of skill plugins maintained by the .NET team and community. It provides plugins for .NET MAUI development, diagnostics, builds, testing, and more. Each plugin targets a specific area of .NET development and can be installed independently. + +## Available skills for .NET MAUI developers + +The following table lists the skill plugins most relevant to .NET MAUI development: + +| Plugin | Description | +|--------|-------------| +| `dotnet-maui` | Environment setup, diagnostics, and troubleshooting for .NET MAUI | +| `dotnet` | Core .NET development skills | +| `dotnet-msbuild` | MSBuild and build system skills | +| `dotnet-test` | Test execution and diagnostics | +| `dotnet-nuget` | NuGet package management | +| `dotnet-ai` | AI/ML integration including LLMs, RAG, and MCP | +| `dotnet-diag` | Performance profiling, debugging, and incident analysis | +| `dotnet-upgrade` | Migration and framework upgrading | + +> [!TIP] +> Start with the `dotnet-maui` and `dotnet` plugins. These two cover the most common scenarios for .NET MAUI app development. Add other plugins as your workflow requires them. + +## Install a skill plugin + +You can install skill plugins through several methods depending on your development environment. + +### GitHub Copilot CLI + +If you're using the GitHub Copilot CLI agent, add the .NET skills marketplace and then install the desired plugin: + +```bash +/plugin marketplace add dotnet-dnceng +/plugin install dotnet-maui +``` + +To verify the plugin is installed: + +```bash +/plugin list +``` + +### Visual Studio Code + +To install skill plugins in Visual Studio Code: + +1. Open the **Settings** editor (**Ctrl+,** on Windows/Linux, **Cmd+,** on macOS). +1. Search for `chat.plugins.enabled` and enable the setting. +1. Open the **Extensions** view and search for the desired skill plugin in the marketplace. +1. Select **Install** on the plugin. + +> [!NOTE] +> The `chat.plugins.enabled` setting must be turned on before skill plugins can be discovered and used by Copilot Chat in Visual Studio Code. + +### Repository-level configuration + +You can enable skill plugins for everyone who uses Copilot in a specific repository by adding a `.github/copilot/settings.json` file: + +```json +{ + "plugins": { + "dotnet-dnceng@dotnet-maui": { + "enabled": true + } + } +} +``` + +This configuration automatically enables the `dotnet-maui` skill plugin for any contributor using Copilot in the repository. Commit this file to your repository so all team members benefit from it. + +> [!IMPORTANT] +> Repository-level configuration only takes effect for contributors who have the skill plugin available in their environment. It does not install the plugin automatically. + +### Codex CLI + +If you're using the Codex CLI, install a skill plugin with the `skill-installer` command: + +```bash +skill-installer install dotnet-maui +``` + +To install multiple plugins at once: + +```bash +skill-installer install dotnet-maui dotnet-test dotnet-msbuild +``` + +## Use the dotnet-maui skill + +Once installed, the `dotnet-maui` skill plugin enhances your AI coding assistant with .NET MAUI-specific capabilities. You don't need to invoke the skill explicitly — your AI assistant uses it automatically when it recognizes a relevant context. + +### Environment setup validation + +The skill can validate your development environment, including: + +- .NET SDK version and installation status +- .NET MAUI workload installation +- Android SDK and emulator configuration +- Xcode and iOS simulator setup (macOS) +- Windows App SDK configuration + +Ask your AI assistant to check your environment: + +```text +Check if my environment is set up correctly for .NET MAUI development. +``` + +### Build error diagnostics + +When you encounter build errors, the skill provides targeted guidance based on common .NET MAUI build issues: + +```text +I'm getting error XC0000 when building for iOS. What does this mean? +``` + +The skill draws from known error patterns and platform-specific build requirements to suggest fixes. + +### Platform-specific troubleshooting + +The skill understands the differences between Android, iOS, macOS, and Windows platform targets. It can help with: + +- Platform-specific API usage and conditional compilation +- Manifest and entitlement configuration +- Signing and provisioning profiles +- Deployment and debugging on physical devices + +### Project template scaffolding + +Use the skill to generate new project structures that follow .NET MAUI best practices: + +```text +Create a new .NET MAUI app with Shell navigation and MVVM architecture. +``` + +### Migration assistance + +The skill can help with migrating from: + +- Xamarin.Forms to .NET MAUI +- Older .NET MAUI versions to newer ones +- Platform-specific legacy code to cross-platform .NET MAUI patterns + +## Combine multiple skills + +You can install multiple skill plugins to cover different aspects of your development workflow. The AI assistant draws from all installed skills as needed. + +### Example: Full-stack .NET MAUI workflow + +Install a set of complementary plugins: + +```bash +/plugin install dotnet-maui +/plugin install dotnet-test +/plugin install dotnet-msbuild +/plugin install dotnet-nuget +``` + +With these plugins active, your AI assistant can help across a typical development cycle: + +1. **Build issues** — The `dotnet-msbuild` skill helps diagnose MSBuild targets, property configurations, and build order problems. +1. **Test failures** — The `dotnet-test` skill assists with test execution, diagnosing flaky tests, and improving test coverage. +1. **Package management** — The `dotnet-nuget` skill helps resolve NuGet dependency conflicts, find appropriate packages, and manage package sources. +1. **App-specific issues** — The `dotnet-maui` skill handles platform configuration, XAML issues, and .NET MAUI-specific patterns. + +> [!TIP] +> Skills don't conflict with each other. Install as many as are relevant to your project. The AI assistant selects the most appropriate skill based on the context of your question. + +### Example: Debugging a performance issue + +Combine `dotnet-maui` with `dotnet-diag` to troubleshoot performance problems: + +```text +My .NET MAUI app is slow to start on Android. Help me profile the startup +and identify the bottleneck. +``` + +The `dotnet-diag` skill provides profiling and tracing guidance while the `dotnet-maui` skill offers platform-specific optimization strategies. + +## Create custom skills + +Teams can create their own skill plugins to codify internal patterns, architectural decisions, and domain-specific knowledge. Custom skills are useful when your team has: + +- Established coding conventions specific to your .NET MAUI projects +- Internal libraries or frameworks that require specialized guidance +- Domain-specific patterns that general-purpose skills don't cover + +To get started with creating a custom skill, see the [contributing guide in the .NET Skills repository](https://github.com/dotnet/skills/blob/main/CONTRIBUTING.md). + +A custom skill plugin typically includes: + +- A skill manifest that describes the plugin's capabilities +- Prompt instructions that guide the AI assistant's behavior +- Optional tools or scripts that the AI assistant can invoke + +> [!NOTE] +> Custom skills follow the same plugin format as the official .NET skills. You can distribute them through your organization's internal registries or through the public marketplace. + +## See also + +- [Use Copilot instructions for .NET MAUI](copilot-instructions.md) +- [AI-assisted development workflow](devflow.md) +- [.NET Agent Skills marketplace (GitHub)](https://github.com/dotnet/skills) From 1d18b25f118dbbd005ec45b2b1a6419d2ca14a38 Mon Sep 17 00:00:00 2001 From: Gerald Versluis Date: Sun, 22 Mar 2026 22:02:06 +0100 Subject: [PATCH 2/8] Apply round 1 review fixes across all 6 guides MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes from 6 personas (junior dev, senior architect, tech editor, Xamarin migrator, DevOps engineer, OSS contributor): - Fix broken cross-links (agent-skills.md → skills.md, etc.) - Add security notes for DevFlow (dev-only, port exposure) - Clarify .ios.cs/.maccatalyst.cs Mac Catalyst overlap with WARNING - Add contributor guidance (read AGENTS.md before PRing) - Add Xamarin.Forms migration subsection - Fix nested code blocks, TFM consistency notes - Standardize terminology to 'AI coding assistant' - Add CI/enterprise considerations throughout Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/ai-development/best-practices.md | 34 +++++++++++++++---- docs/ai-development/copilot-instructions.md | 36 +++++++++++++++++---- docs/ai-development/custom-instructions.md | 21 +++++++++--- docs/ai-development/devflow.md | 32 ++++++++++++++++-- docs/ai-development/index.md | 33 ++++++++++--------- docs/ai-development/skills.md | 26 +++++++++++++-- 6 files changed, 144 insertions(+), 38 deletions(-) diff --git a/docs/ai-development/best-practices.md b/docs/ai-development/best-practices.md index adf33faaf1..0da51ece83 100644 --- a/docs/ai-development/best-practices.md +++ b/docs/ai-development/best-practices.md @@ -64,10 +64,18 @@ Services/ └── DeviceService.windows.cs # Windows implementation ``` -The .NET MAUI build system automatically compiles `.android.cs` files only for Android, `.ios.cs` files only for iOS, and so on. +The .NET MAUI build system automatically compiles `.android.cs` files only for Android, `.windows.cs` files only for Windows, and so on. > [!WARNING] -> The `.ios.cs` and `.maccatalyst.cs` files compile independently — they do **not** share code. AI assistants frequently assume that iOS code also runs on Mac Catalyst because both use Apple frameworks. If your iOS and Mac Catalyst implementations are identical, you must duplicate the code in both files or use a shared base class. +> **Mac Catalyst compilation overlap:** When you build for Mac Catalyst, **both** `.ios.cs` and `.maccatalyst.cs` files are compiled into the output. There is no precedence mechanism — if both files define the same type or method, you get a compiler error. AI assistants frequently get this wrong by assuming `.ios.cs` files are ignored on Mac Catalyst or that one overrides the other. +> +> If your iOS and Mac Catalyst implementations are identical, choose **one** approach: +> +> - Use only `.maccatalyst.cs` and `.ios.cs` with `#if` guards inside, **or** +> - Use a shared base class that both platform files inherit from, **or** +> - Use conditional compilation (`#if IOS` / `#if MACCATALYST`) in a single shared file instead of platform-suffixed files. +> +> **Do not** place duplicate implementations in both `.ios.cs` and `.maccatalyst.cs` — this causes duplicate type or member definition errors at build time. ### Partial classes with platform implementations @@ -157,7 +165,7 @@ AI assistants read XML documentation comments to understand what a method does, /// their last-modified timestamp. /// /// The number of records synchronized. -/// +/// /// Thrown when the device is offline or the API is unreachable. /// public async Task SyncDataAsync(bool force = false) @@ -171,6 +179,9 @@ public async Task SyncDataAsync(bool force = false) Include a `README.md` at the repository root with: - **Build instructions** for each platform (`dotnet build -f net10.0-android`, `dotnet build -f net10.0-ios`) + +> [!NOTE] +> The examples in this article use `net10.0-*` target framework monikers. Substitute your project's target .NET version (for example, `net9.0-android`, `net9.0-ios`) wherever you see a TFM in build commands or project configuration. - **Architecture overview** describing the patterns used (MVVM, dependency injection, messaging) - **Key dependencies** and their purpose - **Platform-specific setup** requirements (Xcode version, Android SDK levels, Windows SDK) @@ -232,7 +243,7 @@ private static string CachePath => The .NET trimmer removes code that appears unused at build time. Types accessed only through reflection — such as dependency injection registrations or XAML type references — can be trimmed away: ```xml - + @@ -279,6 +290,9 @@ Not all XAML changes apply through Hot Reload. These changes require a full rebu AI assistants need to know how to build and test your project for each platform. Document these details in your `README.md` or repository instructions file. +> [!TIP] +> Codify your build and test commands in a CI pipeline (such as GitHub Actions or Azure Pipelines) so that every pull request is validated automatically. AI assistants can also reference CI workflow files to understand which platforms and configurations your project supports. + ### Build commands Provide explicit build commands for each target framework: @@ -346,6 +360,9 @@ Use `Directory.Packages.props` to centralize NuGet package versions across your Some NuGet packages behave differently per platform or are only available on certain platforms. Document these in your instructions: +> [!NOTE] +> If your organization uses private or internal NuGet feeds, include a `NuGet.config` file at the solution root with the feed URLs. This ensures AI assistants can resolve all package references and that `dotnet restore` works without additional setup. See [NuGet.config reference](/nuget/reference/nuget-config-file) for details. + ```markdown ## Key packages - **CommunityToolkit.Maui** — cross-platform, but MediaElement @@ -360,6 +377,9 @@ Some NuGet packages behave differently per platform or are only available on cer AI assistants read `.editorconfig` files and use them to match your code style. Include one in your repository root: +> [!NOTE] +> Most AI coding assistants — including GitHub Copilot — automatically detect and follow `.editorconfig` rules when generating code. This makes `.editorconfig` one of the most effective ways to enforce consistent formatting across both human-written and AI-generated code without additional prompting. + ```ini [*.cs] indent_style = space @@ -392,6 +412,6 @@ indent_size = 4 ## See also -- [Repository instructions for .NET MAUI](copilot-instructions.md) -- [Custom instruction files](custom-instructions.md) -- [.NET Agent Skills for .NET MAUI](skills.md) +- [Write a copilot-instructions.md file for .NET MAUI projects](copilot-instructions.md) +- [Custom instruction files and AGENTS.md](custom-instructions.md) +- [.NET Agent Skills for .NET MAUI development](skills.md) diff --git a/docs/ai-development/copilot-instructions.md b/docs/ai-development/copilot-instructions.md index cc84b82fdb..e24b1b2677 100644 --- a/docs/ai-development/copilot-instructions.md +++ b/docs/ai-development/copilot-instructions.md @@ -82,7 +82,10 @@ Native MAUI pages are used for platform integration only. ``` > [!NOTE] -> If your project uses a specific Windows SDK version other than `10.0.19041.0`, update the TFM accordingly. Check your `.csproj` file for the exact `TargetFrameworks` value. +> Replace `net9.0` in the examples above with your target .NET version (for example, `net10.0`). Copilot reads your `.github/copilot-instructions.md` file automatically in Visual Studio Code, Visual Studio, and the GitHub Copilot CLI — no manual configuration is required. + +> [!NOTE] +> The Windows TFM requires a Windows SDK version suffix (for example, `net9.0-windows10.0.19041.0`). If your project targets a different SDK version, update the TFM to match. Check your `.csproj` file's `TargetFrameworks` value for the exact version. ### Platform-specific code organization @@ -118,14 +121,14 @@ Use these preprocessor directives for platform-specific code in shared files: - `#if IOS || MACCATALYST` — Both Apple mobile platforms ``` -> [!IMPORTANT] -> The `.ios.cs` and Mac Catalyst double-compilation behavior is the single most common source of AI-generated build errors in .NET MAUI projects. Always include this information in your instructions file. +> [!WARNING] +> Files ending in `.ios.cs` compile for **both** iOS **and** Mac Catalyst targets. Files ending in `.maccatalyst.cs` compile **only** for Mac Catalyst. This means that when you build for Mac Catalyst, both `.ios.cs` and `.maccatalyst.cs` files are compiled — there is no precedence mechanism that picks one over the other. If both files define the same partial class members, you get duplicate-definition compilation errors on Mac Catalyst. This is the single most common source of AI-generated build errors in .NET MAUI projects. Always include this information in your instructions file. ### Project structure Document your directory layout so Copilot understands where to place new files: -```markdown +````markdown ## Project Structure ``` @@ -146,7 +149,7 @@ src/MyApp/ │ └── Styles/ — XAML resource dictionaries └── Platforms/ — Platform-specific code ``` -``` +```` ### Testing patterns @@ -219,6 +222,25 @@ Xamarin.Forms custom renderers. When customizing native controls: `Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping(...)` ``` +### Migrating from Xamarin.Forms + +If your project was migrated from Xamarin.Forms, document migration-specific constraints in your instructions file so AI assistants don't suggest legacy patterns: + +```markdown +## Migration Constraints (Xamarin.Forms to .NET MAUI) + +This project was migrated from Xamarin.Forms. Do NOT use or suggest: +- Custom renderers (use handlers instead) +- `Device.RuntimePlatform` checks (use `DeviceInfo.Platform` or conditional compilation) +- `DependencyService` (use Microsoft.Extensions.DependencyInjection) +- `MessagingCenter` (use WeakReferenceMessenger from CommunityToolkit.Mvvm) + +### Handlers vs. renderers quick reference +- Before (Xamarin.Forms): `[assembly: ExportRenderer(...)]` + subclass `ViewRenderer` +- After (.NET MAUI): Configure handler mappings in `MauiProgram.cs`: + `Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) => { ... });` +``` + ### App entry point ```markdown @@ -356,6 +378,6 @@ Do not create both `.ios.cs` and `.maccatalyst.cs` for the same partial class. ## See also -- [Create custom instructions for GitHub Copilot](custom-instructions.md) +- [Custom instruction files and AGENTS.md](custom-instructions.md) - [Best practices for AI-assisted .NET MAUI development](best-practices.md) -- [Use Copilot skills with .NET MAUI](skills.md) +- [.NET Agent Skills for .NET MAUI development](skills.md) diff --git a/docs/ai-development/custom-instructions.md b/docs/ai-development/custom-instructions.md index daf437129b..0d176867ad 100644 --- a/docs/ai-development/custom-instructions.md +++ b/docs/ai-development/custom-instructions.md @@ -8,7 +8,7 @@ no-loc: [".NET MAUI"] # Custom instruction files and AGENTS.md -While `copilot-instructions.md` provides project-wide context, custom instruction files let you provide focused guidance for specific tasks or file types. These files live in `.github/instructions/` and are loaded automatically based on file glob patterns. For project-wide setup, see [Custom instructions for GitHub Copilot](copilot-instructions.md). +While `copilot-instructions.md` provides project-wide context, custom instruction files let you provide focused guidance for specific tasks or file types. These files live in `.github/instructions/` and are loaded automatically based on file glob patterns. When you open or edit a file in VS Code or work with files through GitHub Copilot CLI, any instruction file whose `applyTo` glob matches is automatically included in the AI context—no manual configuration required. For project-wide setup, see [Write a copilot-instructions.md file for .NET MAUI projects](copilot-instructions.md). This article covers how to create task-specific instruction files and how to use `AGENTS.md` for repository-level agent policies. @@ -37,7 +37,13 @@ applyTo: "**/*.xaml" Your instructions here in Markdown format. ``` -The `applyTo` field accepts comma-separated glob patterns to match multiple file types or directories. +The `applyTo` field accepts comma-separated glob patterns to match multiple file types or directories: + +```markdown +--- +applyTo: "**/*.xaml,**/*.xaml.cs,**/Resources/Styles/**" +--- +``` > [!TIP] > Keep each instruction file focused on a single concern. Multiple small files are easier to maintain than one large file covering everything. @@ -46,6 +52,9 @@ The `applyTo` field accepts comma-separated glob patterns to match multiple file The following examples show instruction files for common .NET MAUI development scenarios. Use them as starting points and adapt them to your project's conventions. +> [!TIP] +> If you're contributing to a project, skim the `.github/instructions/` folder for any `*.instructions.md` files whose `applyTo` patterns match the files you're editing. These files describe the conventions the AI assistant follows and can help you align your changes with the project's expectations. + ### iOS and Mac Catalyst safe area handling Create `.github/instructions/safe-area-ios.instructions.md` to provide guidance when working on iOS or Mac Catalyst platform code: @@ -174,7 +183,7 @@ applyTo: "**/Platforms/Android/**,**/*.android.cs" ## AGENTS.md -`AGENTS.md` is a file placed at the root of your repository that provides high-level instructions for AI agents performing autonomous workflows. While `copilot-instructions.md` is optimized for interactive coding assistance, `AGENTS.md` targets agents that work independently, such as those that create pull requests, run builds, or perform multi-step tasks. +`AGENTS.md` is a file placed at the root of your repository that provides high-level instructions for AI agents performing autonomous workflows. While `copilot-instructions.md` is optimized for interactive coding assistance, `AGENTS.md` targets agents that work independently, such as those that create pull requests, run builds, or perform multi-step tasks. For example, an AI agent might clone your repository, run `dotnet build` and `dotnet test`, and leave a PR comment summarizing any failures—all guided by the policies in `AGENTS.md`. ### When to use AGENTS.md @@ -216,6 +225,10 @@ Use `AGENTS.md` to define repository-wide policies that autonomous agents should > [!NOTE] > `AGENTS.md` and `copilot-instructions.md` are complementary. Use both in your project — `copilot-instructions.md` for interactive coding context and `AGENTS.md` for autonomous agent policies. +### For contributors + +If you're contributing to an open-source project, read the repository's `AGENTS.md` before opening a pull request. It describes the conventions and quality checks that AI agents enforce during PR reviews, such as required CI checks, commit message formats, and code standards. Understanding these policies helps you avoid automated review feedback and ensures your PR aligns with the project's workflow from the start. + ## When to use which file Use the following table to decide where to put your AI guidance: @@ -243,5 +256,5 @@ Follow these practices to get the most value from your instruction files: ## See also -- [Custom instructions for GitHub Copilot](copilot-instructions.md) +- [Write a copilot-instructions.md file for .NET MAUI projects](copilot-instructions.md) - [Best practices for AI-assisted .NET MAUI development](best-practices.md) diff --git a/docs/ai-development/devflow.md b/docs/ai-development/devflow.md index 3282112d01..f990caf49d 100644 --- a/docs/ai-development/devflow.md +++ b/docs/ai-development/devflow.md @@ -13,6 +13,23 @@ MauiDevFlow is an experimental toolkit from maui-labs that provides an HTTP API > [!WARNING] > MauiDevFlow is experimental and its APIs may change without notice. The source is available at [github.com/dotnet/maui-labs](https://github.com/dotnet/maui-labs). +> [!IMPORTANT] +> MauiDevFlow is intended for local development and debugging only. Never include DevFlow packages in production builds. The `#if DEBUG` guard and the `Condition="'$(Configuration)' == 'Debug'"` in the project file ensure DevFlow is excluded from release builds. + +## Who should use MauiDevFlow + +MauiDevFlow is an optional, advanced tool. Consider using it when: + +- You're doing **heavy UI debugging** — diagnosing layout problems, clipped elements, or unexpected rendering. +- You're working with **complex layouts** where the visual tree is deeply nested and hard to reason about from code alone. +- You're building **Blazor Hybrid** apps and need to inspect the WebView DOM alongside the native visual tree. +- Standard tools like **XAML Hot Reload** and **Live Visual Tree** aren't providing enough visibility into the issue. + +If your debugging needs are met by the built-in Visual Studio tools, you don't need MauiDevFlow. It's designed for scenarios where deeper, programmatic access to the running app's UI state is required. + +> [!NOTE] +> MauiDevFlow is strictly for interactive debugging during development. It's not designed for automated CI/CD test runs or headless environments. + ## What MauiDevFlow provides MauiDevFlow exposes a rich set of capabilities for inspecting and interacting with a running .NET MAUI app: @@ -78,7 +95,7 @@ builder.AddMauiDevFlowAgent(); ### Install the CLI tool -Install the DevFlow CLI as a global .NET tool: +Install the DevFlow CLI as a global .NET tool. The `-g` flag installs the tool globally, making it available from any directory in your terminal rather than only within a specific project: ```dotnetcli dotnet tool install -g Microsoft.Maui.DevFlow.CLI @@ -94,6 +111,15 @@ Build and run your app in `Debug` configuration, then confirm that the agent is maui-devflow agent status ``` +A successful connection produces output similar to: + +``` +✅ Agent is running + Version: 1.0.0-preview.3 + Platform: maccatalyst + App: com.companyname.myapp +``` + If the connection is successful, the command reports the agent version and the platform the app is running on. ## Key CLI commands @@ -183,6 +209,8 @@ The agent can read `ILogger` output from the running app. This enables the AI to The MCP server exposes 50+ structured tools that AI agents can call directly. When configured as an MCP tool provider, DevFlow gives the AI agent the ability to autonomously inspect, interact with, and diagnose issues in your running app. This transforms the AI from a code-only assistant into one that understands your app's live runtime state. +MCP is supported by a growing number of AI coding tools, including **GitHub Copilot** (in VS Code, Visual Studio, and the CLI), **Claude Code**, **Cursor**, and **Windsurf**. Any AI tool that supports the [Model Context Protocol](https://modelcontextprotocol.io) specification can use DevFlow as a tool provider. + To use DevFlow as an MCP server, point your AI tool's MCP configuration at the DevFlow CLI. The exact configuration depends on your AI tool. For example, in a `.json` configuration file: ```json @@ -217,5 +245,5 @@ If the CLI connects but returns empty or unexpected results: ## See also - [Best practices for AI-assisted .NET MAUI development](best-practices.md) -- [Configure Copilot instructions for .NET MAUI projects](copilot-instructions.md) +- [Write a copilot-instructions.md file for .NET MAUI projects](copilot-instructions.md) - [MauiDevFlow source and documentation (github.com/dotnet/maui-labs)](https://github.com/dotnet/maui-labs) diff --git a/docs/ai-development/index.md b/docs/ai-development/index.md index f3a7be9a0b..fba96016dd 100644 --- a/docs/ai-development/index.md +++ b/docs/ai-development/index.md @@ -8,35 +8,37 @@ no-loc: [".NET MAUI"] # AI-assisted development for .NET MAUI +AI coding assistants are tools that integrate directly into your development environment — GitHub Copilot in Visual Studio and Visual Studio Code, Claude Code in the terminal, and similar tools — to suggest code, answer questions, and automate repetitive tasks using large language models. They can understand natural-language prompts alongside your code context to generate, refactor, and debug code in real time. + AI coding assistants such as GitHub Copilot and Claude Code can dramatically accelerate .NET MAUI development. From generating XAML layouts and platform-specific code to diagnosing build errors and suggesting API usage, these tools reduce the time you spend on repetitive tasks and help you explore unfamiliar platform APIs faster. -However, .NET MAUI's cross-platform nature introduces complexity that general-purpose AI models don't always handle well. A single .NET MAUI project can target up to six platforms (Android, iOS, Mac Catalyst, macOS, Windows, and Tizen), each with its own APIs, lifecycle, permissions model, and build tooling. Platform-specific code patterns (such as conditional compilation and platform-specific files), multi-targeted MSBuild configurations, and the interplay between XAML and C# all require context that an AI assistant won't have by default. +However, .NET MAUI's cross-platform nature introduces complexity that general-purpose AI coding assistants don't always handle well. A single .NET MAUI project can target up to six platforms (Android, iOS, Mac Catalyst, macOS, Windows, and Tizen), each with its own APIs, lifecycle, permissions model, and build tooling. Platform-specific code patterns (such as conditional compilation and platform-specific files), multi-targeted MSBuild configurations, and the interplay between XAML and C# all require context that an AI coding assistant won't have by default. -This section covers how to configure your repository and development workflow so that AI assistants understand your .NET MAUI project structure, follow your team's conventions, and produce code that builds and runs correctly across platforms. +This section covers how to configure your repository and development workflow so that AI coding assistants understand your .NET MAUI project structure, follow your team's conventions, and produce code that builds and runs correctly across platforms. ## What's available -The following tools and techniques help AI assistants work effectively with .NET MAUI projects: +The following tools and techniques help AI coding assistants work effectively with .NET MAUI projects: ### Repository instructions -A [repository instructions file](copilot-instructions.md) (`.github/copilot-instructions.md`) teaches AI assistants about your project's structure, build commands, target frameworks, and coding conventions. This is the single most impactful step you can take to improve AI-generated code quality. +A [repository instructions file](copilot-instructions.md) (`.github/copilot-instructions.md`) teaches AI coding assistants about your project's structure, build commands, target frameworks, and coding conventions. This is the single most impactful step you can take to improve AI-generated code quality. ### Custom instruction files -[Custom instruction files](custom-instructions.md) provide task-specific guidance that AI assistants can apply in the right context. You can create separate instruction files for iOS-specific patterns, XAML best practices, testing strategies, accessibility guidelines, and more. +[Custom instruction files](custom-instructions.md) provide task-specific guidance that AI coding assistants can apply in the right context. You can create separate instruction files for iOS-specific patterns, XAML best practices, testing strategies, accessibility guidelines, and more. ### Agent skills -[Agent skills](agent-skills.md) are pre-built capabilities from the skills marketplace that give AI assistants specialized knowledge about .NET MAUI. The `dotnet-maui` skill, for example, provides MAUI-specific diagnostics, API guidance, and awareness of common pitfalls. +[Agent skills](skills.md) are pre-built capabilities from the skills marketplace that give AI coding assistants specialized knowledge about .NET MAUI. The `dotnet-maui` skill, for example, provides MAUI-specific diagnostics, API guidance, and awareness of common pitfalls. ### MauiDevFlow -[MauiDevFlow](mauidevflow.md) is an experimental tool that connects AI assistants to your running app's visual tree. It enables AI-assisted UI debugging by letting the assistant inspect the live element hierarchy, identify layout issues, and suggest fixes based on actual runtime state. +[MauiDevFlow](devflow.md) is an experimental tool that connects AI coding assistants to your running app's visual tree. It enables AI-assisted UI debugging by letting the assistant inspect the live element hierarchy, identify layout issues, and suggest fixes based on actual runtime state. ### Best practices -[Best practices for AI-assisted development](best-practices.md) covers project structure patterns, code organization, and documentation habits that help AI assistants understand your codebase. Small changes — like consistent file naming and clear XML documentation comments — can significantly improve the quality of AI-generated code. +[Best practices for AI-assisted development](best-practices.md) covers project structure patterns, code organization, and documentation habits that help AI coding assistants understand your codebase. Small changes — like consistent file naming and clear XML documentation comments — can significantly improve the quality of AI-generated code. ## Quick-start checklist @@ -44,19 +46,20 @@ Follow these steps to make your .NET MAUI repository AI-ready: 1. **Add repository instructions.** Create a `.github/copilot-instructions.md` file with your project overview, build commands (`dotnet build`, `dotnet run`), and target frameworks. 2. **Document platform-specific conventions.** List your file naming patterns for platform code (`.ios.cs`, `.android.cs`, `.windows.cs`) and any conditional compilation symbols you use. -3. **Install the `dotnet-maui` agent skill.** This gives AI assistants MAUI-specific diagnostics and API knowledge out of the box. -4. **Consider adding MauiDevFlow.** If you frequently debug layout or visual tree issues, this experimental tool lets AI assistants inspect your running UI. -5. **Document your testing and CI setup.** Include instructions for running unit tests, UI tests, and any platform-specific test configurations so AI assistants can help you write and debug tests. +3. **Install the `dotnet-maui` agent skill.** This gives AI coding assistants MAUI-specific diagnostics and API knowledge out of the box. +4. **Consider adding MauiDevFlow (experimental).** If you frequently debug layout or visual tree issues, this tool lets AI coding assistants inspect your running UI. +5. **Document your testing and CI setup.** Include instructions for running unit tests, UI tests, and any platform-specific test configurations so AI coding assistants can help you write and debug tests. +6. **Read existing project conventions.** When contributing to an existing repo, first read its `.github/copilot-instructions.md` and any `AGENTS.md` file to understand the project's conventions. > [!TIP] -> Start with step 1. A well-written repository instructions file alone can eliminate most incorrect suggestions from AI assistants, such as using deprecated APIs or targeting the wrong platform. +> Start with step 1. A well-written repository instructions file alone can eliminate most incorrect suggestions from AI coding assistants, such as using deprecated APIs or targeting the wrong platform. ## See also - [Repository instructions for .NET MAUI](copilot-instructions.md) - [Custom instruction files](custom-instructions.md) -- [Agent skills for .NET MAUI](agent-skills.md) -- [MauiDevFlow](mauidevflow.md) +- [Agent skills for .NET MAUI](skills.md) +- [MauiDevFlow](devflow.md) - [Best practices for AI-assisted development](best-practices.md) - [Microsoft.Extensions.AI overview](/dotnet/ai/ai-extensions) -- [Microsoft.Maui.Essentials.AI](../ai/index.md) +- [On-device AI capabilities](../ai/index.md) diff --git a/docs/ai-development/skills.md b/docs/ai-development/skills.md index a6368b8729..9ebf7001fd 100644 --- a/docs/ai-development/skills.md +++ b/docs/ai-development/skills.md @@ -43,6 +43,9 @@ If you're using the GitHub Copilot CLI agent, add the .NET skills marketplace an /plugin install dotnet-maui ``` +> [!NOTE] +> `dotnet-dnceng` is the marketplace organization name that hosts the official .NET skill plugins. Adding it registers the source so you can install individual plugins like `dotnet-maui` by name. + To verify the plugin is installed: ```bash @@ -78,7 +81,10 @@ You can enable skill plugins for everyone who uses Copilot in a specific reposit This configuration automatically enables the `dotnet-maui` skill plugin for any contributor using Copilot in the repository. Commit this file to your repository so all team members benefit from it. > [!IMPORTANT] -> Repository-level configuration only takes effect for contributors who have the skill plugin available in their environment. It does not install the plugin automatically. +> Repository-level configuration only *enables* a plugin — it does not install it automatically. Contributors must install the plugin in their own environment before it takes effect. Pair this configuration with onboarding documentation (such as a `README.md` or `CONTRIBUTING.md` setup guide) that lists the required plugins and installation steps. + +> [!TIP] +> When contributing to an open-source repository, check whether maintainers recommend specific skills — for example in an `AGENTS.md` file or contributing guide — and install them to match the expected development environment. ### Codex CLI @@ -124,6 +130,16 @@ I'm getting error XC0000 when building for iOS. What does this mean? The skill draws from known error patterns and platform-specific build requirements to suggest fixes. +#### Example: Diagnosing an Android build failure + +A common scenario is an Android build that fails without a clear error message. Ask your AI assistant: + +```text +Why is my Android build failing? +``` + +With the `dotnet-maui` skill active, the assistant can check for missing .NET workloads, verify your Android SDK version meets the project's target, confirm the Android emulator is configured correctly, and suggest the specific `dotnet workload install` or SDK manager commands needed to fix the issue. Without the skill, the assistant would only offer generic troubleshooting advice. + ### Platform-specific troubleshooting The skill understands the differences between Android, iOS, macOS, and Windows platform targets. It can help with: @@ -174,6 +190,10 @@ With these plugins active, your AI assistant can help across a typical developme > [!TIP] > Skills don't conflict with each other. Install as many as are relevant to your project. The AI assistant selects the most appropriate skill based on the context of your question. +#### Team standardization + +For team projects, consider documenting your baseline set of plugins in a `CONTRIBUTING.md` or onboarding guide. This ensures every team member has a consistent AI-assisted development experience and avoids gaps when different developers have different plugins installed. + ### Example: Debugging a performance issue Combine `dotnet-maui` with `dotnet-diag` to troubleshoot performance problems: @@ -206,6 +226,6 @@ A custom skill plugin typically includes: ## See also -- [Use Copilot instructions for .NET MAUI](copilot-instructions.md) -- [AI-assisted development workflow](devflow.md) +- [Write a copilot-instructions.md file for .NET MAUI projects](copilot-instructions.md) +- [AI-assisted UI debugging with MauiDevFlow](devflow.md) - [.NET Agent Skills marketplace (GitHub)](https://github.com/dotnet/skills) From 3f1949c7a578d75a4cb4aeb48719477fec509700 Mon Sep 17 00:00:00 2001 From: Gerald Versluis Date: Sun, 22 Mar 2026 22:07:08 +0100 Subject: [PATCH 3/8] Apply round 2 review fixes Fixes from iOS dev, tech writer, AI engineer, principal engineer, accessibility personas: - Add .NET explanations for Swift/iOS newcomers (partial classes, TFMs, DI) - Add screen-reader text descriptions before ASCII art structures - Replace emoji in code with plain text for accessibility - Add text status column to platform support table - Consolidate excessive callouts in devflow.md - Add MCP tool categories and Xcode/DevTools comparison - Add 'How skills complement instruction files' section - Reduce cross-page redundancy with links - Recommend devcontainers for team-wide skill installation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/ai-development/best-practices.md | 37 +++++++++++---------- docs/ai-development/copilot-instructions.md | 6 ++-- docs/ai-development/custom-instructions.md | 4 +-- docs/ai-development/devflow.md | 19 ++++++++--- docs/ai-development/skills.md | 13 ++++++-- 5 files changed, 50 insertions(+), 29 deletions(-) diff --git a/docs/ai-development/best-practices.md b/docs/ai-development/best-practices.md index 0da51ece83..e7095c97b6 100644 --- a/docs/ai-development/best-practices.md +++ b/docs/ai-development/best-practices.md @@ -12,7 +12,9 @@ AI coding assistants work best when your project follows clear, consistent patte ## Project structure -A predictable folder layout helps AI assistants locate relevant code and understand the relationships between components. The standard .NET MAUI template provides a solid starting point: +A predictable folder layout helps AI assistants locate relevant code and understand the relationships between components. The standard .NET MAUI template provides a solid starting point. + +The following folder structure shows a typical .NET MAUI project with platform-specific folders under `Platforms/`, shared resources, and separated concerns: ```text MyApp/ @@ -67,19 +69,17 @@ Services/ The .NET MAUI build system automatically compiles `.android.cs` files only for Android, `.windows.cs` files only for Windows, and so on. > [!WARNING] -> **Mac Catalyst compilation overlap:** When you build for Mac Catalyst, **both** `.ios.cs` and `.maccatalyst.cs` files are compiled into the output. There is no precedence mechanism — if both files define the same type or method, you get a compiler error. AI assistants frequently get this wrong by assuming `.ios.cs` files are ignored on Mac Catalyst or that one overrides the other. -> -> If your iOS and Mac Catalyst implementations are identical, choose **one** approach: -> -> - Use only `.maccatalyst.cs` and `.ios.cs` with `#if` guards inside, **or** -> - Use a shared base class that both platform files inherit from, **or** -> - Use conditional compilation (`#if IOS` / `#if MACCATALYST`) in a single shared file instead of platform-suffixed files. -> -> **Do not** place duplicate implementations in both `.ios.cs` and `.maccatalyst.cs` — this causes duplicate type or member definition errors at build time. +> **Mac Catalyst compilation overlap:** When you build for Mac Catalyst, **both** `.ios.cs` and `.maccatalyst.cs` files are compiled into the output. There is no precedence mechanism — if both files define the same type or method, you get a compiler error. **Do not** place duplicate implementations in both files. + +If your iOS and Mac Catalyst implementations are identical, choose **one** of these resolution strategies: + +- Use only `.maccatalyst.cs` and `.ios.cs` with `#if` guards inside. +- Use a shared base class that both platform files inherit from. +- Use conditional compilation (`#if IOS` / `#if MACCATALYST`) in a single shared file instead of platform-suffixed files. ### Partial classes with platform implementations -Partial classes let you split a type across shared and platform-specific files: +Unlike Swift extensions, C# partial classes are a single class definition split across multiple files that the compiler merges at compile time. Partial classes let you split a type across shared and platform-specific files: ```csharp // Services/DeviceService.cs (shared) @@ -119,12 +119,15 @@ public string GetDefaultCacheSize() } ``` +> [!NOTE] +> These compilation symbols (`ANDROID`, `IOS`, `MACCATALYST`, `WINDOWS`) are defined automatically by the .NET MAUI build system based on your target framework. You don't need to configure them manually. + > [!NOTE] > Prefer partial classes or platform-specific files over `#if` directives when the platform-specific code is more than a few lines. Large blocks of conditional compilation are harder for AI assistants to reason about because they must mentally track which branches are active for each platform. ### Dependency injection for platform services -Register platform-specific implementations in `MauiProgram.cs`: +Dependency injection (DI) is a design pattern where services are provided to classes through their constructors rather than being created directly. Register platform-specific implementations in `MauiProgram.cs`: ```csharp public static MauiApp CreateMauiApp() @@ -228,11 +231,11 @@ These are mistakes AI assistants frequently make with .NET MAUI code. Document t Platform APIs like `FileSystem.AppDataDirectory` aren't available during type initialization. Static readonly fields are evaluated at type load time, which can happen before the .NET MAUI platform is initialized: ```csharp -// ❌ WRONG — evaluated during type initialization, before MAUI platform is ready +// WRONG: evaluated during type initialization, before MAUI platform is ready private static readonly string CachePath = Path.Combine(FileSystem.AppDataDirectory, "cache"); -// ✅ CORRECT — lazy evaluation defers the call until first access +// CORRECT: lazy evaluation defers the call until first access private static string? _cachePath; private static string CachePath => _cachePath ??= Path.Combine(FileSystem.AppDataDirectory, "cache"); @@ -240,7 +243,7 @@ private static string CachePath => ### Linker and trimmer safety -The .NET trimmer removes code that appears unused at build time. Types accessed only through reflection — such as dependency injection registrations or XAML type references — can be trimmed away: +The .NET trimmer removes code that appears unused at build time. Types accessed only through reflection — such as dependency injection registrations or XAML type references — can be trimmed away. Add the following to your `.csproj` file (the XML-format project configuration file that defines your app's build settings, dependencies, and target frameworks in .NET): ```xml @@ -256,11 +259,11 @@ Alternatively, use the `[DynamicallyAccessedMembers]` or `[RequiresUnreferencedC On iOS, `Environment.SpecialFolder.LocalApplicationData` maps to a **cache** directory that the OS can purge at any time. For persistent data, always use the .NET MAUI file system API: ```csharp -// ❌ WRONG on iOS — this path can be purged by the OS +// WRONG on iOS: this path can be purged by the OS var path = Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData); -// ✅ CORRECT — guaranteed persistent across app launches +// CORRECT: guaranteed persistent across app launches var path = FileSystem.AppDataDirectory; ``` diff --git a/docs/ai-development/copilot-instructions.md b/docs/ai-development/copilot-instructions.md index e24b1b2677..e6158b6a2d 100644 --- a/docs/ai-development/copilot-instructions.md +++ b/docs/ai-development/copilot-instructions.md @@ -62,7 +62,7 @@ Native MAUI pages are used for platform integration only. ### Build and run commands -.NET MAUI projects use target framework monikers (TFMs) to build for specific platforms. Include the exact commands so Copilot can suggest the correct build invocation: +.NET MAUI projects use target framework monikers (TFMs) to build for specific platforms. TFMs like `net9.0-ios` tell the .NET build system which platform to target — similar to selecting a build destination in Xcode or a build variant in Android Studio. Include the exact commands so Copilot can suggest the correct build invocation: ```markdown ## Build Commands @@ -122,11 +122,11 @@ Use these preprocessor directives for platform-specific code in shared files: ``` > [!WARNING] -> Files ending in `.ios.cs` compile for **both** iOS **and** Mac Catalyst targets. Files ending in `.maccatalyst.cs` compile **only** for Mac Catalyst. This means that when you build for Mac Catalyst, both `.ios.cs` and `.maccatalyst.cs` files are compiled — there is no precedence mechanism that picks one over the other. If both files define the same partial class members, you get duplicate-definition compilation errors on Mac Catalyst. This is the single most common source of AI-generated build errors in .NET MAUI projects. Always include this information in your instructions file. +> Files ending in `.ios.cs` compile for **both** iOS **and** Mac Catalyst targets, while `.maccatalyst.cs` files compile **only** for Mac Catalyst. If both define the same partial class members, you get duplicate-definition compilation errors. This is the most common source of AI-generated build errors in .NET MAUI projects. For detailed resolution strategies, see [Best practices](best-practices.md#platform-specific-code-patterns). ### Project structure -Document your directory layout so Copilot understands where to place new files: +Document your directory layout so Copilot understands where to place new files. The following example describes a typical .NET MAUI project structure with shared app entry points, MVVM folders for models, views, and view models, platform-specific code under `Platforms/`, and resources for fonts, images, and styles: ````markdown ## Project Structure diff --git a/docs/ai-development/custom-instructions.md b/docs/ai-development/custom-instructions.md index 0d176867ad..13a85fdb80 100644 --- a/docs/ai-development/custom-instructions.md +++ b/docs/ai-development/custom-instructions.md @@ -223,7 +223,7 @@ Use `AGENTS.md` to define repository-wide policies that autonomous agents should ``` > [!NOTE] -> `AGENTS.md` and `copilot-instructions.md` are complementary. Use both in your project — `copilot-instructions.md` for interactive coding context and `AGENTS.md` for autonomous agent policies. +> `AGENTS.md` and `copilot-instructions.md` are complementary. Use both in your project — `copilot-instructions.md` for interactive coding context and `AGENTS.md` for autonomous agent policies. The `AGENTS.md` convention is supported by GitHub Copilot, Claude Code, and other AI coding assistants. ### For contributors @@ -234,7 +234,7 @@ If you're contributing to an open-source project, read the repository's `AGENTS. Use the following table to decide where to put your AI guidance: | Scenario | Recommended file | -|---|---| +|----------|------------------| | Project overview, build commands, architecture | `copilot-instructions.md` | | Platform-specific coding patterns (iOS, Android) | `.github/instructions/*.instructions.md` | | File-type guidance (XAML, tests) | `.github/instructions/*.instructions.md` | diff --git a/docs/ai-development/devflow.md b/docs/ai-development/devflow.md index f990caf49d..a6fc59ed00 100644 --- a/docs/ai-development/devflow.md +++ b/docs/ai-development/devflow.md @@ -8,13 +8,10 @@ no-loc: [".NET MAUI"] # AI-assisted UI debugging with MauiDevFlow -MauiDevFlow is an experimental toolkit from maui-labs that provides an HTTP API and CLI for visual tree inspection, element interaction, screenshots, and more in .NET MAUI apps. It's particularly powerful when combined with AI coding assistants, enabling them to inspect your running app's UI and diagnose layout and rendering issues in real time. +MauiDevFlow is an experimental toolkit from maui-labs that provides an HTTP API and CLI for visual tree inspection, element interaction, screenshots, and more in .NET MAUI apps. It's particularly powerful when combined with AI coding assistants, enabling them to inspect your running app's UI and diagnose layout and rendering issues in real time. If you're familiar with Xcode Instruments or Chrome DevTools, MauiDevFlow provides a similar level of runtime introspection for .NET MAUI apps, with the added benefit of AI agent integration through the Model Context Protocol. > [!WARNING] -> MauiDevFlow is experimental and its APIs may change without notice. The source is available at [github.com/dotnet/maui-labs](https://github.com/dotnet/maui-labs). - -> [!IMPORTANT] -> MauiDevFlow is intended for local development and debugging only. Never include DevFlow packages in production builds. The `#if DEBUG` guard and the `Condition="'$(Configuration)' == 'Debug'"` in the project file ensure DevFlow is excluded from release builds. +> MauiDevFlow is experimental and its APIs may change without notice. It is intended for local development and debugging only — never include DevFlow packages in production builds. The `#if DEBUG` guard and the `Condition="'$(Configuration)' == 'Debug'"` in the project file ensure DevFlow is excluded from release builds. The source is available at [github.com/dotnet/maui-labs](https://github.com/dotnet/maui-labs). ## Who should use MauiDevFlow @@ -209,6 +206,18 @@ The agent can read `ILogger` output from the running app. This enables the AI to The MCP server exposes 50+ structured tools that AI agents can call directly. When configured as an MCP tool provider, DevFlow gives the AI agent the ability to autonomously inspect, interact with, and diagnose issues in your running app. This transforms the AI from a code-only assistant into one that understands your app's live runtime state. +The tools are organized into the following categories: + +- **Visual tree inspection** — query elements, layout properties, binding contexts, and rendered bounds. +- **Element interaction** — tap, type text, scroll, and navigate within the running app. +- **Screenshot capture** — capture the current app state as an image for visual verification. +- **Network monitoring** — observe outgoing HTTP requests and responses. +- **Performance profiling** — collect timing data for rendering and layout passes. +- **Blazor WebView / CDP commands** — inspect the DOM, evaluate JavaScript, and debug Blazor Hybrid content. +- **Application logging** — read `ILogger` output and diagnostic messages from the running app. + +For the full tool reference including parameters and response formats, see the [MauiDevFlow documentation in the maui-labs repository](https://github.com/dotnet/maui-labs). + MCP is supported by a growing number of AI coding tools, including **GitHub Copilot** (in VS Code, Visual Studio, and the CLI), **Claude Code**, **Cursor**, and **Windsurf**. Any AI tool that supports the [Model Context Protocol](https://modelcontextprotocol.io) specification can use DevFlow as a tool provider. To use DevFlow as an MCP server, point your AI tool's MCP configuration at the DevFlow CLI. The exact configuration depends on your AI tool. For example, in a `.json` configuration file: diff --git a/docs/ai-development/skills.md b/docs/ai-development/skills.md index 9ebf7001fd..360005c0c8 100644 --- a/docs/ai-development/skills.md +++ b/docs/ai-development/skills.md @@ -81,7 +81,7 @@ You can enable skill plugins for everyone who uses Copilot in a specific reposit This configuration automatically enables the `dotnet-maui` skill plugin for any contributor using Copilot in the repository. Commit this file to your repository so all team members benefit from it. > [!IMPORTANT] -> Repository-level configuration only *enables* a plugin — it does not install it automatically. Contributors must install the plugin in their own environment before it takes effect. Pair this configuration with onboarding documentation (such as a `README.md` or `CONTRIBUTING.md` setup guide) that lists the required plugins and installation steps. +> Repository-level configuration only *enables* a plugin — it does not install it automatically. Contributors must install the plugin in their own environment before it takes effect. Pair this configuration with onboarding documentation (such as a `README.md` or `CONTRIBUTING.md` setup guide) that lists the required plugins and installation steps. For team-wide consistency, consider using [devcontainers](https://containers.dev/) or repository setup scripts (for example, a `setup.sh` or `init.ps1`) that automate plugin installation as part of the development environment setup. > [!TIP] > When contributing to an open-source repository, check whether maintainers recommend specific skills — for example in an `AGENTS.md` file or contributing guide — and install them to match the expected development environment. @@ -102,7 +102,7 @@ skill-installer install dotnet-maui dotnet-test dotnet-msbuild ## Use the dotnet-maui skill -Once installed, the `dotnet-maui` skill plugin enhances your AI coding assistant with .NET MAUI-specific capabilities. You don't need to invoke the skill explicitly — your AI assistant uses it automatically when it recognizes a relevant context. +Once installed, the `dotnet-maui` skill plugin enhances your AI coding assistant with .NET MAUI-specific capabilities. Your AI coding assistant automatically selects relevant skills based on the context of your question. You don't need to invoke skills explicitly — the assistant matches your query to available skill capabilities and activates the appropriate plugins. ### Environment setup validation @@ -224,6 +224,15 @@ A custom skill plugin typically includes: > [!NOTE] > Custom skills follow the same plugin format as the official .NET skills. You can distribute them through your organization's internal registries or through the public marketplace. +## How skills complement instruction files + +Skills and instruction files serve different roles in your AI-assisted development workflow and work best when used together: + +- **Instruction files** provide *static context* — they describe your project structure, coding conventions, architectural patterns, and platform-specific guidelines. The AI assistant reads these files to understand *how* your project is organized and *what* conventions to follow. +- **Skills** provide *dynamic capabilities* — they enable the AI assistant to perform actions like running diagnostics, analyzing build errors, scaffolding code from templates, and profiling performance. Skills give the assistant the ability to *do* things, not just know things. + +For example, an instruction file might tell the AI assistant to use compiled bindings in XAML, while the `dotnet-maui` skill enables the assistant to validate your development environment and diagnose why a build targeting iOS is failing. Together, they give the AI both the knowledge and the tools to assist effectively. + ## See also - [Write a copilot-instructions.md file for .NET MAUI projects](copilot-instructions.md) From 48573473bbf43e85d33af7b11cd0abc8fff736aa Mon Sep 17 00:00:00 2001 From: Gerald Versluis Date: Sun, 22 Mar 2026 22:12:21 +0100 Subject: [PATCH 4/8] Apply round 3 review fixes Fixes from skeptic, Blazor dev, QA bot, UX researcher, cross-platform dev personas: - Replace overselling language with measured claims - Add 'Choose your path' routing block to index - Add Blazor Hybrid subsections (copilot-instructions, best-practices, devflow) - Add template jump-link for quick access - Remove hardcoded padding values for platform-safe guidance - Simplify DevFlow port binding docs - Add CDP snapshot Blazor debugging workflow Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/ai-development/best-practices.md | 64 ++++++++++++++++++++- docs/ai-development/copilot-instructions.md | 34 +++++++++++ docs/ai-development/devflow.md | 12 +++- docs/ai-development/index.md | 21 ++++--- docs/ai-development/skills.md | 3 +- 5 files changed, 122 insertions(+), 12 deletions(-) diff --git a/docs/ai-development/best-practices.md b/docs/ai-development/best-practices.md index e7095c97b6..5c3a1b58b5 100644 --- a/docs/ai-development/best-practices.md +++ b/docs/ai-development/best-practices.md @@ -269,14 +269,17 @@ var path = FileSystem.AppDataDirectory; ### Android edge-to-edge display -Starting with .NET 10, Android apps default to edge-to-edge display with `SafeAreaEdges` set to `None`. UI elements can render behind the system status bar and navigation bar. Account for safe areas in your layouts: +Starting with .NET 10, Android apps default to edge-to-edge display with `SafeAreaEdges` set to `None`. UI elements can render behind the system status bar and navigation bar. Account for safe areas in your layouts using platform-safe approaches rather than hardcoded padding values: ```xml - - + + + ``` +On Android, use `OnPlatform` with your app's safe area logic or the platform's `fitsSystemWindows` attribute. Avoid hardcoded padding values like `Padding="0,48,0,0"` because status bar height varies across Android devices and OS versions. Instead, query the actual insets at runtime or use community toolkit helpers that calculate platform-safe margins dynamically. + ### XAML Hot Reload limitations Not all XAML changes apply through Hot Reload. These changes require a full rebuild: @@ -380,6 +383,61 @@ Some NuGet packages behave differently per platform or are only available on cer AI assistants read `.editorconfig` files and use them to match your code style. Include one in your repository root: +## Blazor Hybrid patterns + +If your app uses Blazor Hybrid, these patterns help AI assistants navigate the coexistence of native MAUI and web-based Razor content. + +### XAML and Razor coexistence + +In a Blazor Hybrid app, native MAUI pages host `BlazorWebView` controls that render Razor components. Keep these boundaries clear: + +- Use XAML pages for native platform integration (navigation, permissions, device features). +- Use Razor components for the main app UI rendered inside `BlazorWebView`. +- Don't mix XAML data bindings with Razor component parameters — they use different binding systems. +- Document which pages are native XAML and which are Blazor-hosted so AI assistants place new code in the right location. + +### `wwwroot/` organization + +Static web assets must live in `wwwroot/` at the project root: + +```text +MyApp/ +├── wwwroot/ +│ ├── index.html # Blazor host page (required, do not rename) +│ ├── css/ +│ │ └── app.css # App-level styles +│ └── js/ +│ └── interop.js # JavaScript interop functions +├── Components/ +│ ├── Layout/ +│ │ └── MainLayout.razor +│ └── Pages/ +│ └── Home.razor +└── MainPage.xaml # Native page hosting BlazorWebView +``` + +### JavaScript interop safety patterns + +JavaScript interop in Blazor Hybrid has mobile-specific considerations: + +- Always use asynchronous `IJSRuntime` methods — synchronous JS interop (`IJSInProcessRuntime`) can deadlock on mobile platforms. +- Dispose `IJSObjectReference` instances in the component's `DisposeAsync` method to avoid memory leaks. +- Guard JS interop calls with `try-catch` — WebView initialization timing varies across platforms. +- Test JS interop on all target platforms, as JavaScript engine behavior differs between Android WebView, iOS WKWebView, and Windows WebView2. + +### `BlazorWebView` configuration + +Configure the `BlazorWebView` in your XAML page and register Razor components in `MauiProgram.cs`: + +```csharp +builder.Services.AddMauiBlazorWebView(); +#if DEBUG +builder.Services.AddBlazorWebViewDeveloperTools(); +#endif +``` + +Document your `BlazorWebView` setup in your repository instructions so AI assistants know the host page location and root component configuration. + > [!NOTE] > Most AI coding assistants — including GitHub Copilot — automatically detect and follow `.editorconfig` rules when generating code. This makes `.editorconfig` one of the most effective ways to enforce consistent formatting across both human-written and AI-generated code without additional prompting. diff --git a/docs/ai-development/copilot-instructions.md b/docs/ai-development/copilot-instructions.md index e6158b6a2d..30ca03563e 100644 --- a/docs/ai-development/copilot-instructions.md +++ b/docs/ai-development/copilot-instructions.md @@ -15,6 +15,9 @@ When you provide a well-written instructions file, Copilot generates code that f > [!TIP] > The `.github/copilot-instructions.md` file is automatically loaded by GitHub Copilot in Visual Studio Code, Visual Studio, and the GitHub Copilot CLI. You don't need to reference it manually. +> [!TIP] +> Want to skip ahead? Jump to the [complete template](#template) for a ready-to-use file. + ## Create the file Create a file named `copilot-instructions.md` in the `.github` directory at the root of your repository: @@ -279,6 +282,37 @@ This app uses Shell navigation. Routes are registered in AppShell.xaml.cs: - Receive parameters with [QueryProperty] attribute or IQueryAttributable ``` +### Blazor Hybrid + +If your app uses Blazor Hybrid, document the web-specific project structure and patterns so AI assistants don't confuse Razor components with XAML views: + +```markdown +## Blazor Hybrid + +### App type +This is a .NET MAUI Blazor Hybrid app. The main UI is built with +Razor components hosted inside a BlazorWebView on native MAUI pages. + +### wwwroot folder +Static web assets live in `wwwroot/`: +- `wwwroot/index.html` — Blazor host page (do not rename) +- `wwwroot/css/` — App stylesheets +- `wwwroot/js/` — JavaScript files for interop + +### Razor components +- Components live in `Components/` (or `Pages/` for routable components) +- Use `@page "/route"` directive for routable components +- Shared layout components go in `Components/Layout/` +- Do NOT mix XAML data binding with Razor component parameters + +### JavaScript interop +- Inject `IJSRuntime` for JavaScript calls from Razor components +- Use `[JSInvokable]` for .NET methods called from JavaScript +- Always use `ValueTask` return types for JS interop methods +- Dispose `IJSObjectReference` instances in component `DisposeAsync` +- Avoid synchronous JS interop (`IJSInProcessRuntime`) on mobile platforms +``` + ## Template Use the following template as a starting point for your own `.github/copilot-instructions.md` file. Remove sections that don't apply and add details specific to your project. diff --git a/docs/ai-development/devflow.md b/docs/ai-development/devflow.md index a6fc59ed00..4cb37bc860 100644 --- a/docs/ai-development/devflow.md +++ b/docs/ai-development/devflow.md @@ -170,7 +170,7 @@ No additional configuration is required. The agent is accessible over localhost ### iOS Simulator -No additional configuration is required. The agent is accessible over localhost once the app is running in the simulator. If you're running multiple simulators, the agent binds to the default port on each instance. +No additional configuration is required. The agent is accessible over localhost once the app is running in the simulator. DevFlow's agent listens on port 9223 by default. ## Using with AI assistants @@ -198,6 +198,16 @@ The agent can capture a screenshot of the running app to verify layout changes v For apps using Blazor Hybrid, the agent can capture a DOM snapshot through the CDP bridge. This gives the AI full visibility into the HTML structure rendered inside the `BlazorWebView`, which is especially helpful for diagnosing CSS or component rendering issues. +### Blazor Hybrid debugging workflow + +When debugging Razor component rendering issues in a Blazor Hybrid app, the AI agent can combine native visual tree inspection with CDP DOM snapshots: + +1. You describe a rendering issue (for example, "my `WeatherList` Razor component shows a blank area instead of the forecast cards"). +1. The agent calls `maui-devflow agent tree` to confirm the `BlazorWebView` is present and correctly sized in the native layout. +1. The agent calls `maui-devflow cdp snapshot` to capture the DOM inside the WebView, revealing the rendered HTML and CSS state of the Razor component. +1. The agent identifies the root cause in the DOM (for example, a missing CSS class, a conditional rendering block evaluating to `false`, or a failed data binding) and proposes a fix to the `.razor` or `.css` file. +1. After you apply the fix and hot reload, the agent takes another CDP snapshot to verify the component renders correctly. + ### Check logs for runtime errors The agent can read `ILogger` output from the running app. This enables the AI to correlate UI issues with runtime exceptions, binding errors, or other diagnostic messages. diff --git a/docs/ai-development/index.md b/docs/ai-development/index.md index fba96016dd..42714e9a0a 100644 --- a/docs/ai-development/index.md +++ b/docs/ai-development/index.md @@ -10,12 +10,19 @@ no-loc: [".NET MAUI"] AI coding assistants are tools that integrate directly into your development environment — GitHub Copilot in Visual Studio and Visual Studio Code, Claude Code in the terminal, and similar tools — to suggest code, answer questions, and automate repetitive tasks using large language models. They can understand natural-language prompts alongside your code context to generate, refactor, and debug code in real time. -AI coding assistants such as GitHub Copilot and Claude Code can dramatically accelerate .NET MAUI development. From generating XAML layouts and platform-specific code to diagnosing build errors and suggesting API usage, these tools reduce the time you spend on repetitive tasks and help you explore unfamiliar platform APIs faster. +AI coding assistants such as GitHub Copilot and Claude Code can significantly improve productivity by providing context-aware code suggestions, platform-specific diagnostics, and automated debugging. From generating XAML layouts and platform-specific code to diagnosing build errors and suggesting API usage, these tools reduce the time you spend on repetitive tasks and help you explore unfamiliar platform APIs faster. However, .NET MAUI's cross-platform nature introduces complexity that general-purpose AI coding assistants don't always handle well. A single .NET MAUI project can target up to six platforms (Android, iOS, Mac Catalyst, macOS, Windows, and Tizen), each with its own APIs, lifecycle, permissions model, and build tooling. Platform-specific code patterns (such as conditional compilation and platform-specific files), multi-targeted MSBuild configurations, and the interplay between XAML and C# all require context that an AI coding assistant won't have by default. This section covers how to configure your repository and development workflow so that AI coding assistants understand your .NET MAUI project structure, follow your team's conventions, and produce code that builds and runs correctly across platforms. +## Choose your path + +- **Want better code suggestions?** → Start with [Repository instructions](copilot-instructions.md) +- **Need task-specific AI guidance?** → See [Custom instruction files](custom-instructions.md) +- **Want pre-built MAUI diagnostics?** → Install [Agent skills](skills.md) +- **Need to debug complex UI issues?** → Try [MauiDevFlow](devflow.md) (experimental) + ## What's available The following tools and techniques help AI coding assistants work effectively with .NET MAUI projects: @@ -44,12 +51,12 @@ A [repository instructions file](copilot-instructions.md) (`.github/copilot-inst Follow these steps to make your .NET MAUI repository AI-ready: -1. **Add repository instructions.** Create a `.github/copilot-instructions.md` file with your project overview, build commands (`dotnet build`, `dotnet run`), and target frameworks. -2. **Document platform-specific conventions.** List your file naming patterns for platform code (`.ios.cs`, `.android.cs`, `.windows.cs`) and any conditional compilation symbols you use. -3. **Install the `dotnet-maui` agent skill.** This gives AI coding assistants MAUI-specific diagnostics and API knowledge out of the box. -4. **Consider adding MauiDevFlow (experimental).** If you frequently debug layout or visual tree issues, this tool lets AI coding assistants inspect your running UI. -5. **Document your testing and CI setup.** Include instructions for running unit tests, UI tests, and any platform-specific test configurations so AI coding assistants can help you write and debug tests. -6. **Read existing project conventions.** When contributing to an existing repo, first read its `.github/copilot-instructions.md` and any `AGENTS.md` file to understand the project's conventions. +1. **[Add repository instructions.](copilot-instructions.md)** Create a `.github/copilot-instructions.md` file with your project overview, build commands (`dotnet build`, `dotnet run`), and target frameworks. +2. **[Document platform-specific conventions.](best-practices.md#platform-specific-code-patterns)** List your file naming patterns for platform code (`.ios.cs`, `.android.cs`, `.windows.cs`) and any conditional compilation symbols you use. +3. **[Install the `dotnet-maui` agent skill.](skills.md)** This gives AI coding assistants MAUI-specific diagnostics and API knowledge out of the box. +4. **[Consider adding MauiDevFlow (experimental).](devflow.md)** If you frequently debug layout or visual tree issues, this tool lets AI coding assistants inspect your running UI. +5. **[Document your testing and CI setup.](best-practices.md#build-and-test-configuration)** Include instructions for running unit tests, UI tests, and any platform-specific test configurations so AI coding assistants can help you write and debug tests. +6. **[Read existing project conventions.](custom-instructions.md)** When contributing to an existing repo, first read its `.github/copilot-instructions.md` and any `AGENTS.md` file to understand the project's conventions. > [!TIP] > Start with step 1. A well-written repository instructions file alone can eliminate most incorrect suggestions from AI coding assistants, such as using deprecated APIs or targeting the wrong platform. diff --git a/docs/ai-development/skills.md b/docs/ai-development/skills.md index 360005c0c8..55cbe82ee6 100644 --- a/docs/ai-development/skills.md +++ b/docs/ai-development/skills.md @@ -230,8 +230,9 @@ Skills and instruction files serve different roles in your AI-assisted developme - **Instruction files** provide *static context* — they describe your project structure, coding conventions, architectural patterns, and platform-specific guidelines. The AI assistant reads these files to understand *how* your project is organized and *what* conventions to follow. - **Skills** provide *dynamic capabilities* — they enable the AI assistant to perform actions like running diagnostics, analyzing build errors, scaffolding code from templates, and profiling performance. Skills give the assistant the ability to *do* things, not just know things. +- **[MauiDevFlow](devflow.md)** provides *runtime inspection* — it connects the AI assistant to your running app so it can query the live visual tree, capture screenshots, read DOM snapshots from Blazor WebViews, and check logs. DevFlow gives the assistant visibility into actual runtime state, which neither instruction files nor skills can provide. -For example, an instruction file might tell the AI assistant to use compiled bindings in XAML, while the `dotnet-maui` skill enables the assistant to validate your development environment and diagnose why a build targeting iOS is failing. Together, they give the AI both the knowledge and the tools to assist effectively. +For example, an instruction file might tell the AI assistant to use compiled bindings in XAML, the `dotnet-maui` skill enables the assistant to validate your development environment and diagnose why a build targeting iOS is failing, and DevFlow lets the assistant inspect your running app's visual tree to identify why a layout renders differently than expected. Together, they give the AI the context, the capabilities, and the runtime visibility to assist effectively. ## See also From f6e511398687a4c3894fe864b2affb95088b29f7 Mon Sep 17 00:00:00 2001 From: Gerald Versluis Date: Sun, 22 Mar 2026 22:19:40 +0100 Subject: [PATCH 5/8] Apply round 4 review fixes - Fix orphaned .editorconfig section in best-practices.md - Remove duplicate macOS/Mac Catalyst platform listing - Add Linux/GTK setup notes in devflow.md - Improve best-practices.md opening paragraph Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/ai-development/best-practices.md | 68 +++++++++++++-------------- docs/ai-development/devflow.md | 4 ++ docs/ai-development/index.md | 2 +- 3 files changed, 39 insertions(+), 35 deletions(-) diff --git a/docs/ai-development/best-practices.md b/docs/ai-development/best-practices.md index 5c3a1b58b5..97a1686458 100644 --- a/docs/ai-development/best-practices.md +++ b/docs/ai-development/best-practices.md @@ -8,7 +8,7 @@ no-loc: [".NET MAUI"] # Best practices for AI-assisted .NET MAUI development -AI coding assistants work best when your project follows clear, consistent patterns. The way you organize files, name classes, document APIs, and configure builds directly affects the quality of AI-generated code. This article covers practical techniques to help AI assistants understand your .NET MAUI codebase and produce correct, platform-aware code. +AI coding assistants work best when your project follows clear, consistent patterns. The way you organize files, name classes, document APIs, and configure builds directly affects the quality of AI-generated code. This article covers project structure, platform-specific code patterns, documentation practices, common pitfalls, and build and test configuration — practical techniques to help AI assistants understand your .NET MAUI codebase and produce correct, platform-aware code. ## Project structure @@ -383,6 +383,39 @@ Some NuGet packages behave differently per platform or are only available on cer AI assistants read `.editorconfig` files and use them to match your code style. Include one in your repository root: +> [!NOTE] +> Most AI coding assistants — including GitHub Copilot — automatically detect and follow `.editorconfig` rules when generating code. This makes `.editorconfig` one of the most effective ways to enforce consistent formatting across both human-written and AI-generated code without additional prompting. + +```ini +[*.cs] +indent_style = space +indent_size = 4 +charset = utf-8 + +# Naming conventions +dotnet_naming_rule.private_fields.symbols = private_fields +dotnet_naming_rule.private_fields.style = prefix_underscore +dotnet_naming_rule.private_fields.severity = suggestion + +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private + +dotnet_naming_style.prefix_underscore.capitalization = camel_case +dotnet_naming_style.prefix_underscore.required_prefix = _ + +# Code style +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_expression_bodied_methods = when_on_single_line:suggestion +csharp_prefer_braces = true:suggestion + +[*.xaml] +indent_style = space +indent_size = 4 +``` + +> [!TIP] +> If your team uses non-standard naming conventions (such as `m_` prefixes for member fields or `I` prefixes for all interfaces), document these explicitly in your `.editorconfig` and repository instructions. AI assistants default to standard .NET naming conventions and need explicit guidance to deviate. + ## Blazor Hybrid patterns If your app uses Blazor Hybrid, these patterns help AI assistants navigate the coexistence of native MAUI and web-based Razor content. @@ -438,39 +471,6 @@ builder.Services.AddBlazorWebViewDeveloperTools(); Document your `BlazorWebView` setup in your repository instructions so AI assistants know the host page location and root component configuration. -> [!NOTE] -> Most AI coding assistants — including GitHub Copilot — automatically detect and follow `.editorconfig` rules when generating code. This makes `.editorconfig` one of the most effective ways to enforce consistent formatting across both human-written and AI-generated code without additional prompting. - -```ini -[*.cs] -indent_style = space -indent_size = 4 -charset = utf-8 - -# Naming conventions -dotnet_naming_rule.private_fields.symbols = private_fields -dotnet_naming_rule.private_fields.style = prefix_underscore -dotnet_naming_rule.private_fields.severity = suggestion - -dotnet_naming_symbols.private_fields.applicable_kinds = field -dotnet_naming_symbols.private_fields.applicable_accessibilities = private - -dotnet_naming_style.prefix_underscore.capitalization = camel_case -dotnet_naming_style.prefix_underscore.required_prefix = _ - -# Code style -csharp_style_var_for_built_in_types = true:suggestion -csharp_style_expression_bodied_methods = when_on_single_line:suggestion -csharp_prefer_braces = true:suggestion - -[*.xaml] -indent_style = space -indent_size = 4 -``` - -> [!TIP] -> If your team uses non-standard naming conventions (such as `m_` prefixes for member fields or `I` prefixes for all interfaces), document these explicitly in your `.editorconfig` and repository instructions. AI assistants default to standard .NET naming conventions and need explicit guidance to deviate. - ## See also - [Write a copilot-instructions.md file for .NET MAUI projects](copilot-instructions.md) diff --git a/docs/ai-development/devflow.md b/docs/ai-development/devflow.md index 4cb37bc860..167280aedf 100644 --- a/docs/ai-development/devflow.md +++ b/docs/ai-development/devflow.md @@ -172,6 +172,10 @@ No additional configuration is required. The agent is accessible over localhost No additional configuration is required. The agent is accessible over localhost once the app is running in the simulator. DevFlow's agent listens on port 9223 by default. +### Linux/GTK + +No additional configuration is required for Linux. Ensure your GTK dependencies are installed. For detailed setup, see the [DevFlow setup guides](https://github.com/dotnet/maui-labs/tree/main/docs/DevFlow/setup-guides). + ## Using with AI assistants MauiDevFlow is designed to work with AI coding assistants such as GitHub Copilot. When an AI agent has access to DevFlow (for example, through the MCP server), it can perform the following actions against your running app. diff --git a/docs/ai-development/index.md b/docs/ai-development/index.md index 42714e9a0a..69b3656dba 100644 --- a/docs/ai-development/index.md +++ b/docs/ai-development/index.md @@ -12,7 +12,7 @@ AI coding assistants are tools that integrate directly into your development env AI coding assistants such as GitHub Copilot and Claude Code can significantly improve productivity by providing context-aware code suggestions, platform-specific diagnostics, and automated debugging. From generating XAML layouts and platform-specific code to diagnosing build errors and suggesting API usage, these tools reduce the time you spend on repetitive tasks and help you explore unfamiliar platform APIs faster. -However, .NET MAUI's cross-platform nature introduces complexity that general-purpose AI coding assistants don't always handle well. A single .NET MAUI project can target up to six platforms (Android, iOS, Mac Catalyst, macOS, Windows, and Tizen), each with its own APIs, lifecycle, permissions model, and build tooling. Platform-specific code patterns (such as conditional compilation and platform-specific files), multi-targeted MSBuild configurations, and the interplay between XAML and C# all require context that an AI coding assistant won't have by default. +However, .NET MAUI's cross-platform nature introduces complexity that general-purpose AI coding assistants don't always handle well. A single .NET MAUI project can target up to five platforms (Android, iOS, Mac Catalyst, Windows, and Tizen), each with its own APIs, lifecycle, permissions model, and build tooling. Platform-specific code patterns (such as conditional compilation and platform-specific files), multi-targeted MSBuild configurations, and the interplay between XAML and C# all require context that an AI coding assistant won't have by default. This section covers how to configure your repository and development workflow so that AI coding assistants understand your .NET MAUI project structure, follow your team's conventions, and produce code that builds and runs correctly across platforms. From 60a62bb54c2efaf54c482d30052deb90d3b14b23 Mon Sep 17 00:00:00 2001 From: Gerald Versluis Date: Mon, 23 Mar 2026 07:27:53 +0100 Subject: [PATCH 6/8] Apply round 5 final fixes - Fix UseSafeArea applied to Grid instead of ContentPage - Remove placeholder GitHub issue URL Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/ai-development/best-practices.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/ai-development/best-practices.md b/docs/ai-development/best-practices.md index 97a1686458..8b8aaa9384 100644 --- a/docs/ai-development/best-practices.md +++ b/docs/ai-development/best-practices.md @@ -215,7 +215,7 @@ When you work around platform-specific behavior, explain **why** the workaround ```csharp // Android: WebView.EvaluateJavaScriptAsync can deadlock if called // before the page finishes loading. Wait for Navigated event first. -// See: https://github.com/dotnet/maui/issues/12345 +// Always wait for the Navigated event before evaluating JavaScript. webView.Navigated += async (s, e) => { var result = await webView.EvaluateJavaScriptAsync("getData()"); @@ -272,10 +272,14 @@ var path = FileSystem.AppDataDirectory; Starting with .NET 10, Android apps default to edge-to-edge display with `SafeAreaEdges` set to `None`. UI elements can render behind the system status bar and navigation bar. Account for safe areas in your layouts using platform-safe approaches rather than hardcoded padding values: ```xml - - - - + + + + + + ``` On Android, use `OnPlatform` with your app's safe area logic or the platform's `fitsSystemWindows` attribute. Avoid hardcoded padding values like `Padding="0,48,0,0"` because status bar height varies across Android devices and OS versions. Instead, query the actual insets at runtime or use community toolkit helpers that calculate platform-safe margins dynamically. From 1cba14c3783e9f222fd68acf999768700e624ab9 Mon Sep 17 00:00:00 2001 From: Gerald Versluis Date: Mon, 23 Mar 2026 09:24:06 +0100 Subject: [PATCH 7/8] Fix build warnings: ms.topic values and filename - Change ms.topic from 'concept' to 'conceptual' (best-practices.md) - Change ms.topic from 'concept' to 'overview' (index.md) - Rename devflow.md to dev-flow.md (filename-incomplete warning) - Update all cross-references to new filename Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/TOC.yml | 2 +- docs/ai-development/best-practices.md | 2 +- docs/ai-development/{devflow.md => dev-flow.md} | 0 docs/ai-development/index.md | 10 +++++----- docs/ai-development/skills.md | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) rename docs/ai-development/{devflow.md => dev-flow.md} (100%) diff --git a/docs/TOC.yml b/docs/TOC.yml index 848065af31..3c016344da 100644 --- a/docs/TOC.yml +++ b/docs/TOC.yml @@ -1263,7 +1263,7 @@ - name: Agent skills href: ai-development/skills.md - name: MauiDevFlow - href: ai-development/devflow.md + href: ai-development/dev-flow.md - name: Best practices href: ai-development/best-practices.md - name: Deployment & testing diff --git a/docs/ai-development/best-practices.md b/docs/ai-development/best-practices.md index 8b8aaa9384..03bb4bbf26 100644 --- a/docs/ai-development/best-practices.md +++ b/docs/ai-development/best-practices.md @@ -1,7 +1,7 @@ --- title: Best practices for AI-assisted .NET MAUI development description: Learn how to structure your .NET MAUI projects and write code that AI coding assistants can understand, navigate, and extend effectively. -ms.topic: concept +ms.topic: conceptual ms.date: 03/22/2026 no-loc: [".NET MAUI"] --- diff --git a/docs/ai-development/devflow.md b/docs/ai-development/dev-flow.md similarity index 100% rename from docs/ai-development/devflow.md rename to docs/ai-development/dev-flow.md diff --git a/docs/ai-development/index.md b/docs/ai-development/index.md index 69b3656dba..d477fe45e6 100644 --- a/docs/ai-development/index.md +++ b/docs/ai-development/index.md @@ -1,7 +1,7 @@ --- title: "AI-assisted development" description: "Learn how to configure your .NET MAUI projects so AI coding assistants like GitHub Copilot and Claude Code can help you build cross-platform apps more effectively." -ms.topic: concept +ms.topic: overview ms.date: 03/22/2026 no-loc: [".NET MAUI"] --- @@ -21,7 +21,7 @@ This section covers how to configure your repository and development workflow so - **Want better code suggestions?** → Start with [Repository instructions](copilot-instructions.md) - **Need task-specific AI guidance?** → See [Custom instruction files](custom-instructions.md) - **Want pre-built MAUI diagnostics?** → Install [Agent skills](skills.md) -- **Need to debug complex UI issues?** → Try [MauiDevFlow](devflow.md) (experimental) +- **Need to debug complex UI issues?** → Try [MauiDevFlow](dev-flow.md) (experimental) ## What's available @@ -41,7 +41,7 @@ A [repository instructions file](copilot-instructions.md) (`.github/copilot-inst ### MauiDevFlow -[MauiDevFlow](devflow.md) is an experimental tool that connects AI coding assistants to your running app's visual tree. It enables AI-assisted UI debugging by letting the assistant inspect the live element hierarchy, identify layout issues, and suggest fixes based on actual runtime state. +[MauiDevFlow](dev-flow.md) is an experimental tool that connects AI coding assistants to your running app's visual tree. It enables AI-assisted UI debugging by letting the assistant inspect the live element hierarchy, identify layout issues, and suggest fixes based on actual runtime state. ### Best practices @@ -54,7 +54,7 @@ Follow these steps to make your .NET MAUI repository AI-ready: 1. **[Add repository instructions.](copilot-instructions.md)** Create a `.github/copilot-instructions.md` file with your project overview, build commands (`dotnet build`, `dotnet run`), and target frameworks. 2. **[Document platform-specific conventions.](best-practices.md#platform-specific-code-patterns)** List your file naming patterns for platform code (`.ios.cs`, `.android.cs`, `.windows.cs`) and any conditional compilation symbols you use. 3. **[Install the `dotnet-maui` agent skill.](skills.md)** This gives AI coding assistants MAUI-specific diagnostics and API knowledge out of the box. -4. **[Consider adding MauiDevFlow (experimental).](devflow.md)** If you frequently debug layout or visual tree issues, this tool lets AI coding assistants inspect your running UI. +4. **[Consider adding MauiDevFlow (experimental).](dev-flow.md)** If you frequently debug layout or visual tree issues, this tool lets AI coding assistants inspect your running UI. 5. **[Document your testing and CI setup.](best-practices.md#build-and-test-configuration)** Include instructions for running unit tests, UI tests, and any platform-specific test configurations so AI coding assistants can help you write and debug tests. 6. **[Read existing project conventions.](custom-instructions.md)** When contributing to an existing repo, first read its `.github/copilot-instructions.md` and any `AGENTS.md` file to understand the project's conventions. @@ -66,7 +66,7 @@ Follow these steps to make your .NET MAUI repository AI-ready: - [Repository instructions for .NET MAUI](copilot-instructions.md) - [Custom instruction files](custom-instructions.md) - [Agent skills for .NET MAUI](skills.md) -- [MauiDevFlow](devflow.md) +- [MauiDevFlow](dev-flow.md) - [Best practices for AI-assisted development](best-practices.md) - [Microsoft.Extensions.AI overview](/dotnet/ai/ai-extensions) - [On-device AI capabilities](../ai/index.md) diff --git a/docs/ai-development/skills.md b/docs/ai-development/skills.md index 55cbe82ee6..7a1364cba8 100644 --- a/docs/ai-development/skills.md +++ b/docs/ai-development/skills.md @@ -230,12 +230,12 @@ Skills and instruction files serve different roles in your AI-assisted developme - **Instruction files** provide *static context* — they describe your project structure, coding conventions, architectural patterns, and platform-specific guidelines. The AI assistant reads these files to understand *how* your project is organized and *what* conventions to follow. - **Skills** provide *dynamic capabilities* — they enable the AI assistant to perform actions like running diagnostics, analyzing build errors, scaffolding code from templates, and profiling performance. Skills give the assistant the ability to *do* things, not just know things. -- **[MauiDevFlow](devflow.md)** provides *runtime inspection* — it connects the AI assistant to your running app so it can query the live visual tree, capture screenshots, read DOM snapshots from Blazor WebViews, and check logs. DevFlow gives the assistant visibility into actual runtime state, which neither instruction files nor skills can provide. +- **[MauiDevFlow](dev-flow.md)** provides *runtime inspection* — it connects the AI assistant to your running app so it can query the live visual tree, capture screenshots, read DOM snapshots from Blazor WebViews, and check logs. DevFlow gives the assistant visibility into actual runtime state, which neither instruction files nor skills can provide. For example, an instruction file might tell the AI assistant to use compiled bindings in XAML, the `dotnet-maui` skill enables the assistant to validate your development environment and diagnose why a build targeting iOS is failing, and DevFlow lets the assistant inspect your running app's visual tree to identify why a layout renders differently than expected. Together, they give the AI the context, the capabilities, and the runtime visibility to assist effectively. ## See also - [Write a copilot-instructions.md file for .NET MAUI projects](copilot-instructions.md) -- [AI-assisted UI debugging with MauiDevFlow](devflow.md) +- [AI-assisted UI debugging with MauiDevFlow](dev-flow.md) - [.NET Agent Skills marketplace (GitHub)](https://github.com/dotnet/skills) From b68993e0f8fdabd2ad4ed7e39861e3d6867a9b83 Mon Sep 17 00:00:00 2001 From: Gerald Versluis Date: Mon, 23 Mar 2026 09:35:30 +0100 Subject: [PATCH 8/8] Fix MD032 lint: add blank line before list after callout Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/ai-development/best-practices.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/ai-development/best-practices.md b/docs/ai-development/best-practices.md index 03bb4bbf26..0d1e3cd3eb 100644 --- a/docs/ai-development/best-practices.md +++ b/docs/ai-development/best-practices.md @@ -185,6 +185,7 @@ Include a `README.md` at the repository root with: > [!NOTE] > The examples in this article use `net10.0-*` target framework monikers. Substitute your project's target .NET version (for example, `net9.0-android`, `net9.0-ios`) wherever you see a TFM in build commands or project configuration. + - **Architecture overview** describing the patterns used (MVVM, dependency injection, messaging) - **Key dependencies** and their purpose - **Platform-specific setup** requirements (Xcode version, Android SDK levels, Windows SDK)