Configuration

Configure sampling, logging, capture, pairing, artifact providers, tool registration, and guard policy with the Ansight options builder.

The .NET SDK is configured through Options.CreateBuilder().

For most development builds, start with the setup package that matches the app.

Standard .NET apps:

using Ansight;

var options = Options.CreateBuilder()
    .WithAnsightSdk()
    .Build();

Runtime.InitializeAndActivate(options);

.NET MAUI apps:

using Ansight.Maui;

builder.UseAnsight<App>();

The all-in-one setup applies FPS sampling, 400ms sampling, 120s retention, JPEG capture at 2000ms/quality-60/max-width-480, touch capture, host auto-probe, automatic loopback and remembered host connection, platform enrollment where supported, tool registration, and full tool access. Battery level telemetry stays opt-in. No bundled host connection call or generated connection resource is required. The callback runs after runtime defaults and before default tool-suite registration:

Important: Screen capture will result in an FPS drop while frames are captured, encoded, and transported. Disable session JPEG capture for trend-focused runs unless visual evidence is required.

using Ansight;
using Ansight.Tools.SecureStorage;

var options = Options.CreateBuilder()
    .WithAnsightSdk(ansight =>
    {
        ansight.WithSecureStorageTools(secure =>
        {
            secure.WithStorageIdentifier("MyApp");
            secure.AllowKeyPrefix("ansight.secure.");
        });
    })
    .Build();

If the callback registers a suite such as secure storage or preferences, the all-in-one setup skips its default registration for that suite and keeps the configured version. Full tool access is applied before the callback, so the callback can also narrow the guard with WithReadOnlyToolAccess(), WithReadWriteToolAccess(), or WithToolGuard(...).

MethodPackagePurpose
WithAnsightSdk(...)AnsightApply runtime defaults, non-MAUI tools, platform enrollment, automatic host connection, host auto-probe, JPEG capture, and full tool access.
WithAnsightDefaults()AnsightApply runtime defaults without registering tools or enabling tool access.
WithAnsightRemoteTools()AnsightRegister all non-MAUI remote tools only, skipping suites already registered on the builder.
WithAnsightMaui(...)Ansight.MauiApply the base all-in-one setup and register MAUI tools, skipping suites already registered on the builder.
UseAnsight(...)Ansight.MauiInitialize and activate Ansight from MauiAppBuilder.

See .NET Setup Packages for package selection and full examples.

Minimal Example

using Ansight;

var options = Options.CreateBuilder()
    .WithFramesPerSecond()
    .WithRetentionPeriodSeconds(600)
    .Build();

Runtime.InitializeAndActivate(options);

Default Behavior

When you use Options.Default, Ansight starts with:

  • sample frequency: 500ms
  • retention: 10 minutes
  • FPS enabled: true
  • battery level enabled: false
  • open-file-handle tracking enabled: false
  • Android JNI-reference-count tracking enabled: false
  • touch capture enabled: true
  • native crash capture enabled: true
  • default memory channels: platform defaults
  • tool registry: empty
  • tool guard: disabled
  • host auto-probe: enabled
  • host connection: automatic loopback registration plus remembered physical-device registrations
  • cellular host connections: disabled
  • unattended provisioning: disabled

An empty Options.CreateBuilder().Build() uses the same scalar defaults, memory channel defaults, host auto-probe defaults, and host connection defaults, but FPS remains disabled until you call WithFramesPerSecond() or an all-in-one setup extension.

Validation clamps important values:

  • sample frequency is kept between 200ms and 2000ms
  • retention is kept between 60s and 3600s
  • JPEG capture interval is kept at 250ms or higher
  • JPEG quality is kept between 1 and 100
  • JPEG maxWidth is clamped to 8192
  • touch move distance thresholds must be finite and non-negative
  • touch move FPS thresholds must be non-negative

Builder Methods

