/shiny:shiny-appdevicebridgefrom shiny
Generate code using Shiny.AppDeviceBridge, device bridges on your app's own Shiny.Net.HttpServer that also host a web app (Blazor WebAssembly, React, Vue, any static build) inside a .NET MAUI app on Android, iOS, Mac Catalyst, Windows and the maui-labs macOS and Linux heads — served from a loopback HTTP server, updated over the air from a signed release server, GitHub releases or a provider of your own, and given device access through bridges with typed C# and TypeScript clients
Ships in shiny. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
You are an expert in Shiny.AppDeviceBridge. Use this skill when the user hosts a web app inside a .NET MAUI app, calls device features from that web app, updates it over the air, or writes a bridge of their own.
Documentation: https://shinylib.net/appdevicebridge
Shiny.AppDeviceBridge is the bridge server, on the app's own Shiny.Net.HttpServer:
http.AddAppDeviceBridge(bridge => …) on the ShinyHttpServerBuilder from services.AddShinyHttpServer(http => …).
The server's address, port, TLS, limits, authentication and the app's own endpoints are configured on that same
builder; AppDeviceBridgeOptions holds only the bridges' concerns (app id, mount points, allowed hosts, the bridge
policy), set with bridge.Configure(o => …). UseAppDeviceBridge in MAUI calls AddShinyHttpServer for you.MauiAppBuilder or ShinyHttpServerBuilder.
AppDeviceBridgeBuilder has Http, Services, Options, Configure(Action<AppDeviceBridgeOptions>) and
AddBridge<TBridge>(); creating one registers the bridge server with the built-in host, settings, files and invoke
bridges. In MAUI, both UseAppDeviceBridge overloads — (bridge => …, webApp => …) with a web app, (bridge => …) without — hand out a
MauiAppDeviceBridgeBuilder (adds Maui, the MauiAppBuilder) and do the host work once: UseShiny() on every head (guarded, so an
app that already calls it is fine), Shiny.Core's IBattery and IConnectivity, and the app's dispatcher registered as IWebAppMainThread. Never generate
UseShiny() for the bridges. Calling UseAppDeviceBridge again adds to the same server.net11.0), Gps
(GPS/motion), Geofencing, RegionGeofencing, Notifications, Push, Wearables, LiveActivities, InAppPurchases, GameCenter, CallDirectory, AgeSignals, Biometrics, Nfc, Vpn, Speech, Audio, AiConversation, ScreenRecorder, Calendar, Contacts, Health, RpiCamera, Tunnel. They reference
only Shiny.AppDeviceBridge; their extensions are generic (TBuilder AddGpsBridge<TBuilder>(this TBuilder bridge) where TBuilder : AppDeviceBridgeBuilder) and return the builder they were given, so they chain on either builder and
run headless.Shiny.AppDeviceBridge.Maui itself. They reference
Shiny.AppDeviceBridge.Maui, extend MauiAppDeviceBridgeBuilder, and do their own MAUI registration through
bridge.Maui (camera control, tray icon, controls, Essentials, lifecycle events). The app calls none of that.AllowWebPermissions and UseTrafficMonitor stay on MauiAppBuilder; AddTrafficRecorder stays on
ShinyHttpServerBuilder.navigator.geolocation with AllowWebPermissions(WebAppWebPermissions.Geolocation)
over the GPS bridge. It works on every head except Linux, including macOS (AppKit), where the host answers it from
CoreLocation. Declare NSLocationWhenInUseUsageDescription on Apple platforms.AppDeviceBridgePolicies.Bridges, which the bridges enforce themselves.o.Server, o.ConfigureServer, o.AddAuthentication or
o.AddAuthorization on AppDeviceBridgeOptions — they do not exist. Use the builder.Shiny.AppDeviceBridge.WebView adds the web app host — the UseAppDeviceBridge(bridge => …, webApp => …)
overload (bridge delegate first, both required; http.AddAppDeviceBridge(bridge => …, webApp => …) without MAUI).
One delegate registers the bridges alone; a second configures the web app. It serves the web app straight from a
zip (the baseline or a signed download), shown in WebAppHostView / WebAppHostPage. The WebView trades a
one-time launch token for an HttpOnly cookie, which the host adds to the bridge policy.
Only the entry document gets Cache-Control: no-cache; the host sets no cache header on any other file.
WebAppHostOptions.OnPrepareResponse runs after that for every file (an app's own cache policy for LAN/tunnel
callers), and ContentTypeOverrides maps extensions (with the dot) to content types.ServeWebAppRemotely = true; a browser on the same device only with ServeWebAppLocally = true. Neither option
opens the bridges — that is AuthorizeBridges. Never generate a custom middleware to let a local browser in.webApp.Variants("mobile", "desktop") plus
webApp.SelectVariant = ctx => … (cookie, Sec-CH-UA-Mobile, User-Agent), with one zip holding mobile/ and
desktop/. Never generate a second mount point, a redirect to /desktop, or two web app hosts for this. The
first variant is the default; a null/unknown/throwing selector falls back to it.await http.StopAsync(); http.Options.Address = …; http.Options.Port = …; await http.StartAsync(); on the app's HttpServer. Origin, the WebView session and an open
tunnel follow on their own; never re-register the bridges or rebuild the host to change the port./_bridge/{name} (the prefix is configurable) plus one Server-Sent
Events stream. One package per bridge, one extension method each on the bridge builder. Host, settings, files and
invoke are built in. AddAppBridge() (app/…, over Shiny.Core) ships with Shiny.AppDeviceBridge; AddDeviceBridge()
(device/…, over MAUI Essentials) AddSensorsBridge() (/_bridge/sensors) and AddPasskeysBridge(...) (/_bridge/passkeys) ship with Shiny.AppDeviceBridge.Maui.GET /_bridge/events?topics=a,b opens it; the first event,
bridge.stream, carries the id for PUT /_bridge/events/{id} { "topics": [...] }. The host runs each topic's
native source only while a stream names it, and unhooks it when the page drops it, disconnects, or the source throws
(bridge.error { event, message }). The typed clients manage topics — never hand-write new EventSource(...) in a
page that has them.409 not_listening without a listener for their result event, and
stop by themselves once it has none; each sensor stops once its event has none. await the subscription (it
resolves once the host is delivering), then start.fetch("/_bridge/…") or JSON-object bodies in page code;
use the bridge's client — C# for Blazor, TypeScript for everything else.builder
.UseMauiApp<App>()
.UseAppDeviceBridge(
bridge => bridge
.Configure(o => o.AppId = "field-app") // AppId, BasePath, AllowedHosts, AuthorizeBridges
.AddAppBridge()
.AddDeviceBridge()
.AddGpsBridge()
.AddGeofenceBridge()
.AddCalendarBridge()
.AddPhotosBridge()
.AddFoldersBridge(),
webApp =>
{
webApp.UseBaseline(typeof(App).Assembly, "webapp.zip"); // offline, no update provider needed
// webApp.UpdateProvider = new ReleaseServerUpdateProvider(new Uri("https://api.example.com/webapps"), "-----BEGIN PUBLIC KEY-----…");
// webApp.UpdateProvider = new GitHubReleasesUpdateProvider("https://github.com/acme/field-app");
}
);
// No web app, bridges only: the other overload, with just the bridge delegate.
// builder.UseAppDeviceBridge(bridge => bridge.Configure(o => o.AppId = "kiosk").AddGpsBridge());
// A head adding its own bridges (desktop only, say) adds to the same server:
// builder.UseAppDeviceBridge(bridge => bridge.AddTrayIconBridge());
// The server itself — address, auth, the app's own endpoints — on its builder, in any order:
builder.Services.AddShinyHttpServer(http =>
{
http.Options.Address = IPAddress.Any;
http.AddAuthentication().AddApiKey(k => k.AddKey(key, "kiosk"));
http.Configure(server =>
{
server.UseAuthentication();
server.UseAuthorization();
server.MapGet("/api/orders", ctx => …).RequireAuthorization();
});
}, autoStart: false); // MAUI runs no hosted services; UseAppDeviceBridge starts the server
public class App : Application
{
protected override Window CreateWindow(IActivationState? state) => new(new WebAppHostPage());
}
Updates come from webApp.UpdateProvider (an IUpdateProvider): ReleaseServerUpdateProvider(uri, publicKey) for the
signed ASP.NET Core release server (Channel for prereleases), GitHubReleasesUpdateProvider("https://github.com/owner/repo")
for GitHub releases (AssetName, IncludePrereleases, TagPrefix, Token, RequiredWhen), or a class of the app's
own: CheckAsync(UpdateRequest request, ct) — request.HostVersion, request.AppVersion, request.Culture — returns an
UpdateOffer(UpdateInfo? WebApp, HostUpdateInfo? Host) (UpdateOffer.None = nothing newer; derive UpdateInfo to carry a
download URL), DownloadAsync(update, ct) returns the zip stream, and the optional GetDownloadRequest(update) returns an
UpdateDownloadRequest(uri, headers) for background transfers (default null = in-process). The host enforces newer-only, the
size/Sha256 when given, and the archive opening; an exception is offline, InvalidDataException rejects. Never
generate GetUpdateInfoAsync (removed), webApp.UpdateServer, PublicKey, Channel or HttpMessageHandlerFactory —
those don't exist.
Store policy. Over-the-air web updates are for fixes, content and refinements within the app's reviewed purpose
(Apple DPLA 3.3.1(B), Google Play's WebView exemption, Microsoft Store 10.2.2). Never generate hidden or dormant features
switched on after review (Apple 2.5.19). The Mac App Store (macOS and Mac Catalyst heads) is stricter
(2.4.5(iv) and (vii)): fixes only, or leave UpdateProvider unset in that build. Microsoft Store games and Xbox
products must update only through the Store (10.2.5): no UpdateProvider there. See https://shinylib.net/appdevicebridge/faq/.
The splash screen. WebAppHostView shows a splash until the page posts POST /_bridge/host/ready
(IHostBridge.ReadyAsync() / new HostBridge().ready(); the Blazor client sends it automatically) or PageReadyTimeout
(15 s) passes; WaitForPageReady = false hides it on WebView navigation instead. A required web app update installs on the
splash with version, release notes and progress; if it fails, the splash stops with the error and Try again
(BlockOnRequiredUpdateFailure, default true). A required native app update stops the splash with a message and
Update (store). Customize with SplashTemplate (a DataTemplate bound to WebAppSplashContext: Message,
ReleaseNotes, HasReleaseNotes, UpdateVersion, Progress, IsProgressVisible, IsBusy, IsStopped, CanRetry,
RetryCommand, CanOpenStore, OpenStoreCommand, HostUpdate, State) and SplashText (the words). Outside the view,
StartAsync() throws WebAppHostUpdateRequiredException (state HostUpdateRequired) or WebAppUnavailableException.
Native app updates. Release server app.json → "hosts": { "ios": { "minimumVersion", "latestVersion", "storeUrl", "releaseNotes" }, "*": { … } } (WebAppPolicy.Hosts, WebAppHostPolicy). Below minimum = required (splash stops, no web
download); below latest = optional (page sees HostInfo.StoreUpdate, calls IHostBridge.OpenStoreAsync() /
POST host/open-store). The store opens via Shiny IAppStore when registered (AddAppBridge(store => store.AppleAppId = …)),
else the storeUrl (https or a store scheme only), or webApp.OpenStore = update => …. A requirement is remembered offline.
Release notes are localized: the check sends culture (webApp.Culture, default CurrentUICulture); releaseNotes is a
string or { "*": "…", "fr": "…" } (WebAppLocalizedText, resolves culture → parent → * → first).
Background updates — Shiny.AppDeviceBridge.AutoUpdate: bridge.AddWebAppAutoUpdate(o => { o.RequiredInternetAccess = InternetAccess.Unmetered; o.RequireCharging = false; o.UseMeteredConnection = true; }). A Shiny.Jobs job checks; new releases
(optional or required) download as Shiny.Net.Http background transfers, are verified, and are served next launch. Shares one
transfer manager with AddHttpTransfersBridge in either order. iOS: BGTaskSchedulerPermittedIdentifiers (com.shiny.jobnet),
processing mode, forward HandleEventsForBackgroundUrl; Android: FOREGROUND_SERVICE + FOREGROUND_SERVICE_DATA_SYNC.
Custom downloader: implement IWebAppUpdateDownloader and finish with WebAppHost.InstallDownloadedAsync(update, file).
UseAppDeviceBridge listens on loopback port 5780 unless the app sets a port of its own.services.AddShinyHttpServer(http => http.AddAppDeviceBridge(bridge => bridge.Configure(o => …).AddRpiCameraBridge().AddTunnel().AddBridge<ClipboardBridge>())).
A non-MAUI web host is the same overload on the server's builder: http.AddAppDeviceBridge(bridge => …, webApp => …).AddGps(), AddBluetoothLE(),
AddBeaconRanging() and so on.501; IHostBridge.GetInfoAsync() lists every bridge with
IsSupported.127.0.0.1 on Android and NSAllowsLocalNetworking on Apple platforms.A native call — gps, geofence, push.received, wearables.message, hub:{name}, tray.menu, … — goes to the page
only while it's open, listening and accepts within PageAcceptTimeout (2 s). Otherwise it's not handled
(WebAppInvocationResult.NotHandled, Handled == false) and nothing in the web app runs; a late accept is refused.
Background work is the app's own native code, the usual MAUI way: a Shiny delegate (IGpsDelegate,
IGeofenceDelegate, IPushDelegate, …) or a Shiny IJob (services.AddJob<T>()). Shiny runs every registered
delegate, so the app's runs alongside the bridge's, page open or not. Generate that when the user wants something to
happen with the app backgrounded or closed.
// in the MAUI app, next to AddGpsBridge(): runs whether or not a page is open
services.AddGps<TripGpsDelegate>();
sealed class TripGpsDelegate(TripStore trips) : IGpsDelegate
{
public Task OnReading(GpsReading reading) => trips.AppendAsync(reading);
}
WebAppInvoker.IsPageListening(name), or calls invoker.InvokeAsync(...) itself and acts when !result.Handled.background.js, appdevicebridge.on(...), WebAppHostOptions.BackgroundScript, AddBackgroundHandler,
IWebAppBackgroundHandler, BackgroundHandlerTimeout, WebAppInvocationTarget, AddWebAppJob, job:{name} calls,
JobRun or Shiny.AppDeviceBridge.Jobs — all removed. Nothing downloaded runs outside the WebView.| Package | Registration (on the bridge builder) | Client package / interface |
|---|---|---|
| built in | (always) | Shiny.AppDeviceBridge.Client: IHostBridge, ISettingsBridge, IFilesBridge, ILinksBridge |
Shiny.AppDeviceBridge (the server) | AddAppBridge(store => store.AppleAppId = …, startup => startup.Arguments.Add(…)) | Shiny.AppDeviceBridge.Client: IAppBridge (AppJsonContext) — info, orientation, screen (app.screen), settings, store (Shiny.AppStore's IAppStore; 501 unless store is passed; OpenReviewPageAsync), launch at login (Shiny.Core's IAppStartupInstaller; 409 startup_failed), battery (app.battery carries BatteryInfo with energy saver) and connectivity, from Shiny.Core's IPlatform, IScreenInfo, IBattery and IConnectivity. No MAUI; a host without MAUI calls services.AddBattery() / AddConnectivity() itself |
Shiny.AppDeviceBridge.Maui | AddDeviceBridge(), AddSensorsBridge(), AddPasskeysBridge("example.com") (relying party ids required; each needs the app's domain association — Apple webcredentials: + AASA, Android assetlinks.json) | Shiny.AppDeviceBridge.Client: IDeviceBridge (DeviceJsonContext) — browser (http/https/mailto/tel only), map, share (text or file roots, ≤ 20), haptics, vibrate (≤ 5 s), keep-awake (PUT 501 where it does not hold), clipboard (≤ 1 MB), over MAUI Essentials, each 501 alone where missing; ISensorsBridge — start a sensor with a speed and MinIntervalMs, readings only as events (OnCompassAsync, …), each stopped once nothing listens to its event; IPasskeysBridge (PasskeysJsonContext) — WebAuthn passkeys, iOS / Mac Catalyst / Android / Windows, 501 on AppKit and Linux; see Passkeys below |
.Gps | AddGpsBridge(), AddMotionActivityBridge(), AddGeocodingBridge() | IGpsBridge, IMotionBridge, IGeocodingBridge (GpsJsonContext): GPS on Android, iOS, Mac Catalyst, macOS (AppKit), Windows and Linux (GeoClue2 through Shiny.Gps.Linux, registered by AddGpsBridge() only on Linux; to set GeoClue's desktop id call services.AddLinuxGps(o => o.DesktopId = "com.mycompany.myapp") before the bridge, which keeps it), 501 elsewhere; motion on Android, iOS, Mac Catalyst only. ReverseGeocodeAsync(latitude, longitude) returns Placemarks from the platform geocoder (MapKit on iOS/Mac Catalyst/macOS, Android's Geocoder) or OpenStreetMap's Nominatim everywhere else, so it works on every platform; services.AddGeocoding(o => o.BaseUri = …) before the bridge points Nominatim at your own server. It needs network but no location permission, and fails with 503 geocoder_unavailable when offline. Address → position is the Maps package's IDirectionsBridge.GeocodeAsync, not this |
.Geofencing | AddGeofenceBridge() | IGeofencesBridge (GeofencingJsonContext) |
.RegionGeofencing | AddRegionGeofenceBridge(cfg => cfg.AddGeocoderRegionSet(name, GeocoderRegionLevel.X) / .AddDocumentRegionSet<T>(name, idSelector, nameSelector, withinMeters:, filter:) / .AddNorthAmericanRegions() / .AddNorthAmericanCities(withinMeters:) / .AddRegionSet(name, IRegionSource), o => { o.UseDelegate<T>(); o.RegionSerializerOptions; }) | IRegionGeofencesBridge (RegionGeofencingJsonContext): GetStatusAsync, RequestAccessAsync, StartAsync, StopAsync, GetCurrentAsync, OnChangeAsync (regiongeofence.change; native call regiongeofence). Backed by Shiny.Geofencing.Regions; region sets are registered in C# only, and the app must not also call AddRegionGeofencing. Document sets (AddDocumentRegionSet, AddNorthAmerican*) need the app to reference Shiny.Geofencing.Regions.DocumentDb and register a SQLite store with the geometry mapped (MapSpatialProperty / MapNorthAmericaData(), plus AddNorthAmericaSeeder() for the dataset). region: a geocoder set's placemark always; anything else only through o.RegionSerializerOptions metadata (pass the store's JsonSerializerOptions), null without it. start: 409 geofence_refused. Shares Shiny.Gps' listener with the GPS bridge. Android, iOS, Mac Catalyst; 501 elsewhere |
.BluetoothLE | AddBluetoothLEBridge() | IBluetoothLEBridge |
.Beacons | AddBeaconsBridge(BeaconFeatures.All, options): pass flags to register only some features; a feature left out, or one the platform reports NotSupported (iBeacon ranging and monitoring on macOS), answers 501 | IBeaconsBridge (BeaconsJsonContext): ranging and Eddystone scans need their event listened to first (OnBeaconAsync, OnEddystoneAsync), otherwise 409 not_listening, and stop with the last listener. Monitoring transitions go to OnRegionAsync and the beacon native call |
.Obd | AddObdBridge(); AddObdVirtualAdapter(IObdVirtualAdapter) adds a non-hardware adapter (emulator, store-review demo car: Id, Name, IsAvailable, CreateTransport() → Shiny.Obd IObdTransport) that every scan lists and the page connects to by Id as peripheralUuid | IObdBridge |
.Printers | AddPrintersBridge(o => o.NetworkPorts.Add(9200)) — PrintersBridgeOptions.NetworkPorts (9100–9102); registers BLE, mDNS and the PDF renderer itself | IPrintersBridge (PrintersJsonContext) + the PrintElements builder — ESC/POS / TSPL receipt printers over BLE or TCP; see Printing below |
.Printing | AddPrintingBridge(o => o.MaxFileBytes = …) — PrintingBridgeOptions: MaxJsonBytes (16 MB), MaxFileBytes (512 MB) | IPrintingBridge (PrintingJsonContext) — the OS print dialog / spooler for PDF, image, HTML; see Printing below |
.Wifi | AddWifiBridge(hotspot) | IWifiBridge |
.Discovery | AddDiscoveryBridge(protocols) | IDiscoveryBridge |
.Hubs | AddHubsBridge(server => server.Http(o => o.DynamicServiceTypes.Add("_myapp._tcp"))) — Universal Hubs 3's own AddUniversalServer builder (call it nowhere else) | IHubsBridge + the page-side WebAppHub base class (AddWebAppHub<THub>(new(name) { ServiceType, CharacteristicUuid })) — Universal Hubs (Wi-Fi, BLE, Multipeer, Nearby) whose logic is the web app's; see Hubs below |
.Push | AddPushBridge() | IPushBridge |
.Wearables | AddWearablesBridge(o => o.Folder = "watch") — WearablesBridgeOptions: Root (data), Folder (wearables), RegisterWearableService (on) | IWearablesBridge — the companion Apple Watch / Wear OS app via Shiny.Wearables 5.9; iOS and Android only, 501 elsewhere |
.LiveActivities | AddLiveActivitiesBridge(o => o.ChannelName = "Deliveries") — Shiny's LiveActivityOptions; iOS also needs <ShinyLiveActivityWidget>true</ShinyLiveActivityWidget> | ILiveActivitiesBridge — iOS Live Activities and Android Live Updates |
.InAppPurchases | AddInAppPurchasesBridge() — registers AddInAppPurchases<WebAppPurchaseDelegate>(); keeps an app's own delegate | IInAppPurchasesBridge — App Store / Google Play purchases via Shiny.Mobile.InAppPurchases 5.9; iOS and Android only, 501 elsewhere; see In-app purchases below |
.GameCenter | AddGameCenterBridge(o => o.AddAchievement(key, appleId, googleId, totalSteps).AddLeaderboard(key, appleId, googleId)) — Shiny's GameCenterOptions; an app's own AddGameCenter wins | IGameCenterBridge — Game Center / Play Games via Shiny.GameCenter; Apple platforms and Android, 501 elsewhere; see Game center below |
.CallDirectory | AddCallDirectoryBridge(o => o.DefaultCountryCode = 44) — Shiny's CallDirectoryOptions; iOS also needs <ShinyCallDirectoryExtension>true</ShinyCallDirectoryExtension> + <ShinyCallDirectoryAppGroup> | ICallDirectoryBridge — call blocking / caller ID via Shiny.Mobile.CallDirectory; iOS and Android 10+, 501 elsewhere; see Call directory below |
.AgeSignals | AddAgeSignalsBridge(); Apple also needs the com.apple.developer.declared-age-range entitlement | IAgeSignalsBridge — the store's age range via Shiny.AgeSignals; iOS, macOS and Android, 501 elsewhere (Mac Catalyst included); see Age signals below |
.Biometrics | AddBiometricsBridge(); iOS also needs NSFaceIDUsageDescription | IBiometricsBridge — the platform biometric prompt via Shiny.Biometrics (Touch ID / Face ID / Optic ID, Android BiometricPrompt, Windows Hello); iOS, Mac Catalyst, macOS, Android and Windows, 501 on Linux; see Biometrics below |
.Nfc | AddNfcBridge(); Android android.permission.NFC, iOS NFCReaderUsageDescription + the NFC entitlement (TAG) | INfcBridge — NDEF tags via Shiny.Nfc: one-tap read/write, scans with nfc.tag events, held-tag write/lock; Android, iOS, PC/SC on Windows/macOS/Linux, 501 on Mac Catalyst; see NFC below |
.Vpn | AddVpnBridge(); Apple also needs the Personal VPN capability (com.apple.developer.networking.vpn.api = allow-vpn) | IVpnBridge — the OS's IKEv2 VPN client via Shiny.Net.Vpn; iOS, Mac Catalyst, macOS, Android 11+ and Linux, 501 on Windows; see VPN below |
.Maps | AddMapsBridge(o => { o.Basemap; o.Catalog; o.CatalogPublicKey; o.Directions.Router; o.Directions.Geocoder; o.Traffic; o.TrafficIncidents; }) — callable repeatedly, one options instance; .Maps.Valhalla: AddOnDeviceDirections() | IMapsBridge, IDirectionsBridge (Shiny.AppDeviceBridge.Maps.Client, AddMapsBridgeClient()/AddDirectionsBridgeClient(), or AddBridgeMaps() from .Maps.Blazor) — see Maps below |
.Notifications | AddNotificationsBridge(); a custom delegate: AddNotificationsBridge(o => o.UseDelegate<MyNotificationDelegate>()) (subclass WebAppNotificationDelegate) | INotificationsBridge — channel actions are NotificationChannelAction(Identifier, Title, ActionType, RequiresUnlock); set RequiresUnlock: true on actions with a real-world effect ("Open Garage") |
.HttpTransfers | AddHttpTransfersBridge() | ITransfersBridge |
.AutoUpdate | AddWebAppAutoUpdate(o => …) — WebAppAutoUpdateOptions: RequiredInternetAccess (Any), RequireCharging, UseMeteredConnection (on), RegisterTransferService (on) | none — not a bridge; background web app updates (Shiny.Jobs + Shiny.Net.Http) |
.AppLinks | AddAppLinksBridge(o => …) | ILinksBridge (built in) |
.ShareTarget | AddShareTargetBridge(o => o.Root = "data") — ShareTargetOptions: Root (data), MaxPending (20), MaxFiles (20), MaxTextLength, AcceptCommandLineFiles (Linux, off) | IShareTargetBridge — text, links and files other apps share to this one, queued for the page; see Receiving shares below |
.Health | AddHealthBridge() | IHealthBridge |
.Speech | AddSpeechBridge() | ISpeechBridge — SpeakRequest.Tone (SpeechTone(Emotion, Intensity, Instructions)) reaches expressive cloud engines; on-device ones ignore it |
.AiConversation | AddAiConversationBridge(ai => ai.SetChatClientProvider<T>(), o => o.Voice = true) — AiConversationBridgeOptions: Voice (off), MaxOpenSessions (8), RegisterAiConversation (on) | IAiConversationBridge — streaming, persisted sessions with the app's model, questions, images, memory and the voice loop via Shiny.AiConversation; see AI conversation below |
.Audio | AddAudioBridge(o => o.MaxRecordingDuration = TimeSpan.FromMinutes(10)) — AudioBridgeOptions: Root (data), Folder (audio-recordings), MaxRecordingDuration (1 h; null for none), RegisterAudioServices (on) | IAudioBridge — clips, system volume, WAV recording with effect presets, routes and a live monitor via Shiny.Audio; see Audio below |
.ScreenRecorder | AddScreenRecorderBridge(o => o.MaxDuration = TimeSpan.FromMinutes(10)) — ScreenRecorderBridgeOptions: Root (data), Folder (screen-recordings), MaxDuration (1 h; null for none), ConfirmStart, RegisterScreenRecorder (on) | IScreenRecorderBridge — the device's screen to a video via Shiny.ScreenRecorder; all platforms — see Screen recorder below |
.Contacts | AddContactsBridge() | IContactsBridge |
.Calendar | AddCalendarBridge() | ICalendarBridge |
.Photos | AddPhotosBridge() | IPhotosBridge |
.Barcodes | AddBarcodesBridge() — calls UseShinyCamera(); camera permission as for .Camera | IBarcodesBridge — the Shiny.Maui.Controls modal scanner, full screen: one code or many, LongRange mode with AutoZoom (not Linux) |
.Camera | AddCameraBridge(o => …) | ICameraBridge — this device's camera driven from a page anywhere; viewfinder MJPEG at camera/preview for an <img> (not Linux) |
.Folders | AddFoldersBridge() — also registers FolderRoots for folders the app adds by path | IFoldersBridge |
.Database | AddDatabaseBridge(o => o.StatementTimeout = …); another engine: bridge.Services.AddDatabaseDriver<T>() | IDatabaseBridge — SQLite files in the file roots, or a driver's connections; all platforms — see Database below |
.Desktop | AddTrayIconBridge(), AddQuickEntryBridge(o => o.HotKey = "Ctrl+Alt+Space"), AddWindowBridge(o => o.HideOnClose = true) | Shiny.AppDeviceBridge.Desktop.Client: ITrayBridge, IQuickEntryBridge, IWindowBridge (desktop only; 501 on mobile; the window bridge is 501 on Mac Catalyst too) |
.RpiCamera | AddRpiCameraBridge(o => …) (either builder — a headless Pi's too) | IRpiCameraBridge — snapshots, captures into a file root, controls; live MJPEG at rpicamera/stream for an <img>; ICameraService.StreamToAsync(stream) for a pipe with no HTTP, read with ReadFramesAsync (Linux + native shim only) |
.Tunnel | AddTunnel(o => o.Host = QuickTunnelHost.Pinggy) (either builder) | none — the app opens and closes it (AppDeviceBridgeTunnel.StartAsync(token) / StopAsync()) from its own UI or endpoints |
Client packages are Shiny.AppDeviceBridge.{Bridge}.Client, registered with Add{Name}BridgeClient() — the
name from the interface: IAppBridge → AddAppBridgeClient(), ITransfersBridge → AddTransfersBridgeClient(),
ITrayBridge → AddTrayBridgeClient(), IQuickEntryBridge → AddQuickEntryBridgeClient(). The desktop bridges share
Shiny.AppDeviceBridge.Desktop.Client.
AddMapsBridge(o => …) adds /_bridge/maps and /_bridge/directions on every platform. Online by default; offline
where the user downloaded a region.
MapsOptions
with OpenStreetMap, Azure Maps and Google Maps implementations built in; each may be reassigned while the app runs. Keys
live in the provider objects in the native app and never reach the page. Azure Maps providers take a key string or
one shared AzureMapsCredential(key) / AzureMapsCredential(clientId, ct => entraToken).o.Basemap = new ProtomapsBasemapProvider("https://…/planet.pmtiles" or "…/{z}/{x}/{y}.mvt") { MaxZoom, ConfigureRequest } (OpenStreetMap, vector, Protomaps schema — the same schema as downloaded regions; cached for
offline), new AzureMapsBasemapProvider(key) { Style = AzureMapsBasemapStyle.Road|DarkGrey|Imagery, Language, View }
(raster), or new GoogleMapsBasemapProvider(key) { Style = GoogleMapsBasemapStyle.Roadmap|Satellite|Terrain, Language, Region } (raster, Map Tiles API; session handled internally). Custom: IBasemapProvider — Layer
(BasemapLayer(provider, TileFormat.Vector|Raster, minZoom, maxZoom, attribution) { TileSize, Cacheable }) and
GetTileAsync(z, x, y, http, ct) → ProviderTile or null. Vector providers must serve the Protomaps schema.GET /_bridge/maps returns TilesUrl/GlyphsUrl/SpritesUrl templates for MapLibre (never hard-code
them) and Basemap (BasemapInfo: provider, format, tilesUrl, zooms, tileSize, attribution; null without one). A
vector tile comes from an installed region, then the tile cache (TileCacheBytes), then a vector basemap, else 204.
A raster basemap is served at maps/basemap/{z}/{x}/{y} (501 when the basemap isn't raster), never cached (Azure's
and Google's terms), and drawn over the vector regions so they show through offline — <BridgeMap> does this
itself; a hand-built MapLibre style adds a raster source above the Protomaps layers. MapsOptions.ConfigureRequest
only covers the catalog, downloads, glyphs and sprites.Shiny.AppDeviceBridge.Maps.Blazor, services.AddWebAppHostClient().AddBridgeMaps(), and use
<BridgeMap @ref="map" Latitude=… Longitude=… Zoom=… Style="height: 60vh" OnClick=… OnDrawn=… />. Methods:
AddPinAsync(new MapPin(id, new GeoPoint(lat, lon), label, Draggable: true)), AddShapeAsync(new MapShape(id, MapShapeKind.Line|Polygon, points, color)), AddCircleAsync, ShowRouteAsync(route), SetDrawModeAsync(MapDrawMode.Pin|Line|Polygon|None),
FitBoundsAsync, FitAllAsync, FlyToAsync, ClearAsync, SnapshotAsync(). MapLibre is bundled — don't add a CDN
script. In Pin mode OnClick gets IsPinMode = true and the page adds the pin; OnDrawn hands back a finished
line/area for the page to add.o.Traffic — new TomTomTrafficProvider(key) (vector), new HereTrafficProvider(key) { MinTrafficCongestion = "heavy" } (raster), new AzureMapsTrafficProvider(key) or (azureMapsCredential) with
Style = AzureMapsTrafficStyle.Relative|RelativeDark|Delay|ReducedSensitivity|Absolute (raster, Render v2 tilesets —
never the Traffic v1 API, retiring 2028). Incidents via o.TrafficIncidents = new TomTomIncidentProvider(key),
independent of flow. Keys stay native. Page: <BridgeMap ShowTraffic="traffic" ShowIncidents="incidents" /> or
SetTrafficAsync/SetIncidentsAsync; HasTraffic/HasIncidents are false without a provider. Custom flow:
ITrafficProvider — Layer (TrafficLayer: TileFormat.Vector with SourceLayer, SpeedRatioProperty
(current/free-flow 0–1), optional ClosedProperty; or Raster with TileSize) and GetTileAsync(z, x, y, http, ct)
→ ProviderTile(bytes, contentType, contentEncoding) or null. Custom incidents: ITrafficIncidentProvider —
TrafficIncidentLayer(minZoom, maxZoom, refresh, attribution, kindProperty, kinds) mapping the provider's values to
TrafficIncidentKind, plus LineSourceLayer, PointSourceLayer, DescriptionProperty, DelayProperty,
ClusterSizeProperty. Routes maps/traffic/{z}/{x}/{y} and maps/incidents/{z}/{x}/{y}: 204 with no data or no
connection, 501 without a provider. o.Traffic/o.TrafficIncidents may be reassigned at runtime (e.g. from a
settings screen); the page re-reads GET maps (re-create <BridgeMap>) to see the change. Never send provider keys
to the page. Live only; directions don't use traffic.Catalog + CatalogPublicKey (required together, usually the web app release key).
GetRegionsAsync(refresh), InstallAsync(id, new MapPackInstallRequest(Directions: true)) (202; progress on
maps.download/OnDownloadAsync; Installed at once when nothing is newer — events can beat the reply, so a page keeps
the newest state rather than overwriting it with the reply), RemoveAsync, RemoveDirectionsAsync, CancelDownloadAsync. Parts are verified
against the signed hash; interrupted downloads resume. Server: services.AddMapPacks(o => { o.SigningKey; o.PacksDirectory; })
app.MapMapPacks("/maps"); build the directory with shiny-map-packs region|assets|list|remove.RouteAsync(new DirectionsRequest([new RouteStop(lat, lon), …], TravelMode.Car, DistanceUnits.Kilometers, Language, DirectionsSource.Auto, new RouteAvoid(Tolls: true))) → DirectionsRoute (metres, seconds, Shape as
[lon, lat], Legs[].Maneuvers[]). Auto = on the device when a downloaded road network covers every stop, else
online through o.Directions.Router: new ValhallaRouteProvider(new Uri("https://…/route")) { ApiKey, ConfigureRequest } (all modes), new AzureMapsRouteProvider(key) { UseTraffic = true } (Car, Walking, Truck), new GoogleMapsRouteProvider(key) { UseTraffic } (Car, Bicycle, Walking; Google's terms want its routes on a Google
basemap), or an IRouteProvider (Name, Attribution, Modes, RouteAsync(request, http, ct) → DirectionsRoute;
throw DirectionsException(DirectionsError.NoRoute|InvalidRequest|RouterFailed, message)). DirectionsInfo.OnlineModes
and .Router tell the page what it can ask for; DirectionsRoute.Attribution must be shown with the route. Errors:
404 no_route, 400 mode_unsupported (mode the online router lacks), 503 offline_unavailable, 501 with no router
at all. o.Directions.Timeout bounds every online route and search.o.Directions.Geocoder = new NominatimGeocoder("MyApp/1.0 ([email protected])") (the User-Agent Nominatim's
policy requires; BaseAddress for your own server, Countries, MinimumInterval 1 s), new AzureMapsGeocoder(key) { View }, new GoogleMapsGeocoder(key) { Region }, or an IGeocoder of your own.
GeocodeAsync(query, limit: 5, language) → GeocodeResult(Places, Attribution), each GeocodedPlace(Name, Address, Latitude, Longitude, Bounds) best first; feed one into a RouteStop. Always online: 503 geocoder_unavailable, 501
without a geocoder; DirectionsInfo.Geocoding says which. Search when the user asks, not per keystroke — the public
server allows one request a second, and the geocoder spaces them. Regions for a trip: the catalog regions whose
Bounds contain any route.Shape point, installed with Directions: true.AddOnDeviceDirections() from .Maps.Valhalla — Android and iOS (valhalla-mobile 0.6.3 / Valhalla
3.6.3); a no-op elsewhere. Road networks must be built with Valhalla 3.6.3 (shiny-map-packs --valhalla docker).HttpClientHandler there can't do TLS 1.3; the macOS head adds
bridge.AddMapsBridge(o => o.HttpMessageHandlerFactory = () => new NSUrlSessionHandler()).AddWearablesBridge() puts the companion app on a paired Apple Watch (WatchConnectivity) or Wear OS device (Data Layer)
behind /_bridge/wearables, backed by Shiny.Wearables (registers AddWearables<WebAppWearableDelegate>() itself unless
RegisterWearableService = false). iOS and Android only; everything else answers 501 — check GetStatusAsync().Supported.
data reaches the watch as UTF-8 JSON text; what the watch sends arrives as JSON,
as a string when it is plain UTF-8 text (WearableData.FromString, a Swift/Kotlin String), or as a base64 string
with binary: true when it is neither. Note a page string goes out JSON-quoted ("hi"), so a companion reading
text should parse JSON.SendMessageAsync(new WearableMessageRequest("sync", data)) waits for the reply (WearableReply);
never queues — 409 not_reachable without a reachable watch. UpdateContextAsync (latest state only),
TransferAsync (queued, in order) and SendFileAsync(new WearableFileRequest(path, new BridgeFile("data", "maps/city.bin")))
return at once with a WearableTransferTicket; wearables.completed reports the id delivered/failed/cancelled.
A file must be in a root on disk and stay there until wearables.completed. GetPendingTransfersAsync, CancelTransferAsync(id).wearables.status, wearables.message, wearables.context, wearables.transfer,
wearables.file, wearables.completed. To act on traffic, register a native-call handler (wearables.message,
wearables.context, wearables.transfer, wearables.file) in the page; a wearables.message handler's return value
is the reply. With no page open, the app's own Shiny.Wearables delegate is what answers.
Received files are filed to data/wearables/{id}/{name} and arrive as a BridgeFile for the files bridge.The companion app speaks Shiny.Wearables.WearableProtocol (watchOS: ["path": String, "data": Data] dictionaries;
Wear OS: /shiny/... paths, the shiny_wearable capability, same application id and signing key).
AddLiveActivitiesBridge() puts iOS Live Activities (Lock Screen, Dynamic Island) and Android 16 Live Updates behind
/_bridge/liveactivities, backed by Shiny.Mobile.LiveActivities (registers AddLiveActivities<WebAppLiveActivityDelegate>()
itself unless the app already registered ILiveActivityManager). iOS 16.2+ and Android only; everything else answers 501.
<ShinyLiveActivityWidget Condition="$(TargetFramework.Contains('-ios'))">true</ShinyLiveActivityWidget>
in the app's csproj. It builds Shiny's stock widget into the app and adds NSSupportsLiveActivities; without it
StartAsync succeeds and nothing appears. The extension's bundle id is <app id>.LiveActivity and needs a profile.StartAsync(new LiveActivityStartRequest(new LiveActivityContent(Title, Body, ShortStatus, Progress, StaleDate, RelevanceScore, Data), Attributes, Kind))
returns a LiveActivity { Id, State, PushToken }. UpdateAsync(id, new LiveActivityUpdateRequest(content, alert?))
(silent unless an alert), EndAsync(id, new LiveActivityEndRequest(content?, dismissAt?)), EndAllAsync(),
GetActivitiesAsync(), GetStatusAsync() / RequestAccessAsync() (Access, PushToStartToken).
LiveActivityProgress: Value 0–1, or Start/End for a system-driven timer, or Indeterminate.404 unknown id, 400 no content / progress outside 0–1, 502 live_activity_failed when ActivityKit refuses.RequestPushToken defaults to true and needs the aps-environment entitlement on iOS (ActivityKit otherwise fails
with "ActivityInput error 0"). Generate RequestPushToken: false unless the app is set up for push.liveactivities.token ({ activityId, token }, per activity) and liveactivities.starttoken ({ token }, iOS 17.2+
push-to-start). Events liveactivities.started and liveactivities.state carry { id, state, pushToken }.AddInAppPurchasesBridge() puts the App Store (StoreKit 2) and Google Play Billing behind /_bridge/purchases, backed
by Shiny.Mobile.InAppPurchases (registers AddInAppPurchases<WebAppPurchaseDelegate>() itself; an app's own
IPurchaseDelegate keeps running beside it). iOS and Android only; everything else answers 501. This is store
purchasing, not Apple Pay / Google Pay card processing.
GetStatusAsync() → PurchasesStatus { Platform, CanMakePayments }. GetProductsAsync(new ProductsRequest([...ids]))
→ StoreProduct (unknown ids omitted; Google base plans/offers and Apple's intro offer in SubscriptionOffers).PurchaseAsync(new PurchaseRequest(productId, AccountToken: user.Id, OfferToken?, Quantity, Replacement?)) →
PurchaseResult { Status, Purchase? } — Success, Pending, Cancelled, AlreadyOwned. Cancel is a result,
not an exception. Always generate AccountToken (the user's GUID); the stores echo it to the server.purchase.VerificationData to the app's own
server (Shiny.Mobile.InAppPurchases.Server's IPurchaseVerifier takes it directly), store the entitlement, then
FinishAsync(purchase.TransactionId, new FinishPurchaseRequest(Consume: isConsumable)). Never grant Pending.
The bridge looks the purchase up by transaction id in the store's unfinished purchases and entitlements; 404 purchase_not_found usually means it was already finished. Google refunds purchases not finished within 3 days.GetUnfinishedAsync() through the same path. GetEntitlementsAsync() for what is owned;
RestoreAsync() only from a "Restore Purchases" button (Apple may prompt sign-in); ShowManageSubscriptionsAsync(new ManageSubscriptionsRequest(productId?)).OnUpdatedAsync / a purchases.updated handler — Ask to Buy approvals, renewals, refunds
(State: Revoked → revoke), other devices. Idempotent on TransactionId. Purchases arriving with no page open are the
native app's to verify and finish — its own purchase delegate, checking WebAppInvoker.IsPageListening("purchases.updated").BridgeException.Code: 503 store_unavailable|network, 403 not_allowed, 404 product_not_found,
409 product_unavailable|no_user_interface|invalid_state, 400 developer_error, 502 verification_failed|purchase_failed.AddGameCenterBridge(o => …) puts Apple Game Center (iOS, Mac Catalyst, macOS) and Google Play Games v2 (Android) behind
/_bridge/games, backed by Shiny.GameCenter (registers AddGameCenter itself unless the app already did). Every other
platform answers 501.
totalSteps matching the Play
Console) — Apple counts percent.SignInAsync() → SignInResult { Player? } — null is a decline, not an error. OnPlayerChangedAsync /
games.player for sign-in, sign-out, account switch.UnlockAsync(key), SetProgressAsync(key, new AchievementProgressRequest(steps))
(absolute — prefer it over increments for idempotency), IncrementAsync, RevealAsync (Google only),
SubmitScoreAsync(key, new SubmitScoreRequest(score)) are queued on the device. GetStatusAsync().PendingCount,
FlushAsync() to wait for the queue. Don't generate client-side retry loops around them.GetAchievementsAsync(forceReload), GetScoresAsync(key, new LeaderboardScoresRequest(Scope, TimeScope, MaxResults ≤ 100)), GetFriendsAsync() → FriendsResult { Status, Friends } — on ConsentRequested (Google) ask again later. UI: ShowAchievementsAsync(),
ShowLeaderboardAsync(new ShowLeaderboardRequest(key?)).BridgeException.Code: 401 not_authenticated, 404 invalid_id, 409 no_user_interface,
503 network|unavailable|not_configured, 502 game_service_failed.AddCallDirectoryBridge() puts call blocking and caller identification behind /_bridge/calldirectory, backed by
Shiny.Mobile.CallDirectory. iOS (a Call Directory extension the build generates) and Android 10+ (call screening role);
everything else answers 501.
CallDirectoryEntry(PhoneNumber, Label?, Type) — PhoneNumber is a long: country code + digits
(18005550100). Normalize user input with NormalizeAsync(new NormalizeNumberRequest(text, DefaultCountryCode?))
— never hand-roll the parsing. Type: Block, Identify (label as caller ID), Allow (Android only; iOS treats it as Identify).SetAsync, RemoveAsync(new CallDirectoryRemoveRequest([...])), ClearAsync(), and ReplaceAllAsync for a full
server sync. Batch edits, then ReloadAsync() once — iOS only sees changes after a reload; read
CallDirectoryReload.Result (ExtensionDisabled → send the user to Settings via RequestAccessAsync()).GetStatusAsync() → { Access, Count }. iOS has no permission prompt; re-check access when the app resumes.
GetEntryAsync(number) answers 404 when the number isn't stored.AddAgeSignalsBridge() puts the user's age range, as the app store shares it, behind /_bridge/agesignals, backed by
Shiny.AgeSignals — Apple Declared Age Range (iOS / macOS 26+) and Google Play Age Signals. For app store accountability
laws (Texas SB 2420, Utah, Louisiana) and any age-gated feature. iOS, macOS and Android; everything else answers 501.
RequestAgeRangeAsync(new AgeRangeRequest([13, 16, 18])) → AgeSignal { Status, LowerBound, UpperBound, Source, … }.
One to three ascending gates, else 400. Declining is a result (Status == Declined), not an exception; so is
NotSupported on an OS older than 26 and VerificationRequired (send the user to the Play Store).signal.IsAtLeast(18) — bool?, and null means the store can't tell, so treat null as "not verified".
Require a minimum strength with signal.Source >= AgeRangeSource.Confirmed (ordered weakest first).GetEligibilityAsync() — no UI — reports IsSupported and Apple's IsEligible / AgeRangeRequired / significant-change
flags (null on Android). ShowSignificantUpdateAsync(new SignificantUpdateRequest(text)) shows Apple's guardian
sheet; Shown is false on Android, where approval arrives on AgeSignal.SignificantChange instead.BridgeException.Code: 503 network|transient|not_available|store_unavailable, 403 app_not_owned,
409 invalid_account|no_user_interface, 502 age_signals_failed.AddBarcodesBridge() puts a barcode scanner behind /_bridge/barcodes: the Shiny.Maui.Controls modal scanner, shown full
screen over the web app — Apple Vision on iOS, Mac Catalyst and macOS, ML Kit on Android, ZXing.Net on Windows. Linux
answers 501. It is the camera of the device running the app; the camera of the machine showing the page is the
browser's BarcodeDetector, and driving the device camera with a viewfinder from elsewhere is .Camera.
ScanAsync(new BarcodeScanRequest()) → BarcodeScanResult { Barcodes, Reason }, answered when the scanner closes. Each
ScannedBarcode has Value, Format, Bounds (normalized). A refused permission, a dismissal or a timeout is a
Reason, not an exception — switch on it (MaxResults, Done, Dismissed, Timeout, Stopped,
PermissionDenied, CameraUnavailable).MaxResults is 1 by default (closes on the first read); 0 scans until the person taps ✓, TimeoutSeconds (idle)
passes or StopScanAsync() is called — then subscribe OnDetectedAsync(...) (barcodes.detected) to show codes as
they come. Also Formats (narrowing it is the biggest speed-up), FilterDuplicates (on), ScanWindow, TorchOn,
Title, Instructions.Mode: BarcodeScanMode.LongRange, AutoZoom: true — shelf labels across an aisle, small, rotated or
soft codes. Tune with MaxAutoZoom (1–10), FullFrameInterval (0–30), MaxNativeCropsPerFrame (0–8),
UncheckedConfirmations (1–10); null keeps the scanner's defaults, and all are ignored in Standard mode. Standard
stays the default: it is quickest for a code held up to the lens.400 for a field out of range or Unknown in Formats; 409 scan_in_progress — one scan at a time.AddBiometricsBridge() puts the platform's own biometric prompt behind /_bridge/biometrics, backed by
Shiny.Biometrics: LocalAuthentication on iOS, Mac Catalyst and macOS, AndroidX BiometricPrompt, and Windows Hello.
Linux answers 501.
GetAvailabilityAsync() — no UI — → BiometricAvailability { Status, Types, IsDeviceCredentialSet }. Check it before
offering biometric sign-in; label the button from Types (Face → "Face ID", Fingerprint → "Touch ID" /
"Fingerprint", Unknown → "Windows Hello"). NotEnrolled → suggest Settings; LockedOut → the passcode unlocks it.AuthenticateAsync(new BiometricRequest("Unlock your vault", AllowDeviceCredential: true)) → BiometricResult.
A cancel, lockout or missing enrollment is a Status, not an exception — switch on it (Success, Cancelled,
Fallback = show your own login, LockedOut, NotEnrolled, PasscodeNotSet, Failed, NotAvailable, Timeout).Reason is required (≤ 256 chars, as are the other texts) or 400. 409 cannot_prompt: no Android activity or a
missing NSFaceIDUsageDescription. Windows Hello always offers its PIN.AddPasskeysBridge("example.com") (in Shiny.AppDeviceBridge.Maui; contracts in Shiny.AppDeviceBridge.Client) puts WebAuthn passkeys behind /_bridge/passkeys, backed by Microsoft.Maui.Authentication.Passkeys
(.NET MAUI 11 Essentials). macOS (AppKit) and Linux answer 501. A hosted page is on loopback, so navigator.credentials
can't make passkeys for your domain — generate bridge calls, never navigator.credentials.create/get, for a hosted page
(fall back to navigator.credentials only when GetStatusAsync().Supported is false in a plain browser).
AddPasskeysBridge (host names, not URLs). Options for any other id → 403 rp_not_allowed.CreateAsync(new PasskeyCreateRequest(optionsJsonElement)) → PasskeyCreateResult { Id, Response } or
AssertAsync(new PasskeyAssertRequest(optionsJsonElement)) → PasskeyAssertResult { Id, UserHandle, Response }, and
POST Response (a JsonElement, unknown in TypeScript) back to the server. Never build challenges or verify in the
page or app — the server does.rp.id; request options must have rpId (no origin to default it from) — else 400.PreferImmediatelyAvailable: true keeps it on-device (no QR / hybrid). Ignored on Windows.BridgeException.Code: 409 cancelled (sheet dismissed — treat like NotAllowedError), 409 failed (no
domain association, no matching passkey; Message has the platform's reason), 501 unsupported OS.com.apple.developer.associated-domains = webcredentials:example.com + the site's
apple-app-site-association; Android the site's assetlinks.json with delegate_permission/common.get_login_creds.AddNfcBridge() puts NDEF NFC tags behind /_bridge/nfc, backed by Shiny.Nfc. A WebView has no Web NFC, so generate
bridge calls, never NDEFReader, for a hosted page.
ReadAsync(new NfcReadRequest("Hold near the tag")) → NfcReadResult? (null = scan ended, e.g. the
iOS sheet was dismissed); WriteAsync(new NfcWriteRequest([new(Uri: "https://…")])) → NfcWriteResult(Written).OnTagAsync(...) before StartScanAsync(new NfcScanRequest()) (else 409 not_listening);
each NfcTag already has Records. OnScanEndedAsync reports Stopped / Dismissed / Failed. StopScanAsync()
or disposing the subscription ends it. One NFC session at a time (409 nfc_busy).HoldSeconds > 0 (≤ 60): WriteTagAsync(tag.TagId, …), LockTagAsync (permanent -
confirm with the user first), then ReleaseTagAsync. TagId is a handle, not the UID; a released tag answers 404.NfcWriteRecord: exactly one of Uri, Text (+Language), MimeType + Data, AndroidPackage, or raw
Format + Type + Data. Read records expose decoded Uri / Text / MimeType plus raw parts.BridgeException.Code: 410 tag_lost (ask the user to hold still), 409 tag_read_only|tag_not_supported|nfc_unavailable,
413 message_too_large, 422 invalid_ndef, 502 nfc_failed. Identifier is null on iOS.AddVpnBridge() puts the app's one profile in the OS's built-in IKEv2 VPN client behind /_bridge/vpn, backed by
Shiny.Net.Vpn. iOS, Mac Catalyst, macOS, Android 11+ and Linux (NetworkManager + strongSwan plugin); Windows answers
501. IKEv2 only — not WireGuard or OpenVPN.
GetStatusAsync().Capabilities before offering an option: Android 11–12 has no Status (state is
Unknown, vpn.status never fires, ConnectAsync returns once the OS accepts), Android has no RemoteIdentifier,
Apple has no ServerRootCertificate, Linux has no Certificate. A missing option answers 501 not_supported.SaveProfileAsync(new VpnProfileRequest(Name, ServerAddress, VpnAuthenticationType.UsernamePassword, Username: …, Password: …)) — or SharedSecret (Secret, and LocalIdentifier on Android) or Certificate (Pkcs12 bytes,
base64 string in TypeScript, plus Password). The first save shows the OS consent prompt: check
VpnProfileResult.Access == Denied. Saving does not connect.ConnectAsync(new VpnConnectRequest(TimeoutSeconds)) (1–300, default 30) waits for the tunnel and answers the new
VpnStatus; DisconnectAsync() keeps the profile; RemoveProfileAsync() deletes it and its secrets.OnStatusChangedAsync (vpn.status): the user can change the tunnel in system settings.BridgeException.Code: 403 vpn_permission (no profile, or consent withdrawn), 502 vpn_connection_failed
(the OS's reason in the message), 502 vpn_failed.VpnProfileRequest's secrets — its ToString() leaves them out, keep it that way — and don't ship
credentials in the web app's bundle; fetch them from your server after sign-in.AddHubsBridge(...) serves Universal Hubs (3.x) whose logic lives in the web app page. The app hosts them over Wi-Fi
(mDNS, a WebSocket per hub at /hubs/{name} on the bridge's own server), Bluetooth LE, and Multipeer or Nearby when it
sets them up; every client call reaches the web app as the native call hub:{name}, answered by the page while it's
open, carrying a HubCall, and the HubCallReply goes back to the client. Clients are ordinary Universal Hubs clients
(AddUniversalHubClient<TContract>("game", o => o.UseHttp("_myapp._tcp").UseBluetoothLE(service, characteristic)))
and can't tell the logic is in a page.
// the app: what web app hubs may use is fixed here (iOS lists every mDNS type in NSBonjourServices)
bridge.AddHubsBridge(
server => server
.Configure(o => o.LocalName = "Kitchen") // what other devices list this one as
.Http(o => o.DynamicServiceTypes.Add("_myapp._tcp"))
.BluetoothLE(o => o.DynamicServiceUuid = ServiceUuid) // optional - else Universal Hubs' default service
.Multipeer("myapp-mc"), // optional - Shiny.UniversalHubs.Multipeer
clients => clients.UseMultipeer("myapp-mc")); // what the page's own hub clients share
builder.Services.AddShinyHttpServer(http => http.Options.Address = IPAddress.Any, autoStart: false); // for Wi-Fi clients
// the Blazor page: Wi-Fi always; BLE only with a characteristic
builder.Services.AddWebAppHostClient().AddWebAppHub<GameHub>(new("game")
{
ServiceType = "_myapp._tcp",
CharacteristicUuid = GameCharacteristic,
MaxClients = 6
});
// once the page is up — every load:
var hubs = host.Services.GetRequiredService<WebAppHubs>();
await hubs.DefineAsync();
await hubs.StartAsync("game");
public sealed class GameHub(GameEngine engine) : WebAppHub
{
protected override void Map(WebAppHubMethods methods) => methods
.Invoke("MakeMove", GameJson.Default.Int32, GameJson.Default.MoveResult, this.MakeMove)
.Stream("Watch", GameJson.Default.GameState, engine.Changes);
public override Task OnConnectedAsync(HubConnectionInfo c) => engine.HasSeat ? Task.CompletedTask : throw new HubException("Full", "No seats");
async Task<MoveResult> MakeMove(int cell)
{
var result = engine.Move(this.Connection.Id, cell);
await this.PushAsync("StateChanged", GameJson.Default.GameState, engine.State);
return result;
}
}
[UniversalHubContract] interface exactly, and
the page's JSON must match the clients' serializer (a camelCase source-gen context on both sides, say). Methods not in
the definition are answered HubMethodNotFound without reaching the page.DefineAsync): defining with the same values keeps the hub and its clients (the
method list may change); a changed service type, characteristic, service, MaxClients or AllowTunnel replaces the
hub and disconnects its clients.HubException(type, message) keeps its type for the client (HubRemoteException.RemoteErrorType); any other
exception is typed by its class name. Abort(reason) ends the caller's session after the reply. Throw from
OnConnectedAsync to refuse a client.hub:{name}, connections are refused and calls fail with HubUnavailable.
Calls get the invoker's PageInvocationTimeout (25 s); streams run until they end or the caller leaves.import { hostHub } from "/_bridge/hubs/client.js" — hostHub(definition, { MakeMove(cell) {…}, async *Watch() {…}, onConnected(c) {…} }), an async generator being a stream; throw new HubError(type, message).
The generated TypeScript HubsBridge client wraps the same routes.CreateClientAsync(new HubClientRequest("game", "_myapp._tcp", characteristicUuid /* null keeps it off BLE */, serviceUuid)), then — with OnHostAsync listened to first (409 not_listening) — DiscoverAsync(id, new(Transports));
ConnectAsync(id, new HubConnectRequest(Host: seen.Name /* or Url: "http://…" */, Name: "Allan", Prefer: HubTransports.Ble, Allowed: HubTransports.Ble | HubTransports.Http)); InvokeAsync(id, new HubInvokeRequest("Send", [json])) (a hub's
own failure is result.Error, not an exception), StreamAsync with items on OnStreamItemAsync, pushes on
OnPushAsync, status on OnClientChangedAsync. 409 refused carries the host's reason. Clients share
AddHubsBridge(server => …, clients => clients.UseMultipeer("myapp-mc"))'s options; Wi-Fi and BLE come from each
request. At most 8.400 for a bad definition (a bad name or UUID, serviceUuid without characteristicUuid) or a service type the app
doesn't allow, 409 for a name or characteristic taken (or the app's MaxHubs), 503 when no transport could start
or the page asked only for ones the app didn't set up, 410 on a stream whose caller left.HubTransports flags: Ble, Http, Multipeer, Nearby, All; HubClientStatus includes Reconnecting (the link
dropped and the client is resuming).services.AddBluetoothLeHosting() — without it the hubs run over the other transports, never fail; Multipeer on Apple
with Shiny.UniversalHubs.Multipeer; Nearby on Android, iOS and macOS with Shiny.UniversalHubs.Nearby. Universal
Hubs 3 can't talk to 2.x. A host without AddHubsBridge answers 501.Two bridges, matching Shiny 5.9's two models — pick by the printer:
printers (AddPrintersBridge(), IPrintersBridge) — 58/80mm receipt and label printers (ESC/POS, TSPL) over
Bluetooth LE or raw TCP 9100. The page builds the receipt; the device encodes and streams it. One printer at a time.printing (AddPrintingBridge(), IPrintingBridge) — any printer the OS knows (AirPrint, PrintManager, Windows
spooler, CUPS): hand it a PDF, PNG/JPEG, HTML or an http(s) URL. Never use it for a thermal printer, nor printers for
an office printer.@inject IPrintersBridge Printers
@inject IPrintingBridge Printing
// find and connect — Id from a scan, or a network printer by LAN IP literal
var found = await Printers.ScanAsync(new PrinterScanRequest(PrinterTransport.Ble));
var printer = await Printers.ConnectAsync(new PrinterConnectRequest(Id: found[0].Id));
// or: new PrinterConnectRequest(PrinterTransport.Network, Host: "192.168.1.50", Port: 9100, Paper: PrinterPaper.Paper58mm)
var cols = printer.Capabilities.CharactersPerLine; // lay out against this — never hard-code 32/48
var receipt = new PrintElements()
.AlignCenter().Bold().Size(2).Line("SHINY MART").ResetStyle()
.AlignLeft().Line(new string('-', cols))
.QrCode("https://example.com/r/1")
.Image(logoPng) // PNG/JPEG bytes; scaled to DotsPerLine on the device
.Cut(); // only feeds on a printer without a cutter
await Printers.PrintAsync(receipt.ToRequest());
// the same receipt on an office printer
var pdf = await Printers.RenderAsync(new PrintRenderRequest(receipt.Elements));
var result = await Printing.PrintAsync(new PrintJobRequest(PrintJobContent.Pdf, Convert.ToBase64String(pdf)));
// result.Status: Completed | Submitted (both success) | Cancelled (dialog closed — not an error) | Failed
// a file the device already has, or anything big: stream it — never base64 a large PDF into PrintAsync (16 MB cap)
await using var file = File.OpenRead(path);
await Printing.PrintPdfAsync(file, jobName: "Invoice 1042", copies: 2); // PrintImageAsync for PNG/JPEG; TS: printPdf(blob, {...})
// HTML -> PDF bytes, no print UI (save/share): iOS, Mac Catalyst, Android only — check caps.HtmlToPdf, 501 elsewhere
byte[] invoicePdf = await Printing.HtmlToPdfAsync(new HtmlToPdfRequest(html, PageWidth: 612, PageHeight: 792));
PrintElements with a Type (Text, Line, Align, Bold, Underline, Size,
ResetStyle, Feed, Barcode, QrCode, Image, Cut, Raw); in TypeScript write them as objects
({ type: "Line", text: "…" }) — enums are PascalCase strings. A bad element answers 400 elements[i]: ….409 not_connected; second connect → 409 already_connected (DisconnectAsync first); a
write that fails drops the printer (409 printer_failed) and raises printers.disconnected — a TCP printer that was
switched off is only noticed this way.ScanAsync(new PrinterScanRequest(PrinterTransport.Network, Sweep: true)) adds a TCP port sweep of the
local /24 (on NetworkPorts) to mDNS, for printers that don't advertise; DiscoveredPrinter.Discovery says which.ConnectedPrinter.SupportsStatus (ESC/POS over the network), GetPrinterStatusAsync() →
PrinterSensorStatus (CanPrint, IsPaperOut, IsPaperNearEnd, IsCoverOpen, IsDrawerSensorHigh, errors). Check
CanPrint before a receipt; 501 when unsupported, 504 printer_timeout when the printer doesn't answer.GetStatusAsync() (BluetoothSupported, NetworkScanSupported, RenderSupported) and
Printing.GetCapabilitiesAsync() (Pdf, Image, Html, Silent, ListPrinters). Content a platform can't print
answers 501 — HTML on Windows and CUPS: render to PDF first. Silent + PrinterId (from GetPrintersAsync())
skips the dialog on Windows and CUPS only.NetworkPorts; a scanned one
connects where it advertised. Don't widen NetworkPorts beyond printer ports — elements can carry raw bytes.SkiaSharp.NativeAssets.Linux on Linux (501 without). Apple:
NSBluetoothAlwaysUsageDescription, NSLocalNetworkUsageDescription, NSBonjourServices _pdl-datastream._tcp and
_printer._tcp (+ com.apple.security.print sandboxed on macOS). Android: BLUETOOTH_SCAN/BLUETOOTH_CONNECT; OS
printing needs the app in the foreground.Built on Shiny.AiConversation 3.0. The model, its key, tools and prompts are the app's; the page never sees them.
AddAiConversationBridge(ai => ai.SetChatClientProvider<T>(), o => o.Voice = true) — the first
argument is Shiny.AiConversation's own AiConversationOptions (provider, stores, tools, interceptors); without a
provider it uses the registered IChatClient. AiConversationBridgeOptions: Voice (off), MaxOpenSessions (8),
RegisterAiConversation (on).POST sessions, GET sessions/latest (204 when none), GET sessions?text=&tag=&profile=,
GET/DELETE sessions/{id}, PUT sessions/{id}/title. Events come only from sessions the bridge holds open (it
opens one on use and closes the least recently used idle one past MaxOpenSessions).POST sessions/{id}/messages takes text or answer: { questionId, choiceIds } (never both), up to
4 images as { file: { root, path } }, and instructions. It answers with turnId at once; "wait": true
answers with the outcome and reply. The turn outlives the request; a newer message supersedes it;
DELETE sessions/{id}/turn interrupts (409 no_turn).ai.delta, ai.message, ai.turn.started, ai.turn.ended (outcome + error), ai.questions,
ai.tool, ai.state, ai.usage, ai.title, ai.compacted, ai.memory, ai.error — each carries sessionId;
filter on it.answer; one without choices with text. Not pending: 409 no_such_question.GET sessions/{id}/messages?before=&count= pages backwards; image parts' attachmentId →
GET attachments?id=.GET/PUT/DELETE memory (Global, or Profile/Session with a scopeKey).POST voice { sessionId, wakeWord?, interruption?, quietWords?, followUpTimeoutSeconds?, culture? }
needs a listener on ai.voice.state (409 not_listening) and detaches when none is left; voice/talk,
voice/stop, voice/pause, voice/resume, DELETE voice. A loop the app attached itself: 409 voice_busy.501 for whatever isn't registered.Built on Shiny.Audio 3.0 (Shiny.Audio.Linux on Linux).
POST playback takes exactly one of an absolute http/https url or a file ({ root, path }) in
a file root, and answers once the clip plays, with its id. Clips play together, at most 32 (409 too_many_clips);
DELETE playback/{id} stops one, DELETE playback all. audio.playback.ended carries stopped and any error.GET status reads the system media volume; PUT volume sets it, 501 on iOS and Mac Catalyst
(volumeControlSupported: false). audio.volume fires for the hardware buttons too.POST recording records 16 kHz mono WAV, with an optional effect preset (Robot, Chipmunk,
DeepVoice, Cathedral, Telephone, Megaphone, Ensemble), processing, inputDeviceId and mode
(Both keeps the clean take as dryFile). DELETE recording files it into Root (data) under Folder
(audio-recordings) as REC_yyyyMMdd-HHmmss.wav, read through the files bridge; POST recording/cancel keeps
nothing. MaxRecordingDuration (1 h; null for none) stops and files a recording left running and raises
audio.recording.ended with MaxDurationReached.GET devices lists inputs and outputs; POST devices/picker shows the system output picker;
audio.devices fires on a route change.POST monitor routes the microphone live to the output (PUT monitor changes gain). Listen to
audio.monitor.level first (409 not_listening without); it stops once nobody listens, so a page that went away
can't leave the microphone on the speaker.409 microphone_busy.501 and shows as false in GET status. Bring your own services with
o => o.RegisterAudioServices = false.RECORD_AUDIO; Apple NSMicrophoneUsageDescription, plus
com.apple.security.device.audio-input when sandboxed.AddScreenRecorderBridge() records the device's screen and registers Shiny.ScreenRecorder's recorder (portal on
Linux). For the screen of a browser showing the page, use getDisplayMedia instead. The WebViews on iOS and Android don't
have it, which is why this bridge exists.
var status = await recorder.GetStatusAsync(); // Capabilities decide what to offer
if (!status.Capabilities.Contains(ScreenRecorderCapability.Recording)) return;
await using var sub = await recorder.OnEndedAsync(e => …); // every ending: Stopped, Cancelled, RevokedByUser, MaxDurationReached, …
await recorder.StartAsync(new ScreenRecordingRequest(IncludeMicrophone: true, MaxWidth: 1280)); // returns after consent
var recording = await recorder.StopAsync(); // recording.File is a BridgeFile → IFilesBridge
ScreenRecorderCapability is listed; anything else answers 501 (not_supported).
Pause and resume need PauseResume, which macOS 15 lacks.409 recording_busy (one at a time, including a recording the app started itself), 409 not_recording (stop,
pause or resume with nothing running; cancel is fine), 403 permission_denied (consent declined) or declined
(ConfirmStart said no).screenrecorder.ended rather than assuming StopAsync will
find one; the salvaged file is in ended.Recording.o.ConfirmStart = (request, ct) => ShowMyConfirmationAsync()
for Windows apps. Keep MaxDuration set; it is what stops a recording nobody is watching.FOREGROUND_SERVICE_MEDIA_PROJECTION (+ RECORD_AUDIO for the microphone); Apple
NSMicrophoneUsageDescription for the microphone; packaged Windows graphicsCapture; Linux xdg-desktop-portal +
GStreamer or ffmpeg.A tray app runs with no window and no taskbar/Dock entry, only its tray icon. Generate AddWindowBridge next to
AddTrayIconBridge; the page keeps running while the window is hidden, so tray and quick entry handlers stay in the page.
bridge.AddTrayIconBridge().AddWindowBridge(o =>
{
o.HideOnClose = true; // close hides instead of quitting
o.StartHidden = Environment.GetCommandLineArgs().Contains("--autostart"); // login launch lands in the tray
});
// the page: the tray menu brings the window back and quits
await nativeCalls.HandleAsync("tray.menu", TrayJsonContext.Default.TrayMenuSelection, async s =>
{
if (s.ItemId == "open") await window.ShowAsync(); // IWindowBridge
if (s.ItemId == "quit") await window.QuitAsync();
});
StartHidden): closing only hides, and
HideAsync only succeeds (else 409 no_tray_icon), while a tray icon is showing. RequireTrayIcon = false turns that
off for an app that comes back another way.window.visibility
reports every change. QuitAsync answers, then quits.501.A prompt window over other applications. The page configures it and answers submissions — the app and its page are
running whenever quick entry (or a tray icon) is there, so generate the handlers in the page, not native code. Native code
can also set the prompt with QuickEntryBridge.SetPromptAsync(…) (throws ArgumentException / PlatformNotSupportedException;
null when the window shows custom content). Register the page's handler as a native call, not only an event:
await quickEntry.SetPromptAsync(new QuickEntryPromptInput(Placeholder: "Ask…", Suggestions: [new("Sync now", Value: "sync")]));
await nativeCalls.HandleAsync("quickentry.submitted", QuickEntryJsonContext.Default.QuickEntrySubmission, async s =>
{
await quickEntry.SetPromptAsync(new QuickEntryPromptInput(IsBusy: true));
await quickEntry.SetPromptAsync(new QuickEntryPromptInput(IsBusy: false, Response: await AnswerAsync(s.Text)));
});
Null properties on QuickEntryPromptInput / QuickEntryOptionsInput leave values unchanged; Response: "" clears the
response and HotKey: "" removes the hotkey.
A debug window onto every request the server answers — files, bridge calls (including 401/403/421 refusals), the app's own endpoints. Register it in a debug build only, and open it from something of the app's own:
#if DEBUG
builder.UseTrafficMonitor(o => o.RedactRequestBody = ctx => ctx.Request.Path == "/api/login");
#endif
traffic.Clicked += async (_, _) => await page.HostView.ShowTrafficMonitorAsync(); // or TrafficMonitorPage.ShowAsync(Navigation)
In memory only (newest 300, text bodies up to 128 KB). Authorization, Proxy-Authorization, Cookie, Set-Cookie
and the token/access_token query parameters are redacted by default — that is what keeps the WebView's launch token
and session cookie out of it; do not clear those sets in shipped code. Without MAUI: http.AddTrafficRecorder() and read
TrafficRecorder.Snapshot() / Changed; TrafficText (Status, Headers, Body, Filter, Describe) formats an
exchange the way the pages do. An exchange is added only after its response has gone out, so a client can be back before
it is there: to read one straight after making the request (a test, a tool), wait for it with
await recorder.WaitForAsync(x => x.Path == "/_bridge/wifi/connection", ct) or WaitUntilAsync(list => list.Count >= 3, ct)
— never Snapshot() right after the call. When overlaying a button on WebAppHostPage, set page.Content = null before
putting HostView in a new layout — replacing the content un-parents the old one and the view's Navigation goes dead.
shiny-bridge-sim (.NET tool Shiny.AppDeviceBridge.Simulator) serves every bridge from its [BridgeClient] interface,
answering with values set in its TUI, a scenario file or a trail. Recommend it for testing a page's behavior against
specific device states (offline, permission denied, 501 on a platform, a GPS walk) — no page changes:
shiny-bridge-sim --dev-server http://localhost:5288 # or --app <published wwwroot>; page at http://127.0.0.1:5299/
shiny-bridge-sim --scenario setup.json --trail walk.gpx --play walk --speed 4 --headless # CI
shiny-bridge-sim --dev-server http://localhost:5288 --web # a browser panel at /_sim/ instead of the TUI
--web replaces the TUI with a browser control panel at /_sim/ (link with #token=… printed at start). Its API is
POST /_sim/api/{operation} — the MCP tool names, arguments as a JSON object, Authorization: Bearer <token> — so a
script can drive it with curl. Callers on this device only; a browser Origin must be the simulator's own.
--web-token <t> fixes the token. Not combinable with --mcp-stdio; fine with --mcp.
A route answers value (JSON validated against the contract; a file for byte routes), null (204) or error
(status + code + message, e.g. 403 access_denied), with optional DelayMs. A bridge can be switched off (all 501).
Values may hold "$now", "$now-5m", "$now+2h", "$uuid", filled in when sent.
Trail JSON: { "name": "...", "loop": false, "steps": [ { "delayMs": 0, "event": "wifi.changed", "payload": {...} }, { "delayMs": 5000, "bridge": "wifi", "route": "GET current", "mode": "null" }, { "bridge": "ble", "supported": false } ] }.
Route keys are "<METHOD> <pattern>" from the interface (GET current, DELETE regions/{identifier}, GET for the root).
.gpx, .kml and .kmz load as gps.reading events plus GET gps/current/GET gps/last values at the recorded
pace (KML: gx:Track with times, else LineString, else Point placemarks, one point per interval).
Geofence simulation (on by default): regions the page monitors via POST geofences/regions are kept, GET regions and
GET regions/{identifier}/state answer from them (404 if not monitored), and each gps.reading that crosses one fires
geofence.status. A region starts Unknown; first reading inside fires Entered, first outside is silent;
notifyOnEntry/notifyOnExit/singleUse are honored. Off via --no-geofences, "simulateGeofences": false in a
scenario, or set_geofence_simulation — then the bridge answers its set route values. regiongeofences isn't simulated
(its sets are registered in C#).
OBD vehicles: --obd <profile.json> (Shiny.Obd obd-emulator.schema.json: vehicle, scenarios, state) makes the obd
bridge the real ObdBridge with an emulated adapter shiny-obd-emulator — scan lists it for any transport, connect
with it as peripheralUuid, then commands/raw/VIN/DTCs/monitor run through Shiny.Obd against an in-process ELM327.
--obd-drive <scenario> / drive_obd plays a drive in real time so monitored values move. Unloaded, the simulated
bridge and its route values are back. Tools: get_obd, load_obd_profile, unload_obd_profile, drive_obd, stop_obd.
A route can also answer a sequence: values one per call, the last repeating — for a page that polls (queued →
running → done). In a trail step or scenario it is "values": [ … ] instead of "value".
A new bridge must be added to BridgeCatalog and the simulator's csproj; SimulatorCatalogTests fail until it is.
shiny-bridge-sim --mcp serves an MCP endpoint at /_sim/mcp on the simulator's own origin, printing a paste-ready
client config (and writing it to mcp.json in the data directory). Use it when you need to put a page into a device
state and then check what it did. --mcp-stdio instead speaks MCP on stdin/stdout, for starting the simulator yourself.
Tools: get_status, list_bridges, describe_bridge, get_route; set_route, set_route_sequence, reset_route,
set_bridge_supported, set_platform, set_sticky_writes, set_geofence_simulation; get_obd, load_obd_profile,
unload_obd_profile, drive_obd, stop_obd; fire_event, set_event_payload; list_trails,
load_trail, load_trail_file, play_trail, pause_trail, stop_trail, remove_trail; apply_scenario,
apply_scenario_file, capture_scenario; get_traffic, get_activity, clear_traffic, set_recording,
wait_for_request, wait_for_quiet.
How to use it well:
get_route before set_route and shape the value on its sample — a value that is not the contract is refused,
and the refusal names the contract it should have matched.wait_for_request for the path the page will call. Do not sleep and then read get_traffic;
only requests made after the wait call count, so the loop is deterministic.fire_event returns — 0 means the page never subscribed.capture_scenario hands back the whole setup to check in beside the app as a reproduction.Origin header —
so a page cannot drive it, and neither can a browser-based tool.// Program.cs
builder.Services
.AddWebAppHostClient() // transport + IHostBridge, ISettingsBridge, IFilesBridge, ILinksBridge
.AddCalendarBridgeClient()
.AddPhotosBridgeClient();
@inject ICalendarBridge Calendar
@inject IPhotosBridge Photos
@inject IFilesBridge Files
@implements IAsyncDisposable
@code {
IAsyncDisposable? subscription;
protected override async Task OnInitializedAsync()
{
var access = await Calendar.RequestAccessAsync(new CalendarAccessRequest());
var page = await Calendar.GetEventsAsync(DateTimeOffset.Now, DateTimeOffset.Now.AddDays(7), limit: 20);
}
async Task PickAsync()
{
foreach (var photo in await Photos.PickAsync(new PhotoPickRequest(Limit: 3)))
{
var bytes = await Files.ReadBytesAsync(photo.File.Root, photo.File.Path);
}
}
public async ValueTask DisposeAsync()
{
if (subscription is not null)
await subscription.DisposeAsync();
}
}
Rules:
BridgeException, never HttpRequestException: it carries StatusCode, the bridge's Code and
IsNotSupported (501). Treat 501 as "hide the feature on this platform".await using var sub = await Gps.OnReadingAsync(r => …) — dispose it when the
component goes away; the last disposal for an event stops its native source. Await it before starting what feeds
it (a scan, a listener). Handlers run off the renderer; call InvokeAsync(StateHasChanged).ISettingsBridge.GetAsync<T>(scope, key, typeInfo, default) and
SetAsync<T>(…) with a source-generated JsonTypeInfo<T>. Never reflection-based JsonSerializer calls.BridgeFile { Root, Path }. Bridges that produce files (photos, exports) return one; read it
through IFilesBridge. Bridges that take a file (share, notification image, tray icon) take one.nativeCalls.HandleAsync("gps", GpsJsonContext.Default.GpsReading, reading => …). With no page open nothing in
the web app runs; background work is the app's own Shiny delegates and jobs.import { BridgeError, CalendarBridge, FilesBridge, FoldersBridge, GpsBridge } from "@shinyorg/appdevicebridge";
const calendar = new CalendarBridge();
try {
await calendar.createEvent({ title: "Standup", start: new Date(), end: new Date(Date.now() + 1_800_000) });
} catch (e) {
if (e instanceof BridgeError && e.isNotSupported) hideCalendar();
}
const folder = await new FoldersBridge().pick({ root: "documents" }); // null when cancelled
if (folder) await new FilesBridge().writeText(folder.root, "notes.txt", "hello");
const stop = await new GpsBridge().onReading(reading => console.log(reading.latitude));
stop(); // unsubscribes
Async. Required parameters are positional; optional
ones, and signal, go in the trailing options object."ReadWrite"), dates accept Date or ISO
strings, byte[] results come back as Blob._host/config, so a moved BridgePrefix or BasePath needs no
page change.IFoldersBridge.PickAsync(new FolderPickRequest("documents")) shows the platform folder picker and makes the
folder a file root named documents, remembered across launches (security-scoped bookmark on Apple, a
persisted SAF grant on Android, the path on Windows and Linux). ForgetAsync(root) releases it. Null means
cancelled. The app's own roots (data, cache) cannot be replaced.
On Android a picked folder has no path: the files bridge works, but share, transfers and notification images refuse it.
A plain net11.0 project referencing .Folders (a shared setup project used by mobile heads) gets GirCore's source
generators from the Linux build, and iOS then fails at launch with Could not find GLib-2.0. Generate this target in
that project's csproj:
<Target Name="_DropGirCoreGenerators" AfterTargets="ResolveLockFileAnalyzers">
<ItemGroup>
<Analyzer Remove="@(Analyzer)" Condition="$([System.String]::Copy('%(Analyzer.NuGetPackageId)').StartsWith('GirCore.'))" />
</ItemGroup>
</Target>
IPhotosBridge.PickAsync needs no permission. GetLibraryAsync/GetThumbnailAsync/ExportAsync need
RequestAccessAsync() and NSPhotoLibraryUsageDescription / READ_MEDIA_IMAGES. The library is 501 on Linux.
AddShareTargetBridge() makes the app a share target. Each share is a SharedContent (Id, ReceivedAt, Text,
Subject, Url, Files) that waits in a queue, persisted across restarts, until the page removes it. Its files are
copied into the Root file root under shares/{id}/ as BridgeFiles, read through the files bridge.
GetPendingAsync() → handle → RemoveAsync(id), and the same
from OnReceivedAsync. RemoveAsync deletes the share's files, so move a file through the files bridge first to keep it.
Never act on a share without removing it, or it is handled again after a reload.Url is only ever an absolute http/https URL, so it is safe to open. Text that is only such a link arrives as Url.
Any other scheme stays in Text. Don't re-parse Text as a link to navigate to.ACTION_SEND/ACTION_SEND_MULTIPLE intent filters on a SingleTop main activity. Only content: files are taken.CFBundleDocumentTypes ("Open in"/"Copy to" deliver files). Text and links need the app's own share
extension, which hands over with ShareTarget.ReceiveAsync(new IncomingShare(...)).OpenUrls in the app delegate and call ShareTarget.ReceiveAsync.%F in the .desktop Exec plus AcceptCommandLineFiles = true.Root file root doesn't exist. Shares only ever reach a page.IDeviceBridge.ShareAsync (device/share)..Database is a database client on the device: bridge.AddDatabaseBridge(), IDatabaseBridge in the page. Every
request names its database by Root + Path (a SQLite file in a file root — the same rules as the files bridge) or
by Connection + Database (a driver's server). Never both: 400. Unknown root or unserved connection: 404.result.Error (and ErrorLine for scripts); only routing
problems throw BridgeException.QueryAsync(new RunDatabaseQuery(sql, Root: "data", Path: "app.db", RunId: id)); stop with
CancelAsync(new CancelDatabaseQuery(id)). Explain: true returns Plan and runs nothing. Pass Record: false for
SQL the app runs on nobody's behalf so it stays out of the history.GetRowsAsync / CountAsync / GetTotalsAsync with Sort, Filters, Search — never build a WHERE in the
page. Edit with InsertRowAsync / UpdateRowAsync / DeleteRowsAsync, passing back RowKeys untouched.PreviewDesignAsync returns DDL; apply it by running that exact Sql with QueryAsync.PreviewImportAsync then ImportAsync (from CsvRoot/CsvPath or CsvText); ExportAsync writes to
TargetRoot/TargetPath.ATTACH, VACUUM INTO or load_extension — SQLite's authorizer refuses them. Don't generate code that
relies on attaching a second file; copy the data through the page instead.IDatabaseDriver the app writes (it keeps its connection strings and secrets) and registers with
bridge.Services.AddDatabaseDriver<T>(); only SQLite ships. The page lists connections with GetConnectionsAsync()
and a server's databases with GetDatabaseNamesAsync(new GetDatabaseNames(connectionId)) (Names, or Error; SQLite
answers with an error, a file being one database). RowView, SqlSpelling, QueryPlans, DatabaseCsv and
TableDesigner.Wrong/DesignOf are public for drivers to reuse.Three different cameras — pick the right one:
getUserMedia in the page, with AllowWebPermissions(WebAppWebPermissions.Camera)..Camera: bridge.AddCameraBridge(), ICameraBridge in the page..RpiCamera.await camera.OpenAsync(); // device shows CameraBridgePage unless the app handles OpenRequested
await using var sub = await camera.OnStatusAsync(s => …); // wait for Live
var photo = await camera.TakePhotoAsync(); // photo.File is a BridgeFile → IFilesBridge
await camera.UpdateSettingsAsync(new CameraSettingsInput(VideoMode: true, Zoom: 2));
BridgeException with Code == "camera_not_open" (409) as an instruction,
camera_state (422) as "not now". Never poll OpenAsync in a loop.<img src="_bridge/camera/preview?t={ticks}"> — always a changing query.CameraBridgeView on the page, o.PresentWhenOpened = false, navigate from
CameraBridgeSession.OpenRequested and set e.Handled = true. Custom filing: register ICameraCaptureStore first.A page watches a Pi camera with <img src="_bridge/rpicamera/stream">. A pipe with no HTTP around it, a Bluetooth LE
L2CAP channel above all, uses ICameraService.StreamToAsync (namespace Shiny.AppDeviceBridge.RpiCamera) on the device and
ReadFramesAsync (namespace Shiny.AppDeviceBridge.RpiCamera.Client) on the viewer. It is not a bridge route, so there is no 501:
off Linux, or without the native shim, it throws CameraUnavailableException.
// Pi (Shiny.BluetoothLE.Hosting 5.6.5+): ICameraService comes from AddRpiCameraBridge(); send ticket.Psm + ticket.Token to the phone
var ticket = await broker.Reserve("camera", TimeSpan.FromSeconds(30), (channel, ct) =>
camera.StreamToAsync(channel, new RpiCameraStreamSettings { MaxFps = 8 }, cancellationToken: ct));
// Phone (Shiny.BluetoothLE 5.6.5+)
await using var channel = await peripheral.OpenL2CapTicketChannel(psm, token);
await foreach (var frame in channel.ReadFramesAsync(ct)) // RpiCameraStreamFrame: Jpeg, Sequence, Width, Height, TimestampMs
Show(frame.Jpeg);
StreamToAsync once the viewer has connected (in the broker handler), never ahead of it: it opens the camera
session on start and releases it on return.RpiCameraStreamSettings defaults: 640×480, Quality 60, MaxFps 10, MaxDuration 5 minutes. Keep them low for
BLE; frames over MaxFps are dropped before encoding and counted in RpiCameraStreamStatistics.FramesDropped.RpiCameraStreamEnd.CameraStopped or MaxDurationReached; cancellation throws OperationCanceledException,
a viewer that left throws IOException. It never disposes the destination.ReadFramesAsync ends cleanly when the stream closes between frames; mid-frame is EndOfStreamException, a bad
header InvalidDataException. A gap in Sequence is dropped frames, not an error.RpiCameraFrameStream): 28-byte little-endian header [length u32][sequence u32][width u32][height u32][fourcc u32 "MJPG"][timestampMs i64]
then the JPEG; WriteFrameAsync, WriteHeader, TryReadHeader, MaxFrameBytes (8 MB).GET rpicamera doesn't list it and DELETE rpicamera/streams doesn't stop it.net11.0, references Shiny.AppDeviceBridge.Client): records plus a
[BridgeClient] interface and its JsonSerializerContext.[BridgeClient("orders", typeof(OrdersJson))]
public interface IOrdersBridge
{
[BridgeGet("{id}")] Task<Order> GetAsync(string id, CancellationToken cancellationToken = default);
[BridgeGet] Task<OrderPage> ListAsync(int offset = 0, int limit = 50, CancellationToken cancellationToken = default);
[BridgePost] Task<Order> CreateAsync(NewOrder order, CancellationToken cancellationToken = default);
[BridgeDelete("{id}")] Task DeleteAsync(string id, CancellationToken cancellationToken = default);
[BridgeEvent("orders.changed")] Task<IAsyncDisposable> OnChangedAsync(Func<Order, Task> handler);
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, PropertyNameCaseInsensitive = true)]
[JsonSerializable(typeof(Order))]
[JsonSerializable(typeof(OrderPage))]
[JsonSerializable(typeof(NewOrder))]
public partial class OrdersJson : JsonSerializerContext;
Binding: a parameter named like a route token fills it; a complex type on POST/PUT (or [BridgeBody]) is the
body; simple types are query parameters ([BridgeQuery("name")] renames). Task<Stream>/Task<byte[]> read raw.
Anything else — a complex type on GET/DELETE, an unmatched token, two bodies — is build error ADB001.
2. Native bridge (MAUI project, references the contracts):
public sealed class OrdersBridge(IOrderStore store) : IWebAppBridge
{
public string Name => "orders";
public bool IsSupported => true;
public void Map(WebAppBridgeRoutes routes) => routes
// Hooked per page stream that names the event; unhooked in finally when it lets go, disconnects or throws.
.MapEvent("orders.changed", ct => WebAppEventStream.FromEvent<Order>(emit =>
{
EventHandler<Order> handler = (_, order) => emit(order);
store.Changed += handler;
return () => store.Changed -= handler;
}, ct), OrdersJson.Default.Order)
.MapGet("/{id}", async ctx => await (await store.FindAsync(ctx.Request.RouteValues["id"]!) is { } order
? WebAppBridgeResults.Json(ctx, order, OrdersJson.Default.Order)
: WebAppBridgeResults.NotFound(ctx, "No such order.")));
}
bridge.AddBridge<OrdersBridge>(); // on the bridge builder, MAUI or headless
// Or an extension of your own, like the packages. No MAUI needed: generic over the builder, returning the one it was given.
public static TBuilder AddOrdersBridge<TBuilder>(this TBuilder bridge) where TBuilder : AppDeviceBridgeBuilder
{
bridge.AddBridge<OrdersBridge>();
return bridge;
}
// Needs MAUI registration (a control, lifecycle events, Essentials): extend MauiAppDeviceBridgeBuilder and use bridge.Maui.
Answer failures with WebAppBridgeResults.Error(ctx, status, code, message), NotSupported (501),
BadRequest, NotFound.
Native UI (a permission prompt, a picker) goes through IWebAppMainThread — resolve it and call
InvokeAsync(...); the MAUI host routes it to the dispatcher, headless it runs inline. Never
Application.Current.Dispatcher or MainThread in a bridge. An IAppDeviceBridgeServerExtension can override
Initialize(IServiceProvider), called once when the container builds the server, before any request.
Events are IAsyncEnumerable<T> mapped with routes.MapEvent(name, ct => …, typeInfo) — never a hub-wide
publish, never a hook in the constructor or Dispose. A native .NET event: WebAppEventStream.FromEvent<T>(emit => { hook; return unhook; }, ct) (an overload takes an async hook for main-thread-only APIs). Values your own code raises
(a Shiny delegate, a session loop): a WebAppEventSource<T> — Publish is a no-op with no listener,
ListenAsync(stopped, ct) reports the listeners remaining so a session can stop at zero — or
routes.Events.Source(name, typeInfo) for a delegate registered outside the bridge. A session the page starts
should answer 409 not_listening while source.HasListeners is false.
3. Map platform enums onto contract enums with BridgeEnum.Convert<TFrom, TTo> (by name) rather than casting.
FolderRoots from .Folders:
folders.Add(root, absolutePath, displayName) keeps it as a root across launches on every platform,
folders.Forget(root) removes it, folders.All lists them with Available. Failures are WebAppFileException
(bad_request, configured_root, folder_unavailable). Never let the page supply the path.files.roots — IFilesBridge.OnRootsChangedAsync / FilesBridge.onRootsChanged — and
should re-list roots then.WebAppFileRoots holds every root, Add(WebAppFileStore) / Remove(name), raises Changed;
TryResolve(root, path, out fullPath) for bridges that need a disk path. WebAppFileRoot needs an absolute path.
Subclass WebAppFileStore for storage that is not a directory; throw WebAppFileException for failures.o.DefaultFileRoots = false (with FileRoots empty there are then no
data/cache roots) and roots.Add(new MyStore("storage")) at startup. Configured FileRoots win regardless.MaxFileWriteBytes raises the server's request body limit whichever bridges are registered, so the app's own
upload endpoints get it too.AllowAnyCallerInDebug,
on by default) — say so when a user binds http.Options.Address past loopback.bridge.Configure(o => o.AuthorizeBridges(p => …)) with a real credential from
http.AddAuthentication()..., keeping BridgeCallers.IsOnDevice(ctx.HttpContext) for the device. Never a policy
that allows everyone in release.BridgeCallers.IsLocalConnection(ctx) or IsOnDevice(ctx) — never IsLocal(ctx.Connection.RemoteIpAddress) alone,
which a tunnel caller passes. Tunneled requests must carry the tunnel's own host.http.AddAuthentication(), http.AddAuthorization(...) (every call
applies), server.UseAuthentication(); server.UseAuthorization(); in http.Configure. Nothing is authenticated by
default unless the app sets a fallback policy. WebAppPolicies.Session accepts only the WebView. Bridge policy and
endpoint policies are separate, and the bridges enforce theirs without the app's pipeline.AddHubsBridge serves hubs at /hubs, outside the bridge prefix: the bridge
policy doesn't apply there — each hub's own rules do (MaxClients, the page refusing in OnConnectedAsync,
AllowTunnel) — and other devices reach them only once the app binds past loopback. Treat hub arguments as untrusted
input from other devices.ReleaseServerUpdateProvider compiled
into the app. GitHub releases are not signed — the asset's SHA-256 (digest) is checked when GitHub reports it — so
prefer the release server when anything other than repository write access must stand between an attacker and the app.Everything is trim/AOT-clean. Generated code must use source-generated JsonTypeInfo, never reflection-based
serialization or JsonObject bodies.
What SKILL.md sets; muted values are Claude Code's defaults
57 skills in this plugin
/localizegenGenerate strongly-typed localization classes from .resx resource files using Shiny.Extensions.Localization.Generator for .NET applications/shiny-accessorysetupGenerate code using Shiny.BluetoothLE.AccessorySetup - the system accessory pairing sheet for BLE devices (AccessorySetupKit on iOS 18+, CompanionDeviceManager on Android) with no MFi, no location prompt and no general Bluetooth prompt on iOS; picked accessories open as Shiny.BluetoothLE peripherals, and Android adds background presence (device appeared / disappeared) events/shiny-actorsGenerate code using Shiny.Actors — Orleans-style virtual actors without the ceremony, AOT/trim-clean, running anywhere .NET runs including .NET MAUI and Blazor WebAssembly. Covers actor interfaces and source-generated proxies, the ShinyActorBuilder (AddShinyActors), persistent state with ETags, named states and auto-save, event-sourced JournaledActor with snapshots, state and event migrations, typed streams (durable, implicit consumers), timers and persistent reminders (background jobs via Shiny.Jobs, on-time OS notifications via Shiny.Notifications), concurrency control ([Reentrant], [AlwaysInterleave], [ReadOnly], [StatelessWorker]), call filters and request context, OpenTelemetry traces and metrics, remoting over HTTP (Shiny.Net.HttpServer server, RemoteActorSystem client), mDNS discovery of actor servers, Shiny.DocumentDb storage (SQLite, PostgreSQL, IndexedDB...), and the ActorTestHost testing kit.npx claudepluginhub shinyorg/skills --plugin shinyOther plugins' skills for the same job