Integrate an SDK · Flutter
Flutter SDK
The Dart runtime ships in bug_capsule 0.4.2, with the runtime, pure-Dart core, bundled integration libraries and the bugcapsule CLI. Capsules report sdk.name: bug_capsule_flutter. Interaction and crash capsules use spec v2 and need the current CLI.
- Requirements
- Dart SDK ^3.10, Flutter ≥ 3.41
- Import
import 'package:bug_capsule/bug_capsule.dart';- Pinned ranges
bloc^9,riverpod^3,get^4.6,mobx^2.3,dio^5.9,http^1.5,go_router14–18,shared_preferences^2.5
The package depends on every library it integrates with, so your app's versions must fall in the ranges above even for libraries you don't use. Unused code is tree-shaken out of release builds. If pub get fails on a version conflict, this is usually why.
1. Add the dependency
dependencies:
bug_capsule: 0.4.2
Optional: native crash reporting
For native crashes in plugins or the Flutter engine, ANRs and app hangs, add the published native plugin:
dependencies:
bug_capsule: 0.4.2
bug_capsule_native: 0.1.1
Flutter registers the plugin automatically and BugCapsule.init starts it. Android requires API 23+. On iOS, set a minimum deployment target of iOS 15 and enable Swift Package Manager:
flutter config --enable-swift-package-manager
CocoaPods alone does not enable native crash reporting on iOS. See native crash coverage and release symbols.
Optional signed patch runtime
Add the published patch package alongside the core SDK when your app needs replacements of explicitly registered logic or surfaces:
dependencies:
bug_capsule: 0.4.2
bug_capsule_patch: 0.1.0
bug_capsule_patch includes Android JNI libraries and an iOS device/simulator XCFramework. No engine checkout or separate native runtime download is required to install it. Android requires API 23+; iOS requires iOS 15+. The iOS patch plugin uses CocoaPods; the separate native crash plugin's Swift Package Manager setup above is not a replacement for that integration.
Register PatchModule contracts and compiled fallbacks, create a BugCapsulePatchBinding, and pass it as BugCapsuleConfig.patchBinding. If resolving the store directory needs a Flutter plugin, use BugCapsulePatchBinding.deferred so BugCapsule.init still runs first in main. PatchUpdater with HttpPatchTransport verifies and stages signed delivery; activate on the next launch, mark the runtime healthy after checking the app, and flush receipts.
Follow Signed patches: setup, integration and rollback for the complete flow, trust roots, immutable base contracts, scoped delivery credentials and replay identity. Installing the package alone does not make arbitrary Dart code patchable or establish store approval.
2. Connect with your SDK token
SDK tokens and the status API are included in these releases. Use the SDK token from your dashboard for a new integration. Existing explicit API URL and ingest key configuration remains supported.
Generate an SDK token in the dashboard (Project Settings › Keys › SDK tokens; it is shown once) and make BugCapsule.init the first line of main:
import 'package:bug_capsule/bug_capsule.dart';
void main() => BugCapsule.init(
config: const BugCapsuleConfig(token: 'bcsdk.v1.…'),
appRunner: () => runApp(const MyApp()),
);
That is a complete connection. The token (bcsdk.v1.…) holds your BugCapsule address and an upload-only credential: it can fetch the project's SDK settings and send Capsules and monitoring data, nothing else, so it is safe to ship in the app. It works the same for hosted and self-hosted BugCapsule. appVersion and appBuild are optional: they default to the BUGCAPSULE_APP_VERSION / BUGCAPSULE_APP_BUILD dart-defines, then to the version in MonitoringOptions.release, then to unknown / 0. Set them so Capsules and releases carry your real version.
A token that can't be used never stops the app: init doesn't throw or wait, prints one [bugcapsule] … line saying what to fix (an ingest or secret key pasted instead of a token, a damaged copy, a token from a newer SDK) and the app runs without uploads. Being offline, a timeout or a server error is never fatal either: Capsules wait in the on-device outbox and go out when BugCapsule is reachable again. When the token is revoked or has expired, the SDK prints the reason once and stops capture and uploads for the session.
Check the connection
final status = BugCapsule.status;
status.connection.state; // connected, connecting, offline, rejected, invalidToken, …
status.connection.reason; // e.g. token_revoked
status.connection.message; // what to do about it
status.connection.configFetchedAt; // 1st confirmation: configuration fetched
status.connection.firstEventAcceptedAt; // 2nd confirmation: first event received …
status.connection.firstCapsuleAcceptedAt; // … or first Capsule received
status.instrumentation.missing; // e.g. [network, navigation, app_state]
status.instrumentation.sourcePinned; // false without BUGCAPSULE_GIT_SHA, or in a dirty build
status.instrumentation.sourceGap; // why, when it isn't pinned
state (.code) | Meaning |
|---|---|
notConfigured (not_configured) | No token and no backend: capture runs on the device only |
invalidToken / unsupportedTokenVersion | The token can't be used; message says why |
connecting | No configuration fetched yet in this session |
connected | The configuration was fetched (basic connectivity) |
offline | BugCapsule can't be reached; data is kept and retried with backoff |
rejected | The token was refused (reason: token_revoked, token_expired, token_unknown, …); capture and uploads are off for the session |
disabled | enabled: false, or capture switched off for the project |
The two confirmations are separate, as they are in the dashboard's onboarding and SDK token list: Configuration fetched proves address, token and network; First event or Capsule received proves captured data reaches your project. Being connected is not the same as complete replay: that is instrumentation, and the next step.
3. Add the progressive adapters
Add replay integrations one at a time. Each one you skip shows up in BugCapsule.status.instrumentation.missing.
Step (missing entry) | Gives replay | Add |
|---|---|---|
network | Recorded responses served as fixtures | BugCapsuleDio or BugCapsuleHttp |
navigation | The route restored | BugCapsuleGoRouter (BugCapsuleNavigatorObserver adds monitoring breadcrumbs only) |
app_state | App state snapshotted and restored | BugCapsuleBloc, BugCapsuleRiverpod, BugCapsuleNotifiers, BugCapsuleGetx, BugCapsuleMobx or BugCapsuleSharedPreferences |
import 'package:bug_capsule/bug_capsule.dart';
final bugCapsuleDio = BugCapsuleDio(rules: [
// Fields that differ on every run must not affect request matching.
EndpointRule('POST', '/api/checkout', ignoreBodyFields: {'timestamp', 'nonce'}),
]);
final bugCapsuleRouter = BugCapsuleGoRouter();
void main() => BugCapsule.init( // first line of main, before ensureInitialized
config: const BugCapsuleConfig(
token: 'bcsdk.v1.…',
appVersion: '1.4.0',
appBuild: '52',
mode: CaptureMode.qa, // or --dart-define=BUGCAPSULE_MODE=qa
),
integrations: [
BugCapsuleBloc(states: [
BugCapsuleState<CartBloc, CartState>(toJson: (s) => s.toJson(), fromJson: CartState.fromJson),
]),
bugCapsuleDio,
bugCapsuleRouter,
BugCapsuleSharedPreferences(allowPrefixes: ['cart.', 'onboarding_']),
],
appRunner: () => runApp(const MyApp()),
);
Then, where you build Dio and GoRouter, and for the QA capture button:
bugCapsuleDio.attach(dio); // after any custom adapter; safe before or after init
final router = GoRouter(initialLocation: bugCapsuleRouter.initialLocation('/'), routes: [...]);
bugCapsuleRouter.attach(router);
MaterialApp.router(
routerConfig: router,
builder: (context, child) => BugCapsuleOverlay(child: child!), // QA capture button
);
initcallsWidgetsFlutterBinding.ensureInitialized()itself and runs your app insidewithClock, soclock.now()is the replay clock.- Startup order: look for a replay request (ignored in release builds) → open storage, outbox and cached remote config, set up integrations, take the launch checkpoint, install error handlers and the pointer route →
appRunner()→ refresh remote config → flush the outbox. - Capture setup has a 5 s budget. If it fails or times out the app runs without capture (reason printed with
debugPrint). A secondinitthrowsStateError. - The overlay only shows when
showOverlayis true (default: any mode but production), the app is recording, and not replaying.
Self-hosted or existing setups (advanced)
A self-hosted BugCapsule issues tokens that carry its own address, so the token setup works there unchanged. Apps that already pass an explicit address and ingest key keep working:
config: const BugCapsuleConfig(
appVersion: '1.4.0',
appBuild: '52',
backend: BugCapsuleBackendConfig(url: 'https://api.bugcapsule.com', ingestKey: 'bci_...'), // never a bcs_ key
),
backend wins when both are set (the SDK prints that the token was ignored), and BugCapsule.status.connection.source says which one is in use.
4. Build with the commit pinned
Pass the git SHA in every build that can capture, production release builds included. Without it a capsule is partial (build.gitSha) and bugcapsule run can't check out the code that failed. Add BUGCAPSULE_MODE=qa only to QA builds.
VERSION=$(grep '^version:' pubspec.yaml | awk '{print $2}' | tr -d "\"'\r") # for example 1.4.0+52
BUILD=$(printf '%s\n' "$VERSION" | sed -n 's/.*+//p') # empty without +build
flutter build ipa \
--dart-define=BUGCAPSULE_GIT_SHA=$(git rev-parse HEAD) \
--dart-define=BUGCAPSULE_APP_VERSION=${VERSION%+*} \
--dart-define=BUGCAPSULE_APP_BUILD=$BUILD \
--dart-define=BUGCAPSULE_MODE=qa
VERSION=$(grep '^version:' pubspec.yaml | awk '{print $2}' | tr -d "\"'\r") # for example 1.4.0+52
BUILD=$(printf '%s\n' "$VERSION" | sed -n 's/.*+//p') # empty without +build
flutter build ipa \
--dart-define=BUGCAPSULE_GIT_SHA=$(git rev-parse HEAD) \
--dart-define=BUGCAPSULE_APP_VERSION=${VERSION%+*} \
--dart-define=BUGCAPSULE_APP_BUILD=$BUILD
From 0.4.2, a build without BUGCAPSULE_GIT_SHA (or built dirty) prints one [bugcapsule] line per launch while capture is enabled, and BugCapsule.status.instrumentation.sourcePinned is false. Capsule eligibility is unchanged: the missing SHA stays a non-blocking partial gap. bugcapsule inspect explains what such a capsule loses.
If your CI overrides --build-name or --build-number, pass those same values to BUGCAPSULE_APP_VERSION and BUGCAPSULE_APP_BUILD.
The SDK reads these dart-defines: BUGCAPSULE_MODE, BUGCAPSULE_GIT_SHA, BUGCAPSULE_GIT_DIRTY, BUGCAPSULE_APP_VERSION, BUGCAPSULE_APP_BUILD and BUGCAPSULE_REPLAY_URL (set by the CLI). An invalid BUGCAPSULE_MODE value throws. The demo app also reads BUGCAPSULE_TOKEN (and, advanced, BUGCAPSULE_BACKEND_URL + BUGCAPSULE_INGEST_KEY), but those are the demo's own; pass the token to BugCapsuleConfig in your code as above.
State management
All integrations come with the package; use the ones that match your app and combine them freely (for example Riverpod with package:http).
BugCapsuleBloc(
states: [
BugCapsuleState<CartBloc, CartState>(
toJson: (s) => s.toJson(),
fromJson: CartState.fromJson,
eventToJson: (e) => e.toJson(), // optional
),
],
recordStateData: null, // default: true except in production
maxStateBytes: 64 * 1024,
treatErrorsAsFailures: true,
)
Installs a global BlocObserver (chaining the previous one). No per-bloc setup. Events, states and errors become bloc.* events; registered states go into periodic checkpoints and are restored by creation order (CartBloc#0).
final bugCapsuleRiverpod = BugCapsuleRiverpod(states: [
BugCapsuleRiverpodState<Cart>(cartProvider, toJson: (c) => c.toJson(), fromJson: Cart.fromJson),
]);
// in init: integrations: [bugCapsuleRiverpod, ...]
appRunner: () => runApp(ProviderScope(observers: [bugCapsuleRiverpod.observer], child: const MyApp())),
NotifierProvider, AsyncNotifierProvider, StreamNotifierProvider (and families) restore on their own. Providers from riverpod_generator need a restore: callback and a registration. id defaults to provider.name; with neither, the constructor throws. An AsyncNotifier whose build finishes after the restore overwrites the restored state.
final bugCapsuleNotifiers = BugCapsuleNotifiers();
ChangeNotifierProvider(
create: (_) => bugCapsuleNotifiers.track(CartModel(), id: 'cart',
toJson: (m) => m.toJson(),
restore: (m, json) => m.replaceWith(CartModel.fromJson(json))),
child: ...,
);
Works with any Listenable (ChangeNotifier, ValueNotifier). Objects tracked before init are not recorded. untrack(object) stops tracking.
final bugCapsuleGetx = BugCapsuleGetx();
class CartController extends GetxController {
final coupon = bugCapsuleGetx.trackRx(''.obs, id: 'cart.coupon'); // primitives need no serializer
final items = bugCapsuleGetx.trackRx(<CartItem>[].obs, id: 'cart.items',
toJson: (items) => {'items': [for (final i in items) i.toJson()]},
fromJson: (json) => [for (final i in json['items'] as List) CartItem.fromJson(i as Map<String, Object?>)]);
}
// GetBuilder controllers: bugCapsuleGetx.track(controller, id: 'cart', toJson: ..., restore: ...)
update([ids]) is not seen, only update().
final bugCapsuleMobx = BugCapsuleMobx(); // spy-based: observable writes, actions, reaction errors recorded on their own
final cart = bugCapsuleMobx.track(CartStore(), id: 'cart',
toJson: (s) => s.toJson(),
restore: (s, json) => s.replaceWith(json)); // restore runs inside an action
Observable writes are redacted by field name (_LoginStore.password). Options: recordObservables, treatReactionErrorsAsFailures, context.
Redux has no integration: its state is re-executed by replay but not checkpointed or restored.
HTTP and navigation
| Library | Integration | Wiring |
|---|---|---|
dio, retrofit | BugCapsuleDio | attach(dio) wraps dio.httpClientAdapter (not an interceptor). Call it after setting a custom adapter. |
http, chopper, anything taking an http.Client | BugCapsuleHttp | client() or client(existingClient). Same request keys and events as Dio. |
go_router 14–18 | BugCapsuleGoRouter | initialLocation('/') + attach(router) (listens to the router delegate). sanitizeLocation: for secrets in paths. |
shared_preferences | BugCapsuleSharedPreferences | See the note below. |
final bugCapsuleHttp = BugCapsuleHttp(
rules: [EndpointRule('POST', '/api/checkout', ignoreBodyFields: {'nonce'})],
exclude: (req) => req.url.path.startsWith('/api/payments'), // record method/URL/status/timing only
);
final client = bugCapsuleHttp.client();
final chopper = ChopperClient(client: bugCapsuleHttp.client(), ...);
Both HTTP integrations take rules, ignoreQuery (default _ ts timestamp nonce cachebust), ignoreBodyFields, maxBinaryBytes and maxKeyBodyBytes (64 KiB), maxBodyWait (30 s) and exclude. EndpointRule(method, path, {ignoreQuery, ignoreBodyFields, matchBodyFields}) accepts * as method and a trailing * in the path.
BugCapsuleSharedPreferences() with no arguments captures every key (default allowPrefixes: [''], only flutter.bugcapsule.* denied). Pass explicit allowPrefixes for anything but a demo.
Not captured: dart:io HttpClient used directly, cupertino_http/cronet_http without an http.Client wrapper, GraphQL subscriptions. WebSockets, platform channels and native SDKs (Firebase, maps, payments) are captured only through their own integrations, from Flutter SDK 0.4.1: see the next section.
WebSockets, platform channels and native SDKs
Available from Flutter SDK 0.4.1-beta.7. Capsules that use them are written as capsule spec v2, which older CLIs reject. Update the CLI everywhere it runs, CI included, before you add them. Capsules without them stay v1.
Each recorded interaction is replayed offline. Replay never reaches the real socket, plugin or SDK, also when the capsule has no recording for a call: the call fails instead. Replay needs the same integrations in the build, and the CLI checks that before the app starts (INCOMPATIBLE, dependency.unsupported). A verify with missing, extra or mismatched interactions is never FIXED (interaction divergences).
| Dependency | Integration | Setup |
|---|---|---|
WebSockets (web_socket_channel 3, dart:io WebSocket) | BugCapsuleWebSocket | Open sockets with connect(uri) or connectIo(url) |
| Platform channels (MethodChannel, EventChannel, BasicMessageChannel) | BugCapsulePlatformChannels | List the channels and their codecs; BugCapsule.init first in main |
| Firebase Auth and Firestore, geolocator, Google Maps, Stripe | Bundled in bug_capsule | Integration libraries |
| Any other SDK | NativeAdapter | Wrap the operations your app uses; check it with AdapterConformance |
final sockets = BugCapsuleWebSocket();
final channels = BugCapsulePlatformChannels(channels: [
PlatformChannel.method('plugins.example.com/battery'),
PlatformChannel.event('plugins.example.com/charging'),
]);
void main() => BugCapsule.init( // first line of main: it creates the binding
config: const BugCapsuleConfig(token: 'bcsdk.v1.…'),
integrations: [sockets, channels, bugCapsuleDio /*, ... */],
appRunner: () => runApp(const MyApp()),
);
WebSockets
final channel = sockets.connect(Uri.parse('wss://quotes.example.com/v1')); // a WebSocketChannel
await channel.ready;
channel.sink.add('{"op":"subscribe","symbol":"ACME"}');
channel.stream.listen(onQuote);
final io = await sockets.connectIo('wss://quotes.example.com/v1'); // a dart:io WebSocket (not on web)
- Capture records the connection, the negotiated protocol, every text frame sent and received, errors, and who closed the connection with which code. Outside capture and replay,
connectis a plainWebSocketChannel.connect. - Binary frames are recorded as their size only unless you pass
BugCapsuleWebSocket(captureBinary: true); replay can't deliver size-only frames.metadataOnly: (url) => …keeps every frame of a socket as sizes only (for example a chat socket with personal messages); such a socket can't be replayed faithfully. - A frame that redaction changed is not replayed unless you pass
redactedReplayable: true(only when the app doesn't branch on the redacted fields). - Replay never connects: it serves the recorded server side in memory with the recorded timing and compares what the app sends. Connections are matched by URL (minus
ignoreQuery, default_ ts timestamp nonce cachebust) and order. Your reconnect logic stays yours: each recorded attempt is replayed in order.
Platform channels
BugCapsulePlatformChannels(channels: [
PlatformChannel.method('plugins.example.com/battery'), // StandardMethodCodec
PlatformChannel.method('acme/settings', codec: const JSONMethodCodec()),
PlatformChannel.event('plugins.example.com/charging'),
PlatformChannel.message('acme/status', codec: const StringCodec()), // default StandardMessageCodec
])
- Allowlist. Only listed channels are recorded, in both directions: calls from Dart and calls the platform makes into Dart, results, errors, missing handlers and EventChannel events. Framework channels (
flutter/*) and BugCapsule's own can't be listed. - Codecs. Give each channel the codec it uses. The standard, JSON, string and binary codecs are understood. Pigeon and other custom codecs decode to objects BugCapsule can't serialize: those payloads are recorded as sizes only with a
codec.unsupportedgap and can't be replayed. - Binding. Plugins on the default messenger are covered because
BugCapsule.initcreates the binding and wraps that messenger. Callinitfirst inmain, beforeWidgetsFlutterBinding.ensureInitialized()and before any plugin is used. Channels you create yourself can also takechannels.messenger()explicitly. - EventChannels always need that binding, even with your own messenger: Flutter sends their
listenandcancelcalls through the default messenger.
A late setup doesn't cover plugins. If the binding already exists when BugCapsule.init runs, capture records a channel.late gap and replay reports the material dependency.late divergence, instead of pretending to cover traffic it can't see.
Native SDK adapters
For an SDK without an adapter package, extend NativeAdapter and route the operations your app uses through call (one result) and subscribe (a stream). Capture runs the real SDK and records what the app got; replay returns the recorded values through decode and never calls the SDK.
class WeatherAdapter extends NativeAdapter {
WeatherAdapter(this.api);
final WeatherApi api;
@override String get name => 'weather';
@override String get adapter => 'example.weather'; // the id capsules and capture settings use
@override List<String> get operations => ['forecast', 'alerts'];
Future<Forecast> forecast(String city) => call(
'forecast',
args: {'city': city},
invoke: () => api.forecast(city),
encode: (f) => f.toJson(),
decode: (json) => Forecast.fromJson(json as Map<String, Object?>),
);
Stream<Alert> alerts(String region) => subscribe(
'alerts',
args: {'region': region},
open: () => api.alerts(region),
encode: (a) => a.toJson(),
decode: (json) => Alert.fromJson(json as Map<String, Object?>),
);
}
- Calls are matched by operation, redacted arguments and invocation order. A call the capsule doesn't contain fails with
NativeAdapterException('bugcapsule.unrecorded')and anative.unrecordeddivergence. OverridedescribeError/rebuildErrorto record and rethrow the SDK's own exception types. - Values round-trip losslessly (64-bit integers, whole-number doubles, bytes, typed lists, maps with non-string keys).
- Check an adapter in a plain test with
AdapterConformancefrompackage:bug_capsule/testing.dart: it runs a scenario against the dependency, replays it offline with a fresh adapter and compares what the app saw.
import 'package:bug_capsule/testing.dart';
test('weather adapter replays offline', () async {
final result = await AdapterConformance.run(
create: (replaying) => WeatherAdapter(replaying ? ThrowingApi() : FakeApi()), // replay must not call the API
scenario: (adapter) async => (await adapter.forecast('Oslo')).toJson(),
);
expect(result.problems, isEmpty);
});
Bundled integrations
Version 0.4.1-beta.12 bundles Firebase, geolocator, Google Maps and Stripe inside bug_capsule. Remove the four standalone adapter dependencies and change their imports as shown below. Constructors and recorded adapter identifiers stay unchanged. The native crash bridge and patch runtime remain separate. Versions before 0.4.1-beta.12 still use the old adapter packages.
The bundled SDK needs Dart 3.10+ and Flutter 3.41+. Firebase plugins become transitive dependencies of every consumer, including their native build requirements. Integrations only activate when registered. Continue installing and configuring the real Maps, geolocator and Stripe plugins when your app uses them.
dependencies:
bug_capsule: ^0.4.1
import 'package:bug_capsule/bug_capsule.dart';
import 'package:bug_capsule/firebase.dart';
import 'package:bug_capsule/geolocator.dart';
import 'package:bug_capsule/google_maps.dart';
import 'package:bug_capsule/stripe.dart';
final auth = BugCapsuleFirebaseAuth();
final firestore = BugCapsuleFirestore();
void main() => BugCapsule.init(
config: const BugCapsuleConfig(token: 'bcsdk.v1.…'),
integrations: [auth, firestore, BugCapsuleGeolocator(), BugCapsuleGoogleMaps(), BugCapsuleStripe()],
appRunner: () async {
await Firebase.initializeApp(); // inside appRunner: BugCapsule.init comes first
Stripe.publishableKey = 'pk_live_…';
runApp(const MyApp());
},
);
Geolocator, Google Maps and Stripe install a delegating platform instance, so app code that calls Geolocator.*, GoogleMap or Stripe.instance stays unchanged. Firebase reads go through the adapters (auth.authStateChanges(), firestore.getDocument('orders/42'), firestore.getQuery(…)). The SDK's integration guides list supported operations and limits.
Validation so far: a fresh app built for the iOS Simulator recorded real Firebase Auth, Firestore and Geolocator calls. The Maps and Stripe adapters were installed but not exercised there, and Android device results are not recorded yet. Treat these as dev releases and inspect real capsules before you rely on them.
| Library | Integration (adapter id) | Covers | Tested against |
|---|---|---|---|
package:bug_capsule/firebase.dart | BugCapsuleFirebaseAuth (bug_capsule.firebase_auth), BugCapsuleFirestore (bug_capsule.cloud_firestore) | Identity state (currentUser, authStateChanges, userChanges); Firestore document and query reads, listeners and write outcomes, called through the adapter. Not sign-in or token calls, transactions, batched writes, aggregate queries or Messaging: those reach Firebase during replay. | firebase_auth 7.0.1, cloud_firestore 7.1.0, firebase_core 5.1.0 |
package:bug_capsule/geolocator.dart | BugCapsuleGeolocator (bug_capsule.geolocator) | Permissions, service state, current and last position, position and service-status streams. App code is unchanged (Geolocator.* goes through the adapter). | geolocator_platform_interface 4.4.1 |
package:bug_capsule/google_maps.dart | BugCapsuleGoogleMaps (bug_capsule.google_maps_flutter) | Camera commands, coordinate queries, taps, long presses, marker taps and camera events. The map still renders through the real platform view; replayed camera commands don't move it. | google_maps_flutter_platform_interface 2.17.0 |
package:bug_capsule/stripe.dart | BugCapsuleStripe (bug_capsule.flutter_stripe) | Payment sheet, confirmPayment and createPaymentMethod outcomes. Replay shows no Stripe UI and returns the recorded outcome. Set it up in BugCapsule.init before the app first touches Stripe, including Stripe.publishableKey. | stripe_platform_interface 14.2.0 |
Operations a package doesn't support still reach the SDK while capturing and add an operation.unsupported gap (the capsule becomes partial); in replay they fail as unrecorded. Calls made before BugCapsule.init, or straight on the SDK instead of the adapter, are not recorded. What the Firebase and Stripe adapters never record is listed under Privacy.
Interaction limits
- Capture bounds, shared by every adapter: 64 KiB per payload (larger: truncated), 1 MiB of interaction payloads per capsule window (later ones: sizes only), 32 open connections and subscriptions (more aren't captured,
connections.limitgap). A gap makes that dependencypartial; if replay needs a payload that wasn't kept, it reports*.noPayloadand the attempt can't count as clean. - A connection or subscription open at a periodic checkpoint can't be restored: the capsule is ineligible and replay ends
INCOMPATIBLE(dependency.unrestorable). Sessions within the 5-minute window replay from launch and avoid this. - Not covered: sockets opened with other constructors, Socket.IO and other protocols on top of WebSockets, ping/pong frames, unlisted or framework channels, background isolates, additional engines, plugins with their own messenger, FFI, platform views, textures, and native work that never crosses a channel.
- Your project's capture settings can turn off one adapter by its id, or lower the interaction payload limit, without touching HTTP capture (capture settings).
Make more bugs eligible
| Hook | Why |
|---|---|
onPressed: BugCapsule.action('cart.checkout', () => ...) | Semantic replay when the developer's screen differs from QA's. actionWithPayload(id, (payload) => ...) for actions with data. |
BugCapsule.trackText('login.email', controller) | Typed text is replayed. Sensitive ids (password, otp, …) are redacted; sensitive: true redacts any field. Use it for every obscured field. untrackText when disposing. |
BugCapsule.check('cart_total_non_negative', total >= 0) / BugCapsule.fail(id) | Wrong behaviour that doesn't throw becomes a checkable failure |
clock.now() (package clock) instead of DateTime.now() | Replay restores the recorded wall clock |
BugCapsule.random instead of Random() | Seeded per session, same seed in replay |
Uncaught errors are captured from FlutterError.onError (non-silent) and PlatformDispatcher.onError, both chained to the previous handlers. A capsule is written 300 ms after a new failure signature, at most 3 per session.
BugCapsule.log('legacy cache migrated', level: 'warn');
final result = await BugCapsule.capture(note: 'QA: total looks wrong'); // null when not recording
await BugCapsule.flushUploads();
await BugCapsule.refreshRemoteConfig();
final status = BugCapsule.status; // connection + instrumentation
final files = await BugCapsule.savedCaptures(); // newest 20
Configuration reference
const BugCapsuleConfig(...)
| Field | Default | Notes |
|---|---|---|
token | null | The SDK token (bcsdk.v1.…) from the dashboard: all a connection needs. Ignored when backend is set |
appVersion, appBuild | BUGCAPSULE_APP_VERSION / BUGCAPSULE_APP_BUILD, then the version in MonitoringOptions.release, then unknown / 0 | |
appId, appName, flavor | null | |
mode | BUGCAPSULE_MODE, else kReleaseMode ? production : debug | Debug and QA always record |
enabled | true | Local master switch: no capture code runs when false |
backend | null | BugCapsuleBackendConfig(url:, ingestKey:): the advanced alternative to token, and wins over it. With neither: nothing is uploaded and capture settings aren't fetched |
gitSha | BUGCAPSULE_GIT_SHA | gitDirty from BUGCAPSULE_GIT_DIRTY=true |
stateSchemaVersion | 1 | Bump when serialized state changes shape |
checkpointInterval / window / maxEvents | 30 s / 5 min / 20 000 | |
productionSampleRate | 0.1 | |
autoCaptureOnFailure / maxCapsulesPerSession | true / 3 | |
captureNetworkBodies / maxBodyBytes | off in production; on in debug/QA / 256 KiB | off in production unless set to true; binary bodies need maxBinaryBytes on the Dio/http integration (What's new) |
collectionEnabled / savedCaptureMaxAge | true / 7 days | consent default and saved-capture expiry; see consent and local data |
redactKeys, redactHeaders, redactPatterns | [] | redactPatterns: List<RegExp> |
beforeRecord(type, data) | null | Return null (or throw) to drop the event |
beforeCheckpoint(integration, data) | null | Return null to leave that integration out |
outboxLimits | OutboxLimits() 10 / 10 MiB / 7 days | |
maxStaleConfig | 7 days | |
showOverlay | mode ≠ production | |
ignoreError(error) | null | |
labels | {} | Scrubbed like free text |
replayUrl | null | Tests only |
Replay specifics
- iOS simulator: the CLI runs
flutter build ios --simulatoronce, then launches the installed app per attempt and hands over the replay request through a file in the app sandbox (environment variables don't reach the app on recent simulator runtimes). - Other devices:
flutter runwith a dart-define per attempt. Android goes throughadb reverse; this path is implemented but has not been exercised end to end. Physical iOS devices need--lan. - Release builds never enter replay mode (
BUGCAPSULE_REPLAY_URLand request files are ignored whenkReleaseMode). - Pointer replay assumes the same logical screen size; otherwise the CLI scales coordinates and falls back to semantic actions when they exist.
- Idle gaps over 1.5 s shrink to ~0.3 s when both recording and app are idle (running animations get up to 2 s). App
Timers aren't tracked; use--no-compress-idleif replay depends on one.
Writing a custom integration
class SecureStoreIntegration extends BugCapsuleIntegration {
@override
String get name => 'secure_store';
@override
Future<void> setUp(BugCapsuleSession session) async {
// record diagnostic events: session.record('secure_store.read', {'key': key});
}
@override
Object? snapshot(CheckpointKind kind) => {'flags': _flags}; // goes to checkpoint.data['secure_store']
@override
Future<void> restore(Object? data, BugCapsuleSession session) async { _flags = ...; }
@override
void describeEligibility(EligibilityBuilder eligibility, RecordedWindow window) {}
}
Each checkpoint.data key belongs to one integration; only that integration reads it back. Data you return passes through redaction and beforeCheckpoint.
Demo app
example/bug_capsule_demo is a shop with planted "cannot reproduce" bugs.
| Bug | How to trigger | What replay needs |
|---|---|---|
| Profile/recommendations race | Tap Refresh picks until it crashes (~1 in 4) | Recorded response latencies |
| Legacy cart cache | Simulate upgrade from v0.9, restart, open cart | Storage from the launch checkpoint |
| Negative total | Open cart until subtotal < $100, apply SAVE100 | Typed text + server cart + custom assertion |
| Discontinued item | Open cart until "unavailable" shows, checkout | The server response with price: null |
| Orders stuck loading | Open My orders until it spins > 4 s | The recorded 202 + watchdog assertion |
| Live quotes (from 0.5) | Open Live quotes; after the feed's server restarts and the app reconnects, a repeated quote throws Quote went stale | The recorded WebSocket traffic (spec v2); replay works with the quote server off |
Upgrading
To 0.4.1-beta.7 (capsule spec v2)
- Capsules that record WebSockets, platform channels or native adapters are written as spec v2. Older CLIs reject them; update the CLI everywhere it runs, CI included, before you add these integrations. Capsules without them stay v1.
- Replaying a v2 capsule needs the same adapters in the build. A missing one ends the attempt
INCOMPATIBLEwithdependency.unsupported. bugcapsule verifyreports reason codes with each run, and BugCapsule never marks a capsule fixed by a run with interaction divergences.
From the 12-package layout to 0.4 (one package)
- Replace every
bug_capsule_*dependency with the singlebug_capsuleline, and everypackage:bug_capsule_*/…import withpackage:bug_capsule/bug_capsule.dart. The API is unchanged. - CLI:
dart pub global deactivate bug_capsule_cli, then activatebug_capsule(see CLI install). - The old
packages/bug_capsule_*folders in the SDK repo only hold stale.dart_tooloutput; ignore them.
From 0.1
BugCapsule.resetForTest()returns aFuture; await it in tests.- The upload outbox is bounded; 0.1 files are kept and count toward the limits.
- BugCapsule no longer moves a capsule to
fixedon results from CLI 0.1 (which couldn't tell an errored attempt from a passing one). Update the CLI. - Capsules captured by 0.1 with body capture off were keyed without body hashes; replaying them reports those requests as unrecorded.
Monitoring and release readiness
This SDK also sends error events, release-health sessions, traces and feedback. Configure those separately from capsule recording using Monitoring, upload release symbols, and complete the integration checklist. For approved artifacts, versions and upgrade rules, start with Installation and upgrades.