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_router 14–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

i

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 / unsupportedTokenVersionThe token can't be used; message says why
connectingNo configuration fetched yet in this session
connectedThe configuration was fetched (basic connectivity)
offlineBugCapsule can't be reached; data is kept and retried with backoff
rejectedThe token was refused (reason: token_revoked, token_expired, token_unknown, …); capture and uploads are off for the session
disabledenabled: 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 replayAdd
networkRecorded responses served as fixturesBugCapsuleDio or BugCapsuleHttp
navigationThe route restoredBugCapsuleGoRouter (BugCapsuleNavigatorObserver adds monitoring breadcrumbs only)
app_stateApp state snapshotted and restoredBugCapsuleBloc, 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
);

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

LibraryIntegrationWiring
dio, retrofitBugCapsuleDioattach(dio) wraps dio.httpClientAdapter (not an interceptor). Call it after setting a custom adapter.
http, chopper, anything taking an http.ClientBugCapsuleHttpclient() or client(existingClient). Same request keys and events as Dio.
go_router 14–18BugCapsuleGoRouterinitialLocation('/') + attach(router) (listens to the router delegate). sanitizeLocation: for secrets in paths.
shared_preferencesBugCapsuleSharedPreferencesSee 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

i

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).

DependencyIntegrationSetup
WebSockets (web_socket_channel 3, dart:io WebSocket)BugCapsuleWebSocketOpen sockets with connect(uri) or connectIo(url)
Platform channels (MethodChannel, EventChannel, BasicMessageChannel)BugCapsulePlatformChannelsList the channels and their codecs; BugCapsule.init first in main
Firebase Auth and Firestore, geolocator, Google Maps, StripeBundled in bug_capsuleIntegration libraries
Any other SDKNativeAdapterWrap 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)

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
])
!

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?>),
      );
}
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.

LibraryIntegration (adapter id)CoversTested against
package:bug_capsule/firebase.dartBugCapsuleFirebaseAuth (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.dartBugCapsuleGeolocator (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.dartBugCapsuleGoogleMaps (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.dartBugCapsuleStripe (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

Make more bugs eligible

HookWhy
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(...)

FieldDefaultNotes
tokennullThe SDK token (bcsdk.v1.…) from the dashboard: all a connection needs. Ignored when backend is set
appVersion, appBuildBUGCAPSULE_APP_VERSION / BUGCAPSULE_APP_BUILD, then the version in MonitoringOptions.release, then unknown / 0
appId, appName, flavornull
modeBUGCAPSULE_MODE, else kReleaseMode ? production : debugDebug and QA always record
enabledtrueLocal master switch: no capture code runs when false
backendnullBugCapsuleBackendConfig(url:, ingestKey:): the advanced alternative to token, and wins over it. With neither: nothing is uploaded and capture settings aren't fetched
gitShaBUGCAPSULE_GIT_SHAgitDirty from BUGCAPSULE_GIT_DIRTY=true
stateSchemaVersion1Bump when serialized state changes shape
checkpointInterval / window / maxEvents30 s / 5 min / 20 000
productionSampleRate0.1
autoCaptureOnFailure / maxCapsulesPerSessiontrue / 3
captureNetworkBodies / maxBodyBytesoff in production; on in debug/QA / 256 KiBoff in production unless set to true; binary bodies need maxBinaryBytes on the Dio/http integration (What's new)
collectionEnabled / savedCaptureMaxAgetrue / 7 daysconsent default and saved-capture expiry; see consent and local data
redactKeys, redactHeaders, redactPatterns[]redactPatterns: List<RegExp>
beforeRecord(type, data)nullReturn null (or throw) to drop the event
beforeCheckpoint(integration, data)nullReturn null to leave that integration out
outboxLimitsOutboxLimits() 10 / 10 MiB / 7 days
maxStaleConfig7 days
showOverlaymode ≠ production
ignoreError(error)null
labels{}Scrubbed like free text
replayUrlnullTests only

Replay specifics

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.

BugHow to triggerWhat replay needs
Profile/recommendations raceTap Refresh picks until it crashes (~1 in 4)Recorded response latencies
Legacy cart cacheSimulate upgrade from v0.9, restart, open cartStorage from the launch checkpoint
Negative totalOpen cart until subtotal < $100, apply SAVE100Typed text + server cart + custom assertion
Discontinued itemOpen cart until "unavailable" shows, checkoutThe server response with price: null
Orders stuck loadingOpen My orders until it spins > 4 sThe 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 staleThe recorded WebSocket traffic (spec v2); replay works with the quote server off

Upgrading

To 0.4.1-beta.7 (capsule spec v2)
From the 12-package layout to 0.4 (one package)
From 0.1

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.