MethodPurpose
WithSampleFrequencyMilliseconds(ushort)Set the telemetry sampling cadence.
WithFramesPerSecond()Enable FPS tracking at startup.
WithBatteryLevel()Enable battery level tracking at startup when the platform supports it.
WithoutBatteryLevel()Disable battery level tracking.
WithOpenFileHandleTracking() / WithoutOpenFileHandleTracking()Toggle process open-file-handle sampling on reserved channel 7.
WithJniReferenceCountTracking() / WithoutJniReferenceCountTracking()Toggle Java.Interop JNI-reference sampling on Android channel 6.
WithRetentionPeriodSeconds(ushort)Set how long metrics and events remain buffered.
WithAdditionalChannels(IEnumerable<Channel>)Replace the custom channel collection.
AddAdditionalChannel(Channel)Add one custom channel.
WithDefaultMemoryChannels(DefaultMemoryChannels)Replace the built-in memory channel flags.
WithoutDefaultMemoryChannels(DefaultMemoryChannels)Remove selected built-in memory channels.
WithAdditionalLogger(ILogCallback)Forward Ansight logs to your logger.
WithBuiltInLogger()Use the built-in console logger.
WithTools(IEnumerable<ITool>)Replace the registered tool collection.
AddTool(ITool)Add one tool.
AddTools(IEnumerable<ITool>)Add multiple tools.
ContainsTool(string)Check whether a tool id is already registered on the builder.
AddRuntimeFeature(IRuntimeFeature)Add or replace one package-owned runtime extension by stable id.
ContainsRuntimeFeature(string)Check whether a package-owned runtime feature is registered.
WithArtifactProviders(IEnumerable<IArtifactProvider>)Replace the registered artifact provider collection.
AddArtifactProvider(IArtifactProvider)Add one artifact provider and register the core artifact tools.
AddArtifactProviders(IEnumerable<IArtifactProvider>)Add multiple artifact providers and register the core artifact tools.
ContainsArtifactProvider(string)Check whether an artifact provider id is already registered on the builder.
WithSessionJpegCapture(...)Enable periodic live-session JPEG capture.
WithSessionJpegCapture(SessionJpegCaptureOptions)Supply a fully populated JPEG capture object.
WithoutSessionJpegCapture()Disable live-session JPEG capture.
WithTouchCapture(...)Enable app-local touch input capture while the runtime is active.
WithTouchCapture(TouchCaptureOptions)Supply a fully populated touch capture object.
WithoutTouchCapture()Disable app-local touch input capture.
WithCrashCapture(CrashCaptureOptions?) / WithoutCrashCapture()Configure or disable durable native crash capture and next-launch delivery.
WithToolGuard(ToolGuard)Set an explicit guard policy.
WithToolsDisabled()Disable tool discovery and execution.
WithReadOnlyToolAccess()Set maximum tool policy to Read.
WithReadWriteToolAccess()Set maximum tool policy to Write.
WithAllToolAccess()Set maximum tool policy to Critical.
WithHostAutoProbe(HostAutoProbeOptions?)Enable or customize background reconnect probing.
WithoutHostAutoProbe()Disable background reconnect probing.
WithHostConnection(HostConnectionOptions?)Replace the runtime-owned host connection configuration.
ConfigureHostConnection(Action<HostConnectionOptions>)Mutate the host connection configuration inline.
WithHostConnectionDiscoveryPort(int)Override the UDP discovery port used for host connection bootstrap.
WithCellularHostConnections(bool)Permit or reject host connections over a cellular network path. Defaults to rejected.
WithUnattendedProvisioning(bool)Opt into native launch-time test-runner enrollment. Defaults to disabled.
WithHostConnectionProfileRetention(TimeSpan)Set how long remembered host profiles remain valid.
Build()Validate and produce the final Options instance.

Package-specific tool registration extensions are added by optional tool packages when you use Ansight.Core directly. The Ansight and Ansight.Maui all-in-one packages reference those tool packages for you.

Use AddTool(ITool) or AddTools(IEnumerable<ITool>) for app-specific tools that you implement yourself. See Custom Tools for the full custom-tool pattern.

Use artifact providers when app-specific output should be discovered and downloaded as a file or stream. See Artifacts for the provider model and request flow.

Runtime Feature Extensions

Separate packages can initialize an SDK extension with AddRuntimeFeature(...). An IRuntimeFeature has a stable, case-insensitive id and receives the newly created IRuntime once:

sealed class ExampleRuntimeFeature : IRuntimeFeature
{
    public string Id => "example.runtime-feature";

    public void Initialize(IRuntime runtime)
    {
        // Attach package-owned behavior to this runtime instance.
    }
}

var options = Options.CreateBuilder()
    .AddRuntimeFeature(new ExampleRuntimeFeature())
    .Build();

Adding another feature with the same id replaces the earlier registration. Initialization failures are logged and isolated from core runtime startup. Annotated Feedback uses this extension point for its opt-in service.

Tool Suite Extension Methods

