Skip to content

Latest commit

 

History

History

DevFlow

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

Microsoft.Maui.DevFlow

A comprehensive testing, automation, and debugging toolkit for .NET MAUI applications — and, since the agent was split away from MAUI, for plain .NET Android, iOS, Mac Catalyst and macOS apps too.

⚠️ Experimental — APIs may change between releases. Not covered by the Microsoft Support Policy.

Integration CI

devflow-integration.yml automatically tests DevFlow-relevant pull requests targeting main, including drafts. It covers MAUI and plain .NET apps on Android, iOS, Mac Catalyst and AppKit, plus MAUI Windows, GTK and WPF. Manual dispatch supports selecting a platform and framework. Use manual dispatch to run it on a branch that does not target main.

Triggers cover DevFlow, its CLI, samples, platform backends and shared build inputs. The separate ci-devflow.yml workflow runs host, browser, JavaScript and AOT tests.

Packages

Package Description
Microsoft.Maui.DevFlow.Agent In-app agent for .NET MAUI apps. Exposes visual tree, element interactions, screenshots, and profiling via HTTP/JSON API.
Microsoft.Maui.DevFlow.Agent.Abstractions The protocol itself: HTTP server, routing, element DTOs, CSS selector engine, network capture, profiling, extensions. No MAUI dependency.
Microsoft.Maui.DevFlow.Agent.Core The MAUI UI backend: visual tree walker, VisualElement interactions, BindableProperty access, Essentials endpoints.
Microsoft.Maui.DevFlow.Agent.Gtk GTK/Linux agent for Microsoft.Maui.Platforms.Linux.Gtk4 apps.
Microsoft.Maui.DevFlow.Agent.Native In-app agent for plain .NET apps with no MAUI reference — Android views, UIKit, and AppKit backends.
Microsoft.Maui.DevFlow.Agent.Native.Essentials Optional add-on that lights up the device, storage and sensor endpoints for native apps using MAUI Essentials.
Microsoft.Maui.DevFlow.Blazor Blazor WebView CDP bridge. Enables Chrome DevTools Protocol access for Blazor Hybrid content via Chobitsu.
Microsoft.Maui.DevFlow.Blazor.Gtk Blazor CDP bridge for WebKitGTK on Linux.
Microsoft.Maui.DevFlow.CLI DevFlow command implementation used by the unified maui devflow CLI surface for automation, debugging, and MCP server support.
Microsoft.Maui.DevFlow.Client Portable protocol client: AgentClient, element and protocol DTOs, and their serialization. Targets netstandard2.0, so .NET Framework harnesses speak the same protocol as modern .NET consumers.
Microsoft.Maui.DevFlow.Driver Platform-aware app driver for iOS, tvOS simulators, Android, Mac Catalyst, Windows, and Linux. Builds on Microsoft.Maui.DevFlow.Client.
Microsoft.Maui.DevFlow.Logging Buffered rotating JSONL file logger. No MAUI dependency.

Quick Start

WebView failures

WebView HTTP and CDP failures are reported as errors, not successful evaluation results. JavaScript exceptions include their description; when a bridge returns only a stack, the agent reads the original error object's message property without re-evaluating the failed expression. CLI evaluation exits nonzero on failure, and MCP evaluation/source tools report an error (including empty source).

Breaking behavior change: AgentClient.SendCdpCommandAsync now throws on HTTP, CDP, JavaScript, invalid JSON/non-object responses, and explicit success: false. NavigateWebViewAsync, ClickWebViewAsync, FillWebViewAsync, and InsertWebViewTextAsync retain their Task<bool> signatures but throw on failure or a missing/non-true success flag instead of returning false. HTTP failures throw HttpRequestException with the response body; protocol/JavaScript failures throw InvalidOperationException, and invalid JSON throws JsonException. GetCdpSourceAsync includes the response body in HTTP exceptions.

NativeAOT and trimming

The agent's built-in HTTP requests/responses, broker registration and lease/recording messages, and WebSocket envelopes use source-generated JSON metadata. They do not require JsonSerializerIsReflectionEnabledByDefault=true. The same contracts run in reflection-disabled trimmed JIT applications. MAUI-specific JSON metadata is registered by Agent.Core; Agent.Abstractions remains MAUI-free.

Custom extension payloads can use string-keyed dictionaries, sequences, primitive values, JsonElement, JsonNode, or JsonDocument without additional registration. For custom CLR request/response types, register a source-generated context before serving requests:

using System.Text.Json.Serialization;
using Microsoft.Maui.DevFlow.Agent.Core;

AgentJson.RegisterContext(MyExtensionJsonContext.Default);

// Existing extension handlers can still use request.BodyAs<MyRequest>() and
// HttpResponse.Json(new MyResponse(...)).
[JsonSerializable(typeof(MyRequest))]
[JsonSerializable(typeof(MyResponse))]
internal partial class MyExtensionJsonContext : JsonSerializerContext;

Include concrete types used inside object-typed members in that context too. Unregistered types fail with an explicit metadata error when JSON reflection is disabled; HTTP handlers report 500 with reason json-metadata-missing rather than dropping the connection or silently serializing an empty object. Reflection-enabled hosts retain the existing arbitrary-object serialization behavior. No existing public method signatures or wire field names changed.

The default System.Text.Json object converter remains in use. Registered polymorphic base/derived contracts retain their discriminators, and member-level JsonNumberHandling applies to boxed numbers and values inside dynamic collections. Generated STJ sequence and dictionary ancestor contracts use native element traversal, including the containing member's settings. Registered converters take precedence.

Custom collection types with multiple unrelated dictionary interfaces can have ambiguous STJ ancestor metadata. Register the concrete collection type in a source-generated context in that case. Unsupported JSON contracts return 500 with reason json-serialization-unsupported and the original diagnostic; missing metadata continues to use json-metadata-missing. These errors do not silently change a dictionary into an array or close the connection without a response.

