## Executive Summary

Historically, mobile development in .NET (Xamarin and early .NET MAUI through .NET 10) relied heavily on IDE-centric workflows: hitting F5 inside Visual Studio with heavy graphical target device dropdowns. Command-line interface (CLI) parity was incomplete or required esoteric MSBuild properties (`/p:AdbTarget`, `/t:Run`).

In **.NET 11**, the developer landscape has undergone two massive shifts:
1. **Lightweight terminal-first development:** The widespread adoption of Visual Studio Code, command line inner loops, and `tasks.json`.
2. **Autonomous AI Coding Agents:** Autonomous agents (such as GitHub Copilot CLI, Devin, Claude Code, and Antigravity swarms) do not have IDE click-interfaces. They require deterministic CLI commands (`dotnet build`, `dotnet run`, `dotnet test`, and `dotnet watch`) to execute, inspect, iterate, and verify that mobile code builds and runs cleanly.

In response, Jonathan Peppers and the .NET Mobile team re-architected the .NET CLI and mobile workloads to achieve full parity for mobile apps across Android, iOS, Mac Catalyst, and tvOS. By decoupling OS specifics into MSBuild extension target contracts (`ComputeAvailableDevices`, `DeployToDevice`, `ComputeRunArguments`), introducing interactive Spectre.Console terminal selectors, replacing desktop Named Pipes with WebSockets across port-forwarded adb/USB tunnels, and unifying testing around the Microsoft Testing Platform (MTP), .NET 11 transforms mobile development into a first-class CLI and agentic citizen.

![Session Title](/dotnetconf2026/archive/18-dotnet-run-test-watch-maui/screenshots/01_title_dotnet_run_test_watch_maui.webp)

---

## 1. The Evolving Developer Landscape: From IDE F5 to Autonomous AI Agents

When .NET MAUI initially released in May 2022, desktop IDEs were the primary medium. In .NET 11, developers increasingly work in lightweight editors and terminal shells. Crucially, **AI agents writing and modifying code** need standard CLI commands to validate changes autonomously.

![AI Agents and CLI Landscape](/dotnetconf2026/archive/18-dotnet-run-test-watch-maui/screenshots/02_ai_agents_cli_landscape.webp)

### Why Mobile Was Hard for the CLI
Unlike a simple console application where running simply executes an `.exe` and streams `stdout`:
- **Target Disambiguation:** A multi-targeted MAUI project (`net11.0-android`, `net11.0-ios`, `net11.0-windows10...`) cannot assume a single runtime target.
- **Device Selection:** The runtime target must bind to a physical USB device, network device, emulator, or simulator.
- **Packaging & Deployment:** The binary must be signed, packaged into an `.apk`/`.aab` or `.ipa`/app bundle, pushed over ADB or `devicectl`/`ios-deploy`, and installed.
- **OS Launch Invocation:** The OS runtime (Android Activity Manager `am start` or iOS `launchd`) must be instructed to spawn the app process.
- **Log Streaming:** Process output does not naturally stream to the terminal `stdout`; it must be captured from Android `logcat` or the Apple unified logging daemon and routed back to the terminal.
- **Lifecycle Cleanliness:** Striking `Ctrl+C` in the terminal must cleanly signal and terminate the remote mobile process.

---

## 2. Architecture of `dotnet run` for Mobile

To solve this without polluting the core .NET SDK with vendor-specific mobile quirks, Microsoft developed a modular execution pipeline orchestrated by the CLI and fulfilled by workload targets.

![dotnet run Mobile Pipeline](/dotnetconf2026/archive/18-dotnet-run-test-watch-maui/screenshots/03_dotnet_run_mobile_pipeline.webp)

### Execution Sequence
1. **Restore:** NuGet package and workload graph verification.
2. **Selection (Interactive or Explicit):** Disambiguation of Target Framework (`-f`) and target hardware/emulator (`--device`).
3. **Build:** Compiling C# source code, AOT/IL compilation, resource packaging.
4. **Deploy:** Transferring and installing the artifact to the target hardware/emulator.
5. **Compute Run Arguments:** Resolving environment variables, start activities, and launch flags.
6. **Execute & Stream:** Spawning the mobile process, attaching to log streams (`logcat`), and handling `Ctrl+C` graceful termination.

### MSBuild Workload Extension Targets Contract
The CLI decouples itself from iOS and Android mechanics by defining standardized MSBuild extension targets implemented inside the respective workload SDKs:

![MSBuild Mobile Extension Targets](/dotnetconf2026/archive/18-dotnet-run-test-watch-maui/screenshots/04_msbuild_mobile_extension_targets.webp)

| MSBuild Target Name | Description & Mobile Workload Behavior |
|---|---|
| `ComputeAvailableDevices` | Scans attached hardware and active simulators/emulators. Returns item collections containing Device ID, OS version, hardware type, and status. |
| `DeployToDevice` | Takes the packaged bundle and executes transport commands (e.g., `adb install -r` or Apple simulator installation). |
| `ComputeRunArguments` | Generates the exact command-line arguments and executable needed to trigger app launch on the remote host/simulator. |

### Interactive vs. Non-Interactive (Agent/CI) Modes
In interactive developer sessions, `dotnet run` activates an interactive **Spectre.Console** menu, allowing keyboard arrow selection and type-ahead fuzzy searching across frameworks and available devices.

![Spectre Console Device Selector](/dotnetconf2026/archive/18-dotnet-run-test-watch-maui/screenshots/08_spectre_console_device_selector.webp)

For CI pipelines and autonomous AI agents, flags bypass the interactive prompt:
```bash
# Explicit target framework and device
dotnet run -f net11.0-android --device "Pixel 10"

# Querying attached devices programmatically
dotnet run -f net11.0-android --list-devices
```

---

## 3. Architecture of `dotnet watch` for Mobile: WebSockets over ADB

`dotnet watch` provides hot reload directly from the CLI. While desktop .NET Watch communicates with running apps over local IPC (Named Pipes), mobile devices connected via USB or network cannot bind directly to desktop named pipes.

![dotnet watch Architecture](/dotnetconf2026/archive/18-dotnet-run-test-watch-maui/screenshots/05_dotnet_watch_architecture.webp)

### The WebSocket Bridge & Startup Hooks
To bridge this gap while keeping the payload protocol identical:
1. **Startup Hook Injection:** `dotnet watch` injects a custom agent DLL into the application launch path via the runtime environment variable `DOTNET_STARTUP_HOOKS`.
2. **Port Forwarding:**
   - **Android:** Executes `adb forward tcp:<port> tcp:<port>` to tunnel traffic from localhost over the USB ADB connection.
   - **iOS:** Establishes a localhost tunnel via Apple USB multiplexing services.
3. **Hot Reload Capabilities:** The mobile workload advertises `<ProjectCapability Include="HotReloadWebSockets" />`.
4. **Delta Application:** When source files (`.cs` or `.xaml`) are modified, Roslyn generates an edit metadata delta (`.dmeta` / `.dil`), which is transmitted across the WebSocket and applied dynamically into the running Mono/CoreCLR runtime on device.
5. **Rude Edit Recovery:** If an unsupported edit is made (e.g., modifying struct fields, altering inheritance hierarchies), the CLI alerts the developer and supports `Ctrl+R` to trigger an in-place rebuild, re-deploy, and restart.

![Startup Hooks and WebSocket Tunneling](/dotnetconf2026/archive/18-dotnet-run-test-watch-maui/screenshots/06_startup_hooks_websocket_adb.webp)

---

## 4. `dotnet test` with Microsoft Testing Platform (MTP)

Prior mobile testing required complex third-party harnesses, NUnit runners embedded in heavy UI shells, or Visual Studio Test (VS Test) adapters. In .NET 11, mobile unit and integration testing standardizes on the **Microsoft Testing Platform (MTP)**.

![dotnet test MTP Orchestrator](/dotnetconf2026/archive/18-dotnet-run-test-watch-maui/screenshots/07_dotnet_test_mtp_orchestrator.webp)

### Architectural Advantages of MTP on Mobile
- **Headless Execution:** On Android, tests execute via native Android **Instrumentation** (`android.app.Instrumentation`). The test harness runs silently in the background without launching a full interactive activity or disrupting the physical screen. On iOS, native UIKit test harnesses execute with zero extraneous UI overhead.
- **Framework Agnostic:** Supports MSTest, NUnit, xUnit v3, and TUnit seamlessly on top of the MTP orchestrator.
- **Deterministic CI Reporting:** Generates console summaries and `.trx` report files directly consumable by CI systems and AI agents.

### New CLI Project Templates
.NET 11 introduces dedicated platform test templates configured with MTP and `global.json`:
```bash
dotnet new android-test -n MyApp.Android.Tests
dotnet new ios-test -n MyApp.iOS.Tests
dotnet new maccatalyst-test -n MyApp.Mac.Tests
dotnet new tvos-test -n MyApp.tvOS.Tests
```

---

## 5. Live Demonstrations & Verification

Jonathan demonstrated end-to-end execution of all three commands on a physical **Google Pixel 10** mirrored via Vysor:

### 1. `dotnet run` on Pixel 10
Selecting `net11.0-android` and the `Pixel 10` device triggered automatic build, APK alignment, ADB deployment, and launch. Standard output filtered process logcat entries directly into the terminal, capturing runtime clicks and C# `Console.WriteLine` outputs.

![Pixel 10 Vysor and Logcat Output](/dotnetconf2026/archive/18-dotnet-run-test-watch-maui/screenshots/09_pixel10_vysor_logcat_output.webp)

### 2. `dotnet watch` Live Updates
Modifying XAML (`Hello World` to `Hello .NET conf`) applied instantly over the WebSocket connection without reloading the activity state. Subsequent C# code modifications (counter increment logic) re-compiled and updated live on the physical device.

### 3. `dotnet test` Headless Instrumentation
Running `dotnet test` against the Android test template deployed an instrumentation package. The tests executed cleanly in under 3 seconds without launching an application window, outputting green MSTest/MTP execution assertions directly to stdout.

![Android Instrumentation Test Results](/dotnetconf2026/archive/18-dotnet-run-test-watch-maui/screenshots/10_android_instrumentation_test_results.webp)

---

## Summary Comparison: Mobile CLI Evolution

| Capability | Legacy .NET (Xamarin / .NET 10) | .NET 11 MAUI Architecture |
|---|---|---|
| **Primary Execution Path** | Visual Studio IDE F5 GUI | Unified `dotnet run`, `watch`, `test` CLI |
| **Interactive Selection** | IDE GUI Dropdowns; manual `-f` requirement | Interactive **Spectre.Console** terminal selector |
| **Non-Interactive / Agent Support** | Fragmented MSBuild `/p:` parameters | Standardized `-f`, `--device`, `--list-devices` |
| **Hot Reload Transport** | Desktop Named Pipes (unsupported on device) | **WebSockets** + `DOTNET_STARTUP_HOOKS` via ADB/USB |
| **Test Runner Architecture** | VS Test UI test harnesses | Headless **MTP** (Android Instrumentation / UIKit) |
| **AI Agent Compatibility** | Poor (requires GUI emulation) | First-class native CLI verification loops |