Common entry points:

ExtensionPackageNuGetPurpose
WithMauiTools()Ansight.Tools.MauiNuGetRegister .NET MAUI page, visual-tree, element, binding, resource, navigation, layout, handler, theme, and binding-context tools.
WithVisualTreeTools()Ansight.Tools.VisualTreeNuGetRegister live UI hierarchy and screenshot tools.
WithReflectionTools(Action<ReflectionToolsOptionsBuilder>)Ansight.Tools.ReflectionNuGetRegister the reflection tools and configure traversal and member visibility.
WithDatabaseTools()Ansight.Tools.DatabaseNuGetRegister SQLite discovery, schema, and query tools.
WithFileSystemTools(Action<FileSystemToolsOptionsBuilder>)Ansight.Tools.FileSystemNuGetRegister sandbox file access and additional tagged roots.
WithPreferencesTools(Action<PreferencesToolsOptionsBuilder>)Ansight.Tools.PreferencesNuGetRegister preference access with store and key restrictions.
WithSecureStorageTools(Action<SecureStorageToolsOptionsBuilder>)Ansight.Tools.SecureStorageNuGetRegister secure-storage access with storage selection and key allow-lists.

Memory Channels

DefaultMemoryChannels is a flags enum:

  • ManagedHeap
  • NativeHeap
  • ResidentSetSize
  • PhysicalFootprint
  • All

Platform defaults:

  • Android: ManagedHeap | NativeHeap | ResidentSetSize
  • iOS and Mac Catalyst: ManagedHeap | PhysicalFootprint
  • other targets: ManagedHeap

Battery Level Telemetry

Battery level telemetry is off by default. Enable it when battery state is useful session context:

var options = Options.CreateBuilder()
    .WithBatteryLevel()
    .Build();

When supported, Ansight records battery charge percentage on the reserved Battery Level channel at the configured sample frequency. Android, iOS, and Mac Catalyst currently expose platform battery readers; other targets skip battery samples.

Use WithoutBatteryLevel() to turn the channel off in shared setup code.

Host Auto-Probe Options

HostAutoProbeOptions controls background reconnect behavior while the runtime is active.

PropertyMeaningDefault
EnabledWhether automatic probe/reconnect runs at all.true
InitialDelayDelay after activation before the first probe.1s
ProbeIntervalDelay between probe attempts while disconnected.5s
ReconnectDelayDelay before probing resumes after a disconnect.10s
ClientNameOptional client name override for automatic connects.null

If you do not want automatic reconnect behavior, call:

var options = Options.CreateBuilder()
    .WithoutHostAutoProbe()
    .Build();

Host Connection Options

HostConnectionOptions controls registered reconnect, UDP enrollment, host retry, and explicit scanner payload handling.

PropertyMeaning
SavedConfigPathOverride the path used to store the saved host config.
DiscoveryPortOptional UDP discovery port override.
ConfigReaderPlatform-owned reader for file or QR payload input. Ansight.Pairing supplies the default QR reader.
AllowCellularConnectionsWhether QR, saved-profile, and explicit connections may use a cellular path. Defaults to false.
AllowUnattendedProvisioningWhether a native test runner may supply a one-use invite at process launch. Defaults to false.

The normal flow needs no bundled resource. Use ConfigReader only to integrate an SDK-owned or app-owned scanner.

Cellular connectivity can consume mobile data and does not change the clear-text local-development transport. Enable it only for intentional mobile-data or personal-hotspot workflows:

var options = Options.CreateBuilder()
    .WithCellularHostConnections()
    .Build();

For unattended physical-device tests, call WithUnattendedProvisioning() only in a trusted development/test variant. The native iOS bridge reads ANSIGHT_ENROLLMENT_PAYLOAD; the Android bridge reads the ai.ansight.bootstrap.payload Activity intent string extra. The value is a one-use bearer invite: do not log it or place it in source control. A successful registration remains in platform-private app storage.

Crash Capture Options

Native crash capture is enabled by default and writes a bounded app-private outbox for next-launch delivery:

var options = Options.CreateBuilder()
    .WithCrashCapture(new CrashCaptureOptions
    {
        HostHandoffEnabled = true,
        OfflineCaptureAttachmentEnabled = true,
        MaximumPendingReports = 8,
        RetentionDays = 7,
        MaximumBreadcrumbs = 64,
        MaximumTraceBytes = 1_048_576
    })
    .Build();