Common MAUI controls retain the public property accessors and bindable-property fields needed by the inspector. For custom controls or custom objects reached through a property path, opt in to preserving just that type's inspection contract:

MauiAgentInspection.RegisterType<MyCustomControl>();
MauiAgentInspection.RegisterType<MyCustomPropertyObject>();

This is not a guarantee that every reflection-based feature is trim-safe. Automatic [DevFlowAction] assembly scanning, arbitrary generic/async method invocation, custom TypeConverter discovery, the legacy reflection-only Comet adapter, and native-handler reflection fallbacks still need application-specific metadata/code preservation. Their linker warnings are not suppressed. Prefer explicit extension routes with generated JSON contracts for AOT applications. Platform screenshots, native injection, and device/Essentials APIs additionally require verification on the target platform; the host smoke below does not render a native UI.

The DevFlow PR workflow publishes and runs both the agent smoke (including the headless MAUI backend) and the standalone logging smoke as Native AOT executables on Linux.

The standalone smoke starts only its own loopback agent and broker fixtures. It checks reflection-disabled HTTP/broker/WebSocket serialization and the core UI transport contracts. Optional MAUI checks exercise real headless MAUI tree walking, tap, property read/write, descriptors, and custom-type registration:

dotnet run --project src/DevFlow/Microsoft.Maui.DevFlow.Agent.AotSmoke \
  -p:IncludeMauiBackend=true -- .artifacts/devflow-aot/jit

# Use the host RID (osx-arm64 shown). AotSmoke sets PublishAot only on the
# executable, not on its netstandard analyzer dependency.
dotnet publish src/DevFlow/Microsoft.Maui.DevFlow.Agent.AotSmoke \
  -c Release -r osx-arm64 -p:AotSmoke=true -p:IncludeMauiBackend=true \
  -p:TrimmerSingleWarn=false -o .artifacts/devflow-aot/native
.artifacts/devflow-aot/native/Microsoft.Maui.DevFlow.Agent.AotSmoke \
  .artifacts/devflow-aot/native-evidence

1. Install the NuGet packages

<PackageReference Include="Microsoft.Maui.DevFlow.Agent" />
<PackageReference Include="Microsoft.Maui.DevFlow.Blazor" />  <!-- If using Blazor Hybrid -->

2. Register in MauiProgram.cs

using Microsoft.Maui.DevFlow.Agent;

public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder.UseMauiApp<App>();

    #if DEBUG
    builder.AddMauiDevFlowAgent();
    #endif

    return builder.Build();
}

Layout diagnostics is currently feature-gated while the cross-platform acceptance matrix completes. Enable it explicitly:

builder.AddMauiDevFlowAgent(options =>
{
    options.EnableLayoutDiagnostics = true;
});

GTK/Linux apps

Use Microsoft.Maui.DevFlow.Agent.Gtk instead of the standard agent package with Microsoft.Maui.Platforms.Linux.Gtk4. For Blazor Hybrid, use Microsoft.Maui.DevFlow.Blazor.Gtk alongside Microsoft.Maui.Platforms.Linux.Gtk4.BlazorWebView. These packages use the in-repo GTK backend; remove superseded Platform.Maui.Linux.Gtk4* package references when migrating. Mixing the two backends is not supported. For Essentials diagnostics, reference Microsoft.Maui.Platforms.Linux.Gtk4.Essentials and call builder.AddLinuxGtk4Essentials(); a package reference alone does not initialize MAUI's static Preferences and FileSystem facades.

using Microsoft.Maui.DevFlow.Agent.Gtk;
using Microsoft.Maui.Platforms.Linux.Gtk4.Hosting;

// In CreateMauiApp:
builder.UseMauiAppLinuxGtk4<App>();
#if DEBUG
builder.AddMauiDevFlowAgent();
#endif

AddMauiDevFlowAgent starts the agent automatically on the GTK thread when the first window is created, after GtkMauiApplication has initialized the MAUI application and its handler. No manual startup call is required. Hosts needing an explicit startup hook can call the extension from OnStarted (not CreateMauiApp, which is too early):

using Microsoft.Maui.DevFlow.Agent.Gtk;
using Microsoft.Maui.Hosting;
using Microsoft.Maui.Platforms.Linux.Gtk4.Platform;

public class Program : GtkMauiApplication
{
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

    protected override void OnStarted()
    {
        base.OnStarted();
#if DEBUG
        this.StartDevFlowAgent();
#endif
    }
}

The explicit hook still requires builder registration. Calling it before initialization or without registering the agent reports an error instead of silently doing nothing. Use maui devflow list to discover the assigned port rather than assuming port 9223.

For Blazor Hybrid, register builder.AddMauiBlazorDevFlowTools() from Microsoft.Maui.DevFlow.Blazor.Gtk as well. CDP wiring starts when the GTK window is created. WebViews are captured through their handlers, initialized on document load, and unregistered on detachment. Repeated WireBlazorCdpToAgent() calls are safe.

Optional bridge diagnostics use GtkBlazorWebViewDebugService.LogCallback; AddMauiBlazorDevFlowTools(enableLogging: true) enables debugger output. JavaScript console entries are available through the DevFlow log API when log capture is enabled.

tvOS apps

MAUI has no tvOS backend of its own. Apps that run MAUI on tvOS through a community backend such as Platform.Maui.TvOS use the standard Microsoft.Maui.DevFlow.Agent package, which has net10.0-tvos and net11.0-tvos targets built and packed alongside the other Apple targets, including in the Windows signing build. Register it in the backend's CreateMauiApp:

using Microsoft.Maui.DevFlow.Agent;

#if DEBUG
builder.AddMauiDevFlowAgent();
#endif

The agent starts once the backend has created the MAUI application. The visual tree, element and window screenshots, tap (sent as PrimaryActionTriggered, the Siri Remote select press), fill, navigation, logs and preference key listing work. Point gestures and synthetic touch are not available because tvOS has no touchscreen. MAUI Essentials ships no tvOS implementation, so the agent reads the platform and app identity from UIKit and the app bundle; the other Essentials endpoints (preference values, secure storage, device info and sensors) return an error unless the app registers an Essentials backend. tvOS 27 only launches apps that adopt the scene lifecycle, so declare UIApplicationSceneManifest in Info.plist and use a backend version that supports scenes. See samples/DevFlow.Sample.TvOS.

The CLI and MCP tools use the selected agent's simulator UDID, not the first booted iPhone or Apple TV. Unscoped screenshots capture the entire simulator display, including system overlays; element and capture-bound screenshots stay with the agent. Simulator recording and app-scoped light/dark theme switching also work. Explicit simulator targets use the existing Apple commands:

maui device list --platform tvos
maui apple runtime list --platform tvOS
maui apple simulator start <tv-udid>
maui apple simulator install <tv-udid> path/to/DevFlow.Sample.TvOS.app
maui apple simulator launch <tv-udid> com.companyname.devflow.tvos
maui devflow ui screenshot --output tv.png
maui devflow recording start --platform tvos --device <tv-udid> --output tv.mp4
maui devflow recording stop
maui devflow theme set dark --scope app
maui apple simulator stop <tv-udid>

maui apple simulator also supports create/delete, app uninstall/terminate, screenshots and video recording without an agent. This is not a full Siri Remote emulator: directional focus movement, remote button injection and system-dialog interaction are not implemented for tvOS. simctl ui appearance is unsupported on Apple TV, so theme changes apply to the app, not the simulator system. Use agent element actions for app controls; physical Apple TVs use in-app screenshots and actions, not host simctl operations.

For manual simulator navigation, use arrow keys to move focus, Return to select, and Escape to go back (Apple's keyboard shortcuts). DevFlow's key action (maui_key over MCP) operates on supported text controls; it does not inject these simulator shortcuts. Element actions do not validate real remote/focus navigation. The bundled maui-devflow-debug Apple reference has the deployment and automation workflow. Updated CLI bundles distribute this guidance through maui devflow init; existing installations can use maui devflow skills update.

2b. Or, in a plain .NET app (no MAUI)

The same agent, CLI and MCP tools work against apps that never reference MAUI. Reference Microsoft.Maui.DevFlow.Agent.Native and start it explicitly — there is no host builder to hook, so nothing starts by itself.

<PackageReference Include="Microsoft.Maui.DevFlow.Agent.Native" />
// Android — MainActivity.OnCreate
using Microsoft.Maui.DevFlow.Agent.Native;

protected override void OnCreate(Bundle? savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.activity_main);
#if DEBUG
    this.StartDevFlowAgent();   // binds the activity the tree is walked from
#endif
}
// iOS / Mac Catalyst — AppDelegate.FinishedLaunching
// macOS — AppDelegate.DidFinishLaunching
#if DEBUG
DevFlowAgent.Start();
#endif

Everything that does not need a UI framework behaves identically: visual tree, CSS queries, hit-testing, tap/fill/clear/focus/key/gesture/scroll/batch, property get/set, screenshots, logs, network capture, the profiler, actions and extensions.

Endpoints that have no meaning outside MAUI answer 501 with { "error": "not_supported", "capability": …, "reason": … } rather than failing opaquely, and /api/v1/agent/capabilities reports them as supported: false up front. Today that is app theme (MAUI reads Application.RequestedTheme) and Shell navigation. Preferences, secure storage, device info, display, battery, connectivity, permissions, geolocation and sensors also start unsupported — add Microsoft.Maui.DevFlow.Agent.Native.Essentials and swap the bootstrap to light them up:

<PackageReference Include="Microsoft.Maui.DevFlow.Agent.Native.Essentials" />
using Microsoft.Maui.DevFlow.Agent.Native.Essentials;

// iOS / Mac Catalyst / macOS
EssentialsDevFlowAgent.Start();

// Android
Microsoft.Maui.ApplicationModel.Platform.Init(this, savedInstanceState);
this.StartDevFlowAgentWithEssentials();

That add-on pulls in Microsoft.Maui.Essentials, which needs the MAUI workload installed but does not make the app a MAUI app — no Microsoft.Maui.Controls, no MauiApp host. On Android it also requires the usual Essentials wiring: Platform.Init as above, plus forwarding OnRequestPermissionsResult to Platform.OnRequestPermissionsResult.

Clients can tell the two apart without guessing: /api/v1/agent/status reports framework (maui | native) alongside uiFramework (maui-controls | android-views | uikit | appkit | gtk | wpf).

3. Install the unified CLI tool

dotnet tool install -g Microsoft.Maui.Cli --prerelease

4. Interact with your running app

# Install DevFlow skills for AI agent integration (auto-detects target directory;
# defaults to .claude/skills/ — configurable via --target: claude, github, agent, agents, or auto)
maui devflow init

# Visual tree
maui devflow ui tree

# Detect clipped, overflowing, truncated, or occluded UI
maui devflow ui diagnostics --profile agent

# Take a screenshot
maui devflow ui screenshot --output screenshot.png

# Tap an element
maui devflow ui tap --automationId "MyButton"

# Start MCP server for AI agent integration
maui devflow mcp

# Start the Inspector, then open http://localhost:19223/inspector/
maui devflow broker start

Session identity