Use WithoutCrashCapture() when the app must not persist crash reports. See Crash Capture for validated bounds, framework candidates, delivery, and privacy.

Session JPEG Capture Options

Use JPEG capture only when you actually need live visual artifacts. See JPEG Screenshots for the full split between periodic session capture and the on-demand ui.get_screenshot tool.

Important: Screen capture will result in an FPS drop while frames are captured, encoded, and transported. Use conservative settings, and disable capture for trend-focused runs unless visual evidence is required.

var options = Options.CreateBuilder()
    .WithSessionJpegCapture(intervalMilliseconds: 2000, quality: 60, maxWidth: 720)
    .Build();

SessionJpegCaptureOptions properties:

PropertyMeaningDefault from WithSessionJpegCapture()
IntervalMillisecondsCapture interval while a pairing session is open. Values below 250ms are clamped.2000
QualityJPEG quality from 1 to 100.70
MaxWidthOptional output width cap. null keeps full width. Values above 8192 are clamped.720
CaptureGpuBackedSurfacesHigher-fidelity Apple capture path for Metal, SceneKit, and similar surfaces.true
ModeScreenshotOnly, ScreenshotAndVisualTree, or ScreenshotWithVisualTreeOnTouch.ScreenshotOnly
CaptureKeyboardPresenceRecord keyboard presence only; never contents or dimensions.false

This feature captures, encodes, and transports frames while the app is running. Keep it conservative.

Touch Capture Options

Touch capture is enabled by default. Customize it when you want different move or cancellation behavior in local player session review and CLI touch inspection:

var options = Options.CreateBuilder()
    .WithTouchCapture(
        captureMoveEvents: true,
        captureCancelEvents: true,
        moveCaptureDistanceThreshold: 4,
        moveCaptureFramesPerSecond: 15)
    .Build();

WithTouchCapture() records app-window coordinates while the runtime is active and streams them over an open host connection as touch input records. Touch records are not written to IDataSink, and they are separate from metrics and timeline events.

TouchCaptureOptions properties:

PropertyMeaningDefault
CaptureMoveEventsInclude drag, scroll, and other move updates in addition to down/up events.true
CaptureCancelEventsInclude platform cancellation events.true
MoveCaptureDistanceThresholdMinimum movement, in logical display units, before another move event is recorded. Set 0 to disable distance filtering.4
MoveCaptureFramesPerSecondMaximum move capture cadence per pointer. Set 0 to disable FPS filtering.15

Android, iOS, and Mac Catalyst currently have platform capture sessions. Other targets accept the option but do not emit touch records.

Use WithoutTouchCapture() to explicitly disable touch capture in shared setup code.

Tool Guard Policy

Registering tools is not enough on its own. You must also choose a guard.

Built-in guards:

  • ToolGuard.Disabled
  • ToolGuard.ReadOnly
  • ToolGuard.ReadWrite
  • ToolGuard.FullAccess

Critical tools stay blocked unless you use WithAllToolAccess() or build a custom ToolGuard whose maximum policy is Critical.

Reflection object inspection, writes, and invocation are Critical because they can disclose sensitive state or execute arbitrary app code. The current reflection options surface controls traversal and member visibility; it does not include per-member allow-lists.

Example: Core-Only Telemetry + Pairing + Tools

using Ansight;
using Ansight.Tools.Reflection;
using Ansight.Tools.VisualTree;

var session = new DebugSessionViewModel();

var sessionRoot = ReflectionRootRegistry.Register(
    "session",
    session,
    new ReflectionRootMetadata("Current Session")
    {
        Description = "Debug session view model",
        Hints = ["debug", "session"]
    },
    ReferenceType.Strong);

var options = Options.CreateBuilder()
    .WithFramesPerSecond()
    .WithRetentionPeriodSeconds(900)
    .WithSessionJpegCapture(intervalMilliseconds: 3000, quality: 60, maxWidth: 720)
    .WithVisualTreeTools()
    .WithReflectionTools(reflection =>
    {
        reflection.WithAssemblyTraversalMode(ReflectionAssemblyTraversalMode.AllowAll);
        reflection.WithNamespaceTraversalMode(ReflectionNamespaceTraversalMode.AllowAll);
        reflection.WithDefaultMemberVisibility(ReflectionMemberVisibility.PublicOnly);
    })
    .WithReadOnlyToolAccess()
    .Build();

Runtime.InitializeAndActivate(options);