When Microsoft.Maui.DevFlow.Agent is referenced, builds are tagged with a session identity derived from a one-way, sanitized project-path value. This metadata-only identifier helps DevFlow distinguish builds from different environments without modifying the app's ApplicationId or bundle identifier. The full project path is not embedded by default.

The session identity is included in:

  • Assembly metadata (Microsoft.Maui.DevFlowSessionId) — compile-time injected by the Microsoft.Maui.DevFlow.Agent MSBuild targets
  • Project identity metadata (Microsoft.Maui.DevFlowProject) — the project filename by default
  • Broker registration (visible via maui devflow list)
  • Agent status endpoint (/api/v1/agent/status)

You can override the automatically derived identity:

# Set a specific session identity
dotnet build -p:MauiDevFlowSessionId=mysession

Note: Session IDs are sanitized to lowercase alphanumeric characters only. For example, My-Session would become mysession. Auto-derived IDs (from the project path) are prefixed with dw and truncated to 26 characters. Explicit overrides keep the full sanitized value without prefix or truncation.

The same value can also be supplied via the MAUI_DEVFLOW_SESSION_ID environment variable.

For local debugging that needs full-path project disambiguation, opt in explicitly with -p:MauiDevFlowIncludeProjectPath=true. This embeds the project path in the app assembly.

Features

  • Visual Tree Inspection — query the full MAUI visual tree via HTTP API or CLI
  • Layout Diagnostics — detect clipping, lost overflow, text truncation, overlap, and interaction occlusion with platform-specific evidence and confidence
  • Element Interaction — tap, fill, scroll, navigate, focus, resize, and mutate properties
  • Continuous Pointer Sessions — capability-negotiated, bounded/coalesced press-move-release input for Android and opt-in UIKit targets, with safe legacy gesture fallback
  • Application Menus — inspect and invoke the app menu bar: the cross-platform MAUI MenuBarItems tree plus the native macOS AppKit NSMenu and active Mac Catalyst responder-chain key commands. Disabled items and disabled ancestors are respected; unhandled native actions report failure.
  • Screenshots — capture PNG screenshots from any platform (full window or per-element); AppKit window capture includes native chrome and attached sheets without activating the app
  • Screen Recording — start/stop video recording of app sessions
  • Network Monitoring — intercept and inspect HTTP requests/responses
  • Performance Profiling — CPU, memory, GC, and jank detection with markers and spans
  • Blazor CDP Bridge — Chrome DevTools Protocol for Blazor WebViews (DOM, JS eval, navigation, input)
  • DevFlow Web Inspector — the shared browser UI, embedded by MAUI DevFlow Inspector hosts for VS Code and GitHub Copilot Canvas
  • Global Mutation Lease — prevents browser, VS Code, Canvas, MCP, and CLI callers from driving the app concurrently
  • Workflow Recording — broker-owned recording observes successful mutations from every host and emits replayable Markdown
  • Click-to-XAML — Debug source maps connect visual-tree elements to their XAML declarations
  • MCP Server — structured tools for AI agent integration, including maui_layout_diagnostics
  • Logging — buffered JSONL file logging with WebView JS console capture
  • Real-time Streaming — WebSocket channels for logs, network, sensors, profiler, and UI events
  • Storage Access — read/write app preferences, secure storage, discover file storage roots, and manage sandboxed app files remotely
  • Device Introspection — battery, connectivity, geolocation, display, permissions, and sensor data
  • Dialog Handling — detect and dismiss alerts/action sheets programmatically; maui_native_dialog_detect / maui_native_dialog_respond require an exact, user-confirmed choice and a one-time prompt token
  • Batch Operations — execute command sequences from stdin for scripting
  • Agent Extensions — expose app-specific diagnostic tools under /api/v1/ext/{namespace}/... with self-describing metadata for CLI and MCP discovery
  • Multi-Platform — iOS, Android, Mac Catalyst, Windows, Linux/GTK, tvOS (through a community MAUI backend)

Android driver commands and screen recording use System.Diagnostics.Process through the driver's internal HostProcess helper, not Xamarin.Android.Tools.ProcessUtils. Output and error streams drain concurrently; cancelling an ADB command terminates only its client, not the shared ADB server. Xamarin.Android.Tools.AndroidSdk remains required for AdbRunner device discovery and reverse-port setup.

Focus-safe capture and native dialogs

iOS Simulator full-screen screenshots use simctl, including system dialogs. CLI and Driver share resizing through macOS's built-in /usr/bin/sips, preserving logical sizing, aspect-ratio rounding and no-upscaling. The CLI supports --max-width; --scale native and --scale full bypass resizing. Resize failures warn on stderr and return the original PNG. Resampling and compression can differ from earlier SkiaSharp output.

Windows host fallback uses GDI for capture and built-in GDI+ for PNG encoding, preserving bounds, top-down BGRA order and opaque alpha. Temporary files and native resources are released after capture. Neither host path bundles SkiaSharp; in-app agents are unchanged.

AppKit screenshots prefer ScreenCaptureKit and fall back to CoreGraphics or in-process rendering without activating or reordering windows. On macOS 14.0–14.1, an attached sheet forces a parent/sheet CoreGraphics composite because ScreenCaptureKit cannot include child windows until macOS 14.2. Capture does not request screen-recording permission automatically.

The MCP native-dialog workflow detects the visible prompt, then receives promptId and buttonLabel. Before acting, the server sends a form elicitation request to the MCP host, which must present the exact app, dialog and button to the user and return explicit approval. The former caller-supplied confirmedByUser flag has been removed; it cannot prove consent. Declines, cancellations, malformed approval responses and hosts without form elicitation support result in no action. As with other MCP elicitation, the host is trusted to show the request to a human rather than approve it automatically. Tokens expire after two minutes, are scoped to the detecting MCP session, and can be used only once. Responses revalidate the target and prompt and respect the app's global mutation lease. Dialog fingerprints retain 128 bits of SHA-256 and format geometry independently of the host's locale; the one-time response token is separate from the fingerprint. macOS uses AXPress, Windows uses UI Automation Invoke, Linux uses the connected agent, and Android/iOS Simulator input is restricted to the device associated with that agent. Physical iOS and unattributed system dialogs require manual interaction. macOS requires Accessibility permission for native dialog automation.

Android verifies the hierarchy package against the focused dialog window's package and WindowManager owner UID, as resolved by the device's package manager. Before tapping, it re-reads the dialog and rejects visible windows above it that overlap its response buttons. This includes non-focusable overlays even when mFocusedApp still names the target app. Missing ownership, visibility or geometry information and non-default displays require manual interaction. This minimizes stale coordinate risks; device input is not an atomic window-targeted invocation, so callers must not use it while another actor is manipulating the device UI.

Behavior change: MacCatalystAppDriver.DismissAlertAsync and HandleAlertIfPresentAsync no longer choose a button implicitly: a null or empty label throws. The IAlertDriver signatures remain compatible with other platforms. Use an exact detected label with maui devflow ui alert dismiss on macOS; ASCII and typographic quotes are treated equivalently, and ambiguous labels are rejected.

Agent API

The in-app agent still exposes the HTTP/JSON and WebSocket API used by the CLI, MCP tools, and Microsoft.Maui.DevFlow.Driver. The server listens on loopback at http://localhost:<port>. Use the broker (port 19223), CLI, MCP tools, or AgentClient to discover the agent's dynamic port. Port 9223 is only the agent's last-resort default when no configured or broker-assigned port is available; it is not the broker port.

The current API is versioned under /api/v1/*, with streaming channels under /ws/v1/*. The endpoint table from the original Redth/MauiDevFlow repository describes the earlier unversioned API and should not be used with the Microsoft.Maui.DevFlow packages.

For application code, prefer the typed AgentClient in Microsoft.Maui.DevFlow.Driver; use the protocol documents when implementing a client in another language or integrating directly with the agent.

Native Android controls outside the MAUI tree

For a native-hosted popup that is absent from the MAUI logical tree, use AndroidAppDriver.GetAccessibilityTreeAsync() to inspect the current screen. Confirm the target package and control bounds before calling TapCoordinateAsync(x, y). Coordinates are physical screen pixels from the Android accessibility bounds, not MAUI device-independent units.

Set Serial when more than one device is connected. The coordinate tap rejects negative values and ambiguous device selection. Re-read the tree and capture the resulting screen after a tap; a completed input command is not proof that the intended action occurred.

CLI Commands

All DevFlow commands are available under maui devflow. Run maui devflow <command> --help for details.

Command Group Description
ui Visual tree, element interaction, screenshots, alerts, assertions, application menus
device fold Host-side fold/hinge capabilities, state, and verified controls for Android emulators and experimental iOS simulators
recording Start, stop, and manage screen recordings of app sessions
webview Blazor WebView automation — DOM, JS eval, navigation, input, screenshots
logs Fetch and stream application logs
network Monitor and inspect HTTP requests
storage Read/write app preferences, secure storage, discover file storage roots, and manage sandboxed app files
agent Discover and inspect connected agents (status, list, wait, diagnose)
extensions List, describe, and call app-specific DevFlow extension tools
broker Manage the agent broker (start, stop, status, log)
batch Execute command sequences from stdin
commands List all available commands (schema discovery)
mcp Start the MCP server for AI agent integration

Application menus

maui devflow ui menu list --window 1
maui devflow ui menu invoke --path "File/Save" --window 1
maui devflow ui menu invoke --key s --modifiers cmd --target native

MAUI menus follow the visible page, including navigation, tabs, flyout detail and modal pages. Invocation defaults to the first matching MAUI item, then tries the native menu only if no MAUI item matched. A disabled item (or disabled ancestor) is a failure, not permission to run a different native command. Use --window to scope MAUI path/title/key matching; native menus use the active application responder chain.

Copy paths from menu list: MAUI/AppKit title segments escape %, /, and backslash as %25, %2F, and %5C. Catalyst native paths are flat titles; fabricated hierarchical paths are not matched. Menu ids are positional and can change when menus change, so refresh the listing before invoking by id. MAUI items list all declared shortcuts in accelerators; key and modifiers retain the first shortcut. Menus on the deepest active page with definitions take precedence over its active ancestor containers. Menu invocation uses the same UI-mutation gate as other actions; containers and separators are not invokable. Prefer key plus modifiers for Catalyst. Invalid arguments return HTTP 400, missing items 404, disabled/unhandled actions 409, and unsupported backends 501. Native actions that stay inside a modal event loop return HTTP 202 with status: "dispatched" after five seconds. This acknowledges dispatch, not completion; inspect and dismiss the dialog before continuing. The client methods are AgentClient.GetMenusAsync(window) and InvokeMenuAsync(..., window: window) in the portable Client package (also available through Driver).

Layout diagnostics

# High-signal findings for an agent repair loop
maui devflow ui diagnostics --profile agent

# Include all geometric overlap observations
maui devflow ui diagnostics --profile exhaustive --minimum-severity info

# Fail CI when serious violations are present or the scan is incomplete
maui devflow ui diagnostics --profile ci --fail-on serious --json

# Continuously re-run after UI events
maui devflow ui diagnostics --watch

The ci profile independently fails incomplete scans so unavailable or budget-truncated evidence cannot produce a clean result. Use --fail-on none only when both violation and incomplete-scan exit failures should be disabled.

The same result is available through:

  • HTTP: POST /api/v1/ui/diagnostics/layout
  • Driver: AgentClient.AnalyzeLayoutAsync
  • MCP: maui_layout_diagnostics
  • Web Inspector: Data -> Layout (also opened by the toolbar's Layout button)

Results distinguish violations, observations, incomplete checks, confidence, clip causes, visual versus interaction occlusion, and permanent platform limitations. Text content is not returned by default.

Rule set 1.1 adds three managed-layout checks while retaining schema 1.0:

Rule Meaning Result
layout.constraint-violation Conflicting minimum/maximum requests, or an arranged size outside those limits by at least one untransformed layout pixel at window density Moderate violation for review
layout.desired-size-constrained The last measured desired size, with margins removed, exceeds the arranged size Informational observation, not proof of lost content
layout.child-outside-parent A child's untransformed arranged frame extends outside its direct layout parent Informational observation, not proof of clipping

Use --minimum-severity info to see the latter two rules. The Inspector's Layout dock starts with All findings; use Filters to select actionable findings, outcome, severity, confidence, or a rule. Selecting a child-outside-parent finding highlights the child and its layout parent with a distinct parent outline, not a clip outline. Lower-severity detections remain visible in summary.filtered even when their detailed findings are omitted. Existing clip, overflow and hit-test rules still establish whether content is actually lost or unreachable; the new observations do not turn intentional overlays into CI failures.

The checks use already-captured MAUI measurements and never call Measure or change the app's layout. Native-only and Blazor nodes are not treated as successful managed checks. Scroll containers are excluded from desired-size checks, and direct scroll content, transformed elements, negative margins, unknown parents and cross-window relationships are excluded from parent-frame checks. Exclusions count as not applicable, not passes; platform coverage remains explicitly partial. A sizing/constraint change invalidates the diagnostics revision even when rendered bounds have not changed.

Selected-subtree scans retain captured ancestor evidence for the selected root's parent-frame checks. Ancestors are analysis-only context: they are not counted, evaluated for findings or passes, or included in scoped overlap comparisons. Their sizing changes still invalidate stability and diagnostics revisions.

A desired-size pass requires known measurements for both axes. A partly unknown measurement is not applicable rather than a whole-rule pass. Unstable snapshots skip these baseline checks and report global incompleteness once; they do not flood the findings list with one incomplete item per element.

Sizing and layoutOverflowInsetsPhysicalPixels describe untransformed layout, while fullRegion and parentRegion are rendered highlight regions. An ancestor transform does not invalidate parent-local containment, but a finding records the coordinate-space limitation so its layout insets are not mistaken for painted edges. Existing desired-size-based content-overflow estimates use the same margin normalization, preventing contradictory findings on valid margin layouts.

Clients should read GET /api/v1/ui/diagnostics/layout/rules before requesting these rule IDs from an older agent. Older agents retain their rule set and reject unknown explicit rule IDs; existing schema-1.0 requests are unchanged.

The sample's Layout Diagnostics page has problem examples and a Use valid layout toggle for checking that these findings disappear after a correction.

Layout workspace

The original docked Layout experience is available with the current diagnostics contract: compact friendly finding rows, a detail view with measured sizing and limitations, and a coverage view listing every rule's actual support and confidence. Coverage does not invent per-element evaluated counts that the current agent does not report. Shared resources can appear under multiple parents in a MAUI tree. Ambiguous identities and their dependent subtrees are excluded with an explicit incomplete coverage limitation; they do not abort the scan or become guessed ownership.

The first opening of Layout performs one scan. Rescan and Recheck are explicit; Live is opt-in and updates after observed layout changes while this dock is visible. Hiding or collapsing the dock stops scheduled live work. Screenshot polling no longer runs layout analysis on every refresh. Returning to a previously scanned Layout tab restores its report and Copilot attachment without another scan. The toolbar's Layout state follows the selected tab and dock visibility. Selecting Layout in a collapsed dock defers scanning until it is expanded; the toolbar button expands that workspace instead of closing the dock. Nested navigation pages and side-by-side flyout/detail panes remain available in the visual tree and finding overlays rather than being treated as inactive tabs. The default scan scope uses their common ancestor so a flyout sidebar cannot silently replace the main content as the inspection target. For Shell navigation, the agent marks its current page as selected even when the tab bar is hidden. Inspector and Canvas prefer that state over retained inactive-page geometry, keeping the screenshot, overlays, and scan target aligned.

Changes mark the previous snapshot stale and remove its highlights. Navigation and reloads invalidate it even when the route and geometry are unchanged; repeated, unchanged connection snapshots do not count as navigation. A missing native event does not leave a visible workspace unchecked: lightweight frame polling compares the full tree revision, rendered state and the MAUI agent's lightweight diagnostic-input revision. Sizing requests and invalidated measurements mark the report stale even when geometry is unchanged, without running analysis during ordinary frame polling. Older or native-only agents without this optional signal retain geometry/rendered-state detection. This does not rescan diagnostics unless Live is enabled. A missing finding is not described as resolved when coverage is incomplete. Details offer Show in app, Open source when mapped, bounded Copy payload and Add to Copilot context, and confirmation before the existing project-policy suppression action. The confirmation shows the full policy path. Suppression requires a full project path from the host or an app built with MauiDevFlowIncludeProjectPath=true; a filename-only app identity never uses the broker's working directory for project policies. When the full project path is known, mapped source actions resolve project-relative XAML references to full local paths without requiring the file to be writable. Copilot context remains a redacted point-in-time snapshot, not mutation or source-write authority.

Debug builds generate XAML source maps by default, so findings can include sourceFile, sourceLine, and sourceColumn. Source-content hashes are not emitted by the diagnostics contract. Set DevFlowXamlSourceMapsEnabled=false to disable source embedding, or enable it explicitly for another configuration. Source maps embed developer file paths and XAML text and should normally remain disabled for Release/store builds. Source maps reuse MAUI's prepared XAML items regardless of target framework, including plain .NET GTK heads and macOS AppKit heads. Projects without the MAUI Controls build targets can still supply MauiXaml items for source mapping. Project-wide XAML prefixes declared with XmlnsPrefix in the app or referenced assemblies are supported.

The request privacy modes are:

  • none - no text or text length in evidence (default);
  • length - include only text length;
  • raw - include raw text explicitly.

Interaction occlusion modes are none, interactiveTargets (default), and all.

Persistent suppressions can be stored beside the project in .mauidevflow:

{
  "port": 9225,
  "layoutDiagnostics": {
    "suppressions": [
      {
        "ruleId": "layout.element-clipped",
        "elementType": "Button",
        "automationId": "ExpectedClippedButton",
        "sourceFile": "Views/Page.xaml",
        "sourceLineStart": 20,
        "sourceLineEnd": 30,
        "relatedAutomationId": "ClipHost",
        "reason": "Intentional carousel preview"
      }
    ]
  }
}

User-wide suppressions use the same suppressions shape in ~/.mauidevflow/layout-diagnostics.json. CLI, MCP, and the Web Inspector merge user and project policies before requesting a scan.

Background jobs

maui devflow ui jobs list --agent-port <port>
maui devflow ui jobs run <work-spec-uuid> --serial <android-serial> --timeout 30 --agent-port <port>
maui devflow ui jobs run com.example.sync --type processing --agent-port <port>
Surface Android WorkManager iOS BGTaskScheduler
Listing (HTTP, CLI, MCP) Requires WorkManager in the app; includes states and exact JobScheduler mappings Lists pending requests; physical device required for scheduling
CLI jobs run Forces enqueued one-time work through host-side adb and polls the exact UUID Requests a debug launch, not verified execution or completion
HTTP/MCP run Unsupported; no host-side adb in the agent Requires a Debug-built agent library and a physical device

Android jobs run matches the JobScheduler id to EXTRA_WORK_SPEC_ID read through the app's public JobScheduler API. Worker names and tags are not unique identities: shorthand is accepted only when it resolves to one WorkSpec generation. Duplicate backing jobs for that same generation (WorkManager's Android API 23 workaround) are equivalent, not ambiguous. An explicit UUID never falls back to another request, and generation changes fail instead of reporting a different run. Use --serial when multiple Android devices are connected. Before triggering, the host runner pins that serial, temporarily forwards the device-side agent port, and compares the running agent's opaque instance identity. A different device, app restart, or unavailable probe fails closed; matching package names or numeric job IDs alone are not accepted.

Host execution claims the app's mutation lease and holds a renewable transaction through adb triggering and outcome polling. Another owner, failed renewal, missing mappings, ambiguous identifiers, query errors, failed/cancelled work, and timeouts fail the command. Exit 0 means the resolved WorkSpec reached SUCCEEDED; periodic work returns to ENQUEUED rather than a terminal success, so it needs an app-specific outcome assertion. --timeout bounds target verification, triggering, and observation; cancellation releases the transaction and temporary forward, but does not cancel a worker that has already started. Older agents without identity, generation, scheduler mapping, or mutation-transaction support must be updated before the CLI can safely force work.

iOS triggering uses Apple's private debugger selector, compiled only into Debug builds of the agent library. The shipped Release-built NuGet agent does not support it, even when the consuming app is built in Debug. Release trigger requests return unsupported before scheduling work; use your app's own scheduling API if you only want to schedule. Keep source-built Debug agents and sample trigger actions out of App Store builds. Configure BGTaskSchedulerPermittedIdentifiers, the appropriate background mode, and a launch handler before app launch completes; scheduling requires a physical device and enabled Background App Refresh. The simulator cannot schedule these tasks.

On iOS, exit 0 and success: true acknowledge only the launch request. The response reports launchRequested: true, executionVerified: false, and completionVerified: false. Verify execution and completion using state recorded by your handler. Pending-request disappearance is not used as an outcome: a handler can immediately reschedule the same identifier. The iOS sample's Debug-only bgtask-simulate-launch action accepts reschedule: true to exercise that pattern; inspect bgtask-run-count and the next pending request to verify it.

DevFlow Global Options

These options apply to all maui devflow subcommands:

Option Description
--agent-port, -ap Agent HTTP port (auto-discovered via broker/.mauidevflow; falls back to 9223)
--agent-host, -ah Agent HTTP host (default: localhost)
--platform, -p Target platform (maccatalyst, android, ios, windows)
--no-json Force human-readable output

Platform Support

Platform Status
Mac Catalyst ✅
iOS Simulator ✅
Linux/GTK ✅
Android 🔄 In progress
Windows 🔄 In progress

Documentation

Development

# Open just DevFlow in your IDE
open src/DevFlow/DevFlow.slnf

# Build
dotnet build src/DevFlow/DevFlow.slnf

# Run tests
dotnet test src/DevFlow/Microsoft.Maui.DevFlow.Tests/

# GTK managed startup and dependency tests (no native GTK runtime required)
dotnet test src/DevFlow/Microsoft.Maui.DevFlow.Agent.Gtk.Tests/

Native GTK WebView tests require Linux, GTK 4.12+, WebKitGTK 6.0 and a display. Run them through the shared native test runner:

pwsh -File platforms/Linux.Gtk4/tests/run-native-tests.ps1 \
  -TestProject src/DevFlow/Microsoft.Maui.DevFlow.Agent.Gtk.Tests/Microsoft.Maui.DevFlow.Agent.Gtk.Tests.csproj \
  -TestNamespace Microsoft.Maui.DevFlow.Agent.Gtk.Tests \
  -TestClass GtkWebViewSnapshotRuntimeTests

The GTK agent and Blazor bridge reference the in-repo Linux GTK4 projects. DevFlow.slnf includes those shipping dependencies and is used by both PR validation and the official DevFlow build. publishDevFlowNuget automatically enables the Linux GTK4 publication stage and waits for it to succeed before publishing DevFlow. The DevFlow preparation step also validates the GTK agents' in-repo dependency closure against the actual shipping nuspecs and rejects missing or mismatched package versions. publishLinuxGtk4Nuget remains available for Linux-only releases.

Real app integration tests

The simulator/emulator-driven suite is separate from the fast host tests and runs automatically in integration CI as described above. For local runs, set DEVFLOW_TEST_PLATFORM to maccatalyst (or mac/catalyst), ios, tvos, android, windows, macos, gtk, or wpf. It defaults to maccatalyst on macOS and windows on Windows.

# Mac Catalyst
DEVFLOW_TEST_PLATFORM=maccatalyst dotnet test src/DevFlow/Microsoft.Maui.DevFlow.Agent.IntegrationTests/

# iOS Simulator
DEVFLOW_TEST_PLATFORM=ios DEVFLOW_TEST_IOS_VERSION=18.x dotnet test src/DevFlow/Microsoft.Maui.DevFlow.Agent.IntegrationTests/

# Android Emulator
DEVFLOW_TEST_PLATFORM=android DEVFLOW_TEST_ANDROID_API=35 DEVFLOW_TEST_ANDROID_AVD=devflow-tests-api35 DEVFLOW_TEST_ANDROID_SERIAL=emulator-5580 dotnet test src/DevFlow/Microsoft.Maui.DevFlow.Agent.IntegrationTests/

# Windows (run on a Windows machine)
DEVFLOW_TEST_PLATFORM=windows dotnet test src/DevFlow/Microsoft.Maui.DevFlow.Agent.IntegrationTests/

tvOS drives the smaller samples/DevFlow.Sample.TvOS on an Apple TV simulator (a booted one is preferred), so only its own tests apply; run them with --filter Category=TvOS. The sample uses the community Platform.Maui.TvOS backend, which is published to nuget.org only and so is not on the repo's feeds: set DEVFLOW_TEST_TVOS_BACKEND_SOURCE to a feed that has it (such as https://api.nuget.org/v3/index.json). The sample targets .NET 11 and uses Platform.Maui.TvOS 0.5.0 with scene lifecycle support for tvOS 27; the agent itself retains its .NET 10 target. No separate backend checkout is required:

DEVFLOW_TEST_PLATFORM=tvos \
DEVFLOW_TEST_TVOS_BACKEND_SOURCE=https://api.nuget.org/v3/index.json \
dotnet test src/DevFlow/Microsoft.Maui.DevFlow.Agent.IntegrationTests/ --filter Category=TvOS

For backend development, set DEVFLOW_TEST_TVOS_BACKEND_PROJECT to a local mauiplatforms/src/Platform.Maui.TvOS/Platform.Maui.TvOS.csproj instead.

For local reliability, prefer running one platform suite at a time from a given repo worktree. Android fixture selection can be pinned with DEVFLOW_TEST_ANDROID_AVD and DEVFLOW_TEST_ANDROID_SERIAL when you want the harness to use a known emulator instance.

CI sets DEVFLOW_TEST_IOS_ISOLATED=true: the fixture creates a fresh iPhone from the installed runtime's supported device types, then shuts down and deletes only that owned simulator, including after startup failure. DEVFLOW_TEST_IOS_VERSION selects the runtime. Set the isolation flag locally to avoid using an existing simulator; otherwise, the fixture prefers an available booted iPhone. The workflow pins the toolchain and runtime. Manual dispatch can select another installed runtime through ios-runtime.

Running the suite against a plain .NET app

DEVFLOW_TEST_FRAMEWORK selects which sample app the fixtures deploy: maui (default) drives samples/DevFlow.Sample, native drives the matching head under samples/DevFlow.Sample.Native. Both samples expose the same automation ids, so the bulk of the suite is shared.

Tests that assert on MAUI-specific behaviour (Shell routing, AppTheme, Essentials-backed preferences/secure-storage/sensors/device info, WebView CDP) are tagged [Trait("framework", "maui")] and must be filtered out of a native run:

# Native iOS Simulator
DEVFLOW_TEST_FRAMEWORK=native DEVFLOW_TEST_PLATFORM=ios \
  dotnet test src/DevFlow/Microsoft.Maui.DevFlow.Agent.IntegrationTests/ --filter "framework!=maui"

# Native Mac Catalyst
DEVFLOW_TEST_FRAMEWORK=native DEVFLOW_TEST_PLATFORM=maccatalyst \
  dotnet test src/DevFlow/Microsoft.Maui.DevFlow.Agent.IntegrationTests/ --filter "framework!=maui"

native is supported for android, ios, maccatalyst, and macos. There are no plain-.NET Windows, GTK, or WPF integration heads.

Running the suite against the .NET 11 community backends

The GTK, WPF, and macOS AppKit backends ship net10.0 assets (MAUI 10 compatibility) and net11.0 assets (MAUI 11 extensibility contracts). Their DevFlow samples multi-target both, and DEVFLOW_TEST_DOTNET selects which build the fixture launches: 10 (default) or 11. CI runs the gtk, wpf, and macos (maui) lanes once per version.

DEVFLOW_TEST_PLATFORM=gtk DEVFLOW_TEST_DOTNET=11 \
  dotnet test src/DevFlow/Microsoft.Maui.DevFlow.Agent.IntegrationTests/

DEVFLOW_TEST_DOTNET=11 applies to the MAUI samples only; the native samples remain net10.0.

There is also a manual GitHub Actions workflow at .github/workflows/devflow-integration.yml for running the same suite in CI.

Version

Current version is managed in eng/Versions.props.