Integrate an SDK · Android
Android SDK
Native Kotlin SDK with a Java-friendly API, an instrumentation replay runner, and a demo shop app. Capsules carry sdk.name: bugcapsule-android and runtime.name: android.
- Coordinates
io.github.bugcapsule:<artifact>:0.4.1- Requirements
- minSdk 23 · Java 17 bytecode · libraries compiled against SDK 36 (README states compileSdk 34+)
- Toolchain
- AGP 8.13, Kotlin 2.2.20
- Distribution
- Maven Central, under
io.github.bugcapsule.
HTTPS on older devices: minSdk 23 covers the SDK runtime. The hosted API currently uses a Let’s Encrypt certificate chain. An unpatched Android 6 emulator cannot validate that chain and reports Trust anchor for certification path not found; capture and replay work locally, but remote configuration and uploads remain offline. Test the backend’s certificate chain on your oldest supported device. Android 7.1.1+ includes ISRG Root X1 according to Let’s Encrypt’s compatibility documentation. Do not disable certificate or hostname validation.
Artifacts
| Artifact | Package | What it does |
|---|---|---|
bugcapsule-android | dev.bugcapsule.android | Core: capsule codec and validator, recorder, redaction, request keys, remote config, outbox, capture (lifecycle, pointers, Back key, failures, crashes), replay engine, Views helpers, SharedPreferences and DataStore checkpoints, state serializers (ViewModels too) |
bugcapsule-okhttp | dev.bugcapsule.okhttp | OkHttp 4 capture and deterministic replay (Retrofit works through it); OkHttp WebSockets (below) |
bugcapsule-navigation | dev.bugcapsule.navigation | Jetpack Navigation route events, checkpoint and restore |
bugcapsule-compose | dev.bugcapsule.compose | Compose helpers: semantic actions, tracked text, navigation effect |
bugcapsule-android-replay | dev.bugcapsule.android.replay | androidTest only. BugCapsuleReplayRunner (an AndroidJUnitRunner) and BugCapsuleReplayTest |
1. Gradle setup
Add Maven Central to your repositories and pin all BugCapsule modules to the same version:
dependencyResolutionManagement {
repositories {
google(); mavenCentral()
}
}
android {
defaultConfig {
// The replay runner must be the instrumentation runner of the app's androidTest APK.
testInstrumentationRunner = "dev.bugcapsule.android.replay.BugCapsuleReplayRunner"
// The CLI passes -PbugcapsuleGitSha=<sha> so capsules and replays carry the build's commit.
// Pass it in every other build too, release included: -PbugcapsuleGitSha=$(git rev-parse HEAD).
buildConfigField("String", "BUGCAPSULE_GIT_SHA",
"\"${providers.gradleProperty("bugcapsuleGitSha").getOrElse("")}\"")
// The SDK token comes from the environment / CI secrets, never from sources.
buildConfigField("String", "BUGCAPSULE_TOKEN",
"\"${providers.environmentVariable("BUGCAPSULE_SDK_TOKEN").getOrElse("")}\"")
}
buildFeatures.buildConfig = true
}
dependencies {
implementation("io.github.bugcapsule:bugcapsule-android:0.4.1")
implementation("io.github.bugcapsule:bugcapsule-okhttp:0.4.1")
implementation("io.github.bugcapsule:bugcapsule-navigation:0.4.1")
implementation("io.github.bugcapsule:bugcapsule-compose:0.4.1") // if you use Compose
implementation("io.github.bugcapsule:bugcapsule-ndk:0.4.1") // native crash events (optional)
implementation("io.github.bugcapsule:bugcapsule-sqlite:0.4.1") // SQLite / Room spans (optional)
androidTestImplementation("io.github.bugcapsule:bugcapsule-android-replay:0.4.1")
// Only if you checkpoint Preferences DataStore:
implementation("androidx.datastore:datastore-preferences:1.1.1")
}
The library modules ship no manifest. Your app must declare android.permission.INTERNET (uploads and the replay socket).
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). It carries your BugCapsule address and an upload-only credential, so it is the only value the app needs:
class ShopApp : Application() {
override fun onCreate() {
super.onCreate()
BugCapsule.init(this, BuildConfig.BUGCAPSULE_TOKEN)
}
}
BugCapsule.init(this, BuildConfig.BUGCAPSULE_TOKEN);
Call it first in Application.onCreate, not from a ContentProvider or App Startup initializer: in replay the runner restores storage right before Application.onCreate. BUGCAPSULE_TOKEN is the buildConfigField from step 1; a string literal works too, since the token ships inside the app anyway.
That is the whole connection: capsule capture and monitoring (errors, ANRs, sessions, screen tracing) start automatically, the configuration is fetched in the background, and app version and build come from the package info. The token is client-visible: it can only fetch the project's SDK configuration and upload Capsules and events. It never reads data. Hosted and self-hosted BugCapsule work the same way. Never put a bcs_ secret key in an app.
init never throws, never blocks on the network and never stops the app from starting. A token that can't be used (empty, damaged, a bare key pasted instead of the token, or a newer token version) logs one line under the BugCapsule tag with what to do, and the app runs without uploads.
Check the connection
val status = BugCapsule.status()
Log.i("Shop", "BugCapsule ${status.connection.state.code}: ${status.connection.message ?: "ok"}, missing ${status.instrumentation.missing}")
status.connection has state, source (TOKEN / BACKEND), apiUrl, reason, message and two separate confirmations: configFetchedAt (Configuration fetched: address, token and network are right) and firstEventAcceptedAt / firstCapsuleAcceptedAt (First event or Capsule received: captured data reached your project). The dashboard shows the same two confirmations during onboarding and in the SDK token list. Neither proves complete replay instrumentation; that is status.instrumentation (recording, network, navigation, appState, nativeCrashes, frameworks, integrations, missing).
state (.code) | Meaning |
|---|---|
NOT_CONFIGURED (not_configured) | No token and no backend: capsules stay on the device |
INVALID_TOKEN / UNSUPPORTED_TOKEN_VERSION | The token can't be used (message says why); the app runs without uploads |
CONNECTING | Configured; the configuration has not arrived yet |
CONNECTED | BugCapsule answered the configuration request |
OFFLINE | No network, a timeout or a server error. Data waits in the bounded outbox and is retried with backoff; the app is unaffected |
REJECTED | The credential was refused; reason is token_revoked, token_expired, token_unknown (or key_unknown_or_revoked for an ingest key) and message says what to do. Capture and uploads stop for this app session. Ship a build with a current token |
DISABLED | enabled(false), capture switched off for the project, or a replay run |
3. Add the progressive adapters
The token proves connectivity; replay also needs the app's inputs. Add the artifacts from step 1 and pass their integrations. Any you skip show up as missing in BugCapsule.status(). Steps 4–8 below wire each one.
| Adapter | Gives replay | status().instrumentation |
|---|---|---|
bugcapsule-okhttp (BugCapsuleOkHttp) | Network fixtures (OkHttp, Retrofit) | network |
bugcapsule-navigation (BugCapsuleNavigation) | Routes, back stack restore | navigation |
BugCapsuleSharedPreferences / BugCapsuleDataStore, registerState / registerViewModel | App state in checkpoints | appState (app_state in missing) |
bugcapsule-compose helpers | Semantic actions, tracked text, screens | frameworks contains compose (after the first composition) |
bugcapsule-ndk | Native crash events, with a crash capsule when a recording journal is available | nativeCrashes |
import dev.bugcapsule.android.BugCapsule
import dev.bugcapsule.android.BugCapsuleConfig
import dev.bugcapsule.android.core.CaptureMode
import dev.bugcapsule.android.core.EndpointRule
import dev.bugcapsule.android.storage.BugCapsuleDataStore
import dev.bugcapsule.android.storage.BugCapsuleSharedPreferences
import dev.bugcapsule.navigation.BugCapsuleNavigation
import dev.bugcapsule.okhttp.BugCapsuleOkHttp
class ShopApp : Application() {
override fun onCreate() {
super.onCreate()
// First thing in Application.onCreate — not a ContentProvider or App Startup initializer:
// in replay the runner restores storage right before Application.onCreate.
BugCapsule.init(
this,
BugCapsuleConfig.builder()
.token(BuildConfig.BUGCAPSULE_TOKEN) // bcsdk.v1.… from the dashboard
.mode(CaptureMode.QA) // default: DEBUG if debuggable, else PRODUCTION
.gitSha(BuildConfig.BUGCAPSULE_GIT_SHA)
.redactKeys("loyaltyId")
.build(),
listOf(
okHttp,
navigation,
BugCapsuleSharedPreferences.builder().allowFile("shop_prefs").build(),
BugCapsuleDataStore.builder().allow("settings").build(),
),
)
}
companion object {
val okHttp = BugCapsuleOkHttp(rules = listOf(
// Fields that change on every run must not affect request matching.
EndpointRule("POST", "/api/checkout", ignoreBodyFields = setOf("timestamp", "nonce"))))
val navigation = BugCapsuleNavigation()
}
}
A second init call is ignored with a warning. Setup errors are caught and the app runs without capture. Besides status(), the SDK exposes BugCapsule.isInitialized, isRecording, isReplaying, mode and session.
Java
BugCapsuleConfig config = BugCapsuleConfig.builder()
.token(BuildConfig.BUGCAPSULE_TOKEN)
.mode(CaptureMode.QA)
.build();
BugCapsule.init(app, config, Arrays.asList(okHttp, navigation));
BugCapsuleViews.onClick(button, "cart.checkout", v -> viewModel.checkout());
BugCapsule.check("cart_total_non_negative", total >= 0, "total " + total);
Self-hosted or existing setups (advanced)
A self-hosted BugCapsule issues tokens that carry its own address, so the token setup above works unchanged. You can still configure the address and ingest credential explicitly; existing apps keep working as they are:
BugCapsuleConfig.builder()
.backend("https://api.bugcapsule.com", BuildConfig.BUGCAPSULE_INGEST_KEY) // bci_…, never a bcs_ key
.build()
When both token and backend are set, the explicit backend wins and the SDK logs that the token was ignored. On an emulator, the token's address must be reachable from the device (a BugCapsule running on your own machine is 10.0.2.2, not 127.0.0.1); use an explicit backend otherwise.
4. Wire OkHttp
Add the SDK interceptor as the innermost application interceptor, after your own. Pass the same BugCapsuleOkHttp instance to init.
val client = OkHttpClient.Builder()
.addInterceptor(AuthInterceptor()) // your interceptors first: they still run in replay
.addInterceptor(ShopApp.okHttp.interceptor) // BugCapsule last
.build()
// or: ShopApp.okHttp.install(builder)
| Constructor parameter | Default | Notes |
|---|---|---|
rules | empty | EndpointRule(method, path, ignoreQuery, ignoreBodyFields, matchBodyFields). path supports :name segments and a trailing *. |
ignoreQuery | _ ts timestamp nonce cachebust | Query params dropped from every request key |
ignoreBodyFields | empty | JSON fields dropped before hashing, for every endpoint |
maxBinaryBytes | 64 KiB | Binary body prefix kept |
maxKeyBodyBytes | 64 KiB | Largest body hashed into the key |
maxBodyWaitMs | 30 000 | After this a still-streaming body is recorded truncated |
exclude | null | RequestFilter { request -> Boolean }: excluded calls record method, URL, status and timing only |
In replay the interceptor answers from the capsule by request key + occurrence after the recorded latency, without calling chain.proceed. An unrecorded request throws ConnectException and reports network.unrecorded. Exchanges recorded as pending (in flight at a crash) are held open until the call is cancelled.
Because replay answers inside the interceptor, interceptors added after it, network interceptors, caching and cookies are not exercised in replay. One-shot and duplex request bodies are never read; they are keyed without a body hash.
5. Navigation
// After the graph is set, on the main thread:
ShopApp.navigation.attach(navHostFragment.navController)
val navController = rememberNavController()
BugCapsuleNavigationEffect(navController, ShopApp.navigation)
BugCapsuleNavigation(sanitizeLocation = LocationSanitizer { it.replace(Regex("/orders/\\d+"), "/orders/:id") }) rewrites locations that contain secrets or ids. Route events carry source: "navigation"; {route, backStack} is snapshotted in periodic checkpoints and restored by navigating. Only String, Number and Boolean arguments are kept (Parcelables are not restored).
6. Actions and tracked text
Semantic replay invokes registered actions by id and restores tracked text by id. It works even when the developer's screen differs from QA's.
import dev.bugcapsule.android.views.BugCapsuleViews
BugCapsuleViews.onClick(checkoutButton, "cart.checkout") { viewModel.checkout() }
BugCapsuleViews.trackText(couponField, "cart.coupon")
BugCapsuleViews.trackText(passwordField, "login.password") // password input types are forced sensitive
import dev.bugcapsule.compose.*
val coupon = rememberTrackedText("cart.coupon")
TextField(value = coupon.value, onValueChange = coupon::onValueChange)
// Compose does NOT detect password fields: pass sensitive = true yourself.
val password = rememberTrackedText("login.password", sensitive = true)
Button(onClick = rememberBugCapsuleAction("cart.checkout") { viewModel.checkout() }) {
Text("Checkout")
}
Lower-level API for custom widgets: BugCapsule.action(id, Runnable), registerAction(id, ActionHandler) / unregisterAction, recordAction(id, payload) and trackText(id, TextSetter, sensitive) which returns a TextTracker (onChanged(value), untrack()).
7. Assertions, errors and logs
BugCapsule.check("cart_total_non_negative", total >= 0, "total $total")
BugCapsule.fail("checkout_stuck", "spinner for 30 s")
try { … } catch (e: IllegalStateException) { BugCapsule.reportError(e) }
BugCapsule.log("legacy cache migrated", level = "warn")
A failure writes a capsule automatically: 300 ms after the failure (crashes immediately), at most maxCapsulesPerSession (3) per session, one per failure signature. Manual capture() calls count toward the same quota.
What is captured automatically
- Uncaught JVM exceptions on any thread through a chained default
UncaughtExceptionHandler. The previous handler is always called afterwards, so the process still dies. The capsule is written synchronously tonoBackupFilesDir/bugcapsuleand uploaded on the next launch; it carriescrash.persisted(partial).ActivityThread's "Unable to start activity" wrapper is unwrapped. - Native crashes, ANR kills and foreground low-memory kills can get a partial crash capsule on the next launch when the crashed process kept a recording journal. An event without a matching journal has no capsule. Caught exceptions need
reportErrorfor explicit failure capture. See native crashes. - Lifecycle (process level), pointers via each Activity's
Window.Callback(dp, no accessibility service or screen recording), the system Back key (keyevent).
8. State and storage
// ViewModel state in periodic checkpoints, restored in replay (auto-unregistered when the VM clears)
BugCapsule.registerViewModel(this, "cart", { state.toJson() }) { value -> state = CartState.fromJson(value) }
// Any other app state
BugCapsule.registerState("session", { sessionStore.snapshot() }) { sessionStore.restore(it) }
BugCapsule.reportState("cart") // diagnostic `state` event (not replayed)
Storage is allowlist only; nothing is read unless you name it:
BugCapsuleSharedPreferences.builder()
.allowFile("shop_prefs") // every key of a file
.allow("settings_prefs", "feature.") // keys with a prefix
.deny("settings_prefs", "feature.secret")
.build()
BugCapsuleDataStore.builder() // reads files/datastore/<name>.preferences_pb
.allow("settings")
.build()
Both are restored by the replay runner before Application.onCreate. Periodic checkpoints (every 30 s) are used only when the session outgrows the 5-minute / 20,000-event window; otherwise replay starts from the launch checkpoint and re-executes the whole session.
9. Deterministic hooks and manual capture
val nonce = BugCapsule.random().nextInt() // seeded per session; same seed in replay
val now = BugCapsule.currentTimeMillis() // recorded wall clock in replay
BugCapsule.capture(note = "QA: total looks wrong") // Future<CaptureResult?>
BugCapsule.flushUploads()
BugCapsule.refreshRemoteConfig()
BugCapsule.savedCaptures() // List<File>, newest 20
A manual capture with no failure gets a blocking failure.assertion gap and is ineligible: stored and inspectable, never counted in the reproduction rate.
WebSockets and native SDKs
Available from 0.4.1-beta.5. Capsules with WebSocket or adapter traffic are written as capsule spec v2, which older CLIs reject: update the CLI everywhere it runs, CI included, before you turn these on. Other capsules stay v1.
OkHttp WebSockets
Sockets are captured when the app opens them through BugCapsuleWebSockets (in bugcapsule-okhttp). Pass the instance to BugCapsule.init's integrations and use its factory where you call newWebSocket:
val webSockets = BugCapsuleWebSockets() // add it to BugCapsule.init's integrations
val sockets: WebSocket.Factory = webSockets.factory(client)
val ws = sockets.newWebSocket(Request.Builder().url("wss://quotes.example.com/v1/stream").build(), listener)
// or: webSockets.newWebSocket(client, request, listener)
- Capture records connects, opens, sends (with the result OkHttp returned), messages, failures, the app's
close/canceland the listener'sonClosing/onClosed. Text frames are redacted like bodies. Binary frames are recorded as their size only unless you passBugCapsuleWebSockets(captureBinary = true); replay can't serve size-only frames. - Replay never connects. Recorded messages, closes and failures reach your
WebSocketListenerat their recorded latency; sends and closes are compared in order. A connection that wasn't recorded fails throughonFailure(ConnectException,ws.unrecorded). - In replay, listener callbacks run on one background thread,
BugCapsule-WebSocket, one at a time in recorded order across all sockets, never on the main thread. A listener that blocks delays every replayed socket. - Adapter id
bugcapsule-okhttp.websocket, tested with OkHttp 4.12.0. Sockets created any other way are not captured.
Native adapter API
Other SDKs (location, auth, databases, payments) need an adapter. Implement NativeAdapter (identity, operations, payload policy), wrap the SDK in a small class of your own that routes its calls and subscriptions through NativeInteractions.call / subscribe, and pass the NativeInteractions to init:
class LocationAdapter : NativeAdapter {
override val id = "example.location" // the adapter id capsules and capture settings use
override val version = "1.0.0"
override val schema = 1
override val operations = setOf("location.last", "location.updates")
override val tested = mapOf("example-location-sdk" to "2.1.0")
}
val location = NativeInteractions(LocationAdapter()) // add it to BugCapsule.init's integrations
val provider: LocationProvider = BugCapsuleLocationProvider(realProvider, location)
// In BugCapsuleLocationProvider, your wrapper around the real SDK:
bridge.call("location.last", null, callback) { cb -> real.lastLocation(cb) }
bridge.subscribe("location.updates", mapOf("intervalMs" to 1000), subscriber) { s -> real.requestUpdates(s) }
- Capture records results, errors and subscription events with the session's redaction and limits. Replay answers from the capsule at the recorded times and never calls the SDK. Calls are matched by operation, redacted arguments and invocation order.
- Replayed callbacks run on
NativeAdapter.callbackExecutor(by default one background thread per adapter) and receive the same decoded values capture handed over. - An operation the capsule doesn't contain fails with
NativeError.UNRECORDEDand anative.unrecordeddivergence. Operations not inoperationsrun uncaptured with anoperation.unsupportedgap.
Check an adapter in a plain JVM unit test with NativeAdapterConformance (testImplementation("io.github.bugcapsule:bugcapsule-android-replay:…")). It records a scripted session, replays it offline and fails on any divergence, on SDK use during replay, and when an unsupported operation doesn't produce an explicit gap. The SDK repository has a complete example location adapter and its test.
private val conformance = NativeAdapterConformance({ LocationAdapter() })
@Test fun adapterConforms() {
conformance.assertConforms(NativeAdapterConformance.Scenario { ctx ->
val sdk = FakeLocationSdk(ctx) // reports every SDK use with ctx.sdkUsed(...)
val provider = BugCapsuleLocationProvider(sdk, ctx.bridge)
provider.lastLocation(observer(ctx, "last")) // a callback that reports results with ctx.observe(...)
ctx.advance(40)
if (!ctx.replaying) sdk.answer(Location(52.37, 4.89, 12f, 1_000))
ctx.advance(10)
})
}
@Test fun unsupportedOperationsProduceGaps() {
conformance.assertUnsupported("location.geofence", mapOf("radiusM" to 100))
}
Replay and limits
- Replaying a capsule with WebSocket or adapter traffic needs the same adapter installed; otherwise the attempt ends
INCOMPATIBLEwithdependency.unsupported. Interaction divergences (ws.*,native.*,dependency.live) keepverifyfrom reporting a fix; see interaction divergences. - Bounds shared by every adapter: 64 KiB per payload (larger: truncated), 1 MiB of payloads per 5-minute window (later ones: size only), 32 connections and subscriptions open at once (more run uncaptured with a
connections.limitgap). With network body capture off, payloads are omitted. - Connections and subscriptions open at a periodic checkpoint are not restored (the WebSocket adapter has no snapshot; native adapters only when they implement restoring). Such capsules are ineligible and replay reports
INCOMPATIBLE(dependency.unrestorable). Ping/pong and frame details are not recorded. - Your project's capture settings can turn off a single adapter (for example
bugcapsule-okhttp.websocket) without affecting HTTP capture.
Configuration reference
BugCapsuleConfig.builder()…build() (also toBuilder()).
| Builder method | Default | Notes |
|---|---|---|
appVersion, appBuild, appId, appName, flavor | package info | versionName, versionCode, packageName, label |
mode | DEBUG if debuggable, else PRODUCTION | Only sampling depends on mode: debug and QA always record |
enabled | true | Local master switch, read at init |
token(token) | none | The SDK token (bcsdk.v1.…) from the dashboard: all a connection needs. Same as BugCapsule.init(app, token) |
backend(url, ingestKey) | none | The advanced alternative to token, and wins over it. With neither, nothing is uploaded and capture settings aren't fetched. Never a bcs_ key |
gitSha, gitDirty | null | Fallback: manifest meta-data dev.bugcapsule.GIT_SHA / dev.bugcapsule.GIT_DIRTY |
stateSchemaVersion | 1 | A mismatch with a periodic checkpoint makes replay INCOMPATIBLE |
checkpointIntervalMs | 30 000 | At least 1000 |
windowMs / maxEvents | 300 000 / 20 000 | Flight-recorder window |
productionSampleRate | 0.1 | Remote sampleRate can only lower it |
autoCaptureOnFailure | true | |
maxCapsulesPerSession | 3 | Shared with manual captures |
captureNetworkBodies / maxBodyBytes | off in production; on in debug/QA / 256 KiB | ANDed with the remote setting. Boolean?: off in production, on in debug/QA unless set; binary bodies need BugCapsuleOkHttp(captureBinaryBodies = true) (What's new) |
collectionEnabled / savedCaptureMaxAgeMs / maxRetainedBytes | true / 7 days / 8 MiB | consent default, saved-capture expiry and in-memory recorder budget; see consent and local data |
redactKeys, redactHeaders, redactPattern(regex), redactPatterns | empty | Added to the built-in rules |
beforeRecord | null | BeforeRecord { type, data -> data or null }, null drops the event |
beforeCheckpoint | null | BeforeCheckpoint { integration, data -> … } |
outboxLimits | OutboxLimits(10, 10 MiB, 7 days) | Oldest evicted first |
maxStaleConfigMs | 7 days | Uploads need a config at most this old |
ignoreError | null | ErrorFilter { e -> Boolean } |
label(key, value) | empty | Free-form tags, scrubbed like text |
maxSavedCaptures | 20 |
Replay
{
"runtime": "android",
"android": {
"gradleDir": ".",
"module": "app",
"variant": "debug",
"applicationId": "com.example.shop",
"testApplicationId": "com.example.shop.test",
"avd": "Pixel_6_2"
},
"timeouts": { "buildSeconds": 1200, "attemptSeconds": 120 }
}
bugcapsule run <id> -n 3 # expects REPRODUCED
bugcapsule verify <id> -n 3 # after the fix: FIXED only if every attempt is valid and clean
bugcapsule regress add <id> && bugcapsule regress run
All android.* keys are listed on the CLI page. What one attempt does:
- The CLI builds
:<module>:assemble<Variant>andassemble<Variant>AndroidTestonce, with-PbugcapsuleGitSha=<sha> -PbugcapsuleGitDirty=<bool>(or uses--apk/--test-apk). - Per attempt:
pm clear,adb reverse tcp:<port>, thenam instrument -r -w -e bugcapsuleReplayUrl <url> -e class dev.bugcapsule.android.replay.BugCapsuleReplayTest <testAppId>/<runner>. BugCapsuleReplayRunner.onCreate(beforeApplication.onCreate) fetches settings and capsule, refuses unless the app is debuggable, and restores SharedPreferences/DataStore.BugCapsule.initstarts in replay mode. The test launches the launcher activity withActivityScenarioand runs the in-app engine: pointers viasendPointerSync(dp → px, scaled if the screen differs), Back viasendKeySync, actions and text on the main thread, lifecycle by moving the scenario (resumed→RESUMED,inactive→STARTED,paused→CREATED).- The result goes to
POST <base>/resultand to instrumentation statusbugcapsule_result=BUGCAPSULE_RESULT::{json}. A replayed crash reports synchronously from the crash handler before the process dies.
From 0.4.1-beta.5, pointer events include soft-keyboard visibility. The runner restores that state before each gesture so a keyboard left open does not intercept touches intended for the app. If synchronization fails, replay reports a divergence. Older capsules keep their original behavior; capture again with this version to include keyboard state.
Strategy AUTO uses pointer replay when the screen matches or no actions exist, otherwise semantic. Idle gaps over 1.5 s shrink to 0.3 s; recorded network latency is never shortened.
Production protection. Replay can only be armed from an Instrumentation (the runner ships in the androidTest APK only) for a debuggable app. There is no intent, deep link, URL, push or file path into replay.
The emulator must be unlocked once after boot. AVDs with a screen-lock PIN cannot be unlocked by the CLI. --device picks a running device (serial, AVD name or model) or an AVD to boot; an emulator the CLI booted is shut down afterwards.
Uploads and capture settings
- The SDK uses its own HTTP connection, so its traffic is never captured by your OkHttp client.
- Uploads wait until the project's capture settings have been fetched once (or a cached copy is younger than 7 days). Failed uploads are retried with backoff from 30 s up to 1 h at the next trigger (launch, foreground, a new capsule,
flushUploads()); a capsule BugCapsule rejects is dropped. - Capture settings are cached per BugCapsule address and credential and refreshed every few minutes and on foreground.
- Kill switch: recording stops, queued and saved captures are deleted, and it persists across launches. A refused token or ingest key stops capture for the session (
status()reportsREJECTED) but keeps the queue (other SDKs delete it).
Demo app
examples/demo: a Views + Compose shop (Retrofit on OkHttp, an in-process FakeShopServer interceptor below the SDK, Jetpack Navigation, allowlisted SharedPreferences and DataStore, CartViewModel registered as state).
| Bug | Trigger | Why replay needs BugCapsule |
|---|---|---|
Data-dependent: item with price: null | 1 in 4 carts; Checkout | The recorded server response |
| Negative total | Coupon SAVE100 on a cart under 100 | check("cart_total_non_negative") + tracked text |
| Race: recommendations before profile | "Refresh home" (~1 in 4) | Recorded response latencies |
| Legacy cart cache | "Simulate upgrade from v0.9", restart, open cart | The launch checkpoint restores shop_prefs |
BUGCAPSULE_TOKEN=bcsdk.v1.… ./gradlew :demo:assembleDebug # the token enables uploads
# Self-hosted / advanced: BUGCAPSULE_INGEST_KEY=bci_… with -PbugcapsuleBackendUrl=https://api.bugcapsule.com
# Isolated fix toggle, no tracked source change:
BUGCAPSULE_ANDROID_GRADLE_ARGS=-PbugcapsuleDemoFix=race bugcapsule verify <id> -p examples/demo
Only race keeps the recorded request sequence. price and legacy change which requests the app makes, so verifying those is (correctly) INCONCLUSIVE with network.unrecorded.
Limitations
- Replay runs only through the instrumentation runner with a debuggable build. Pointer replay assumes the capture screen size; otherwise coordinates are scaled (
screen.size, expected). - Only the Back key among hardware keys; IME text only through tracked fields. Multi-window and system dialogs are not driven.
- Clock and randomness are deterministic only through
currentTimeMillis()andrandom(). WorkManager, alarms and Bluetooth are not captured. Other network stacks (HttpURLConnection, Ktor, Cronet) and SDKs such as location, maps or Firebase are not captured; WebSockets opened throughBugCapsuleWebSocketsand SDKs you route through a native adapter are. - The consumer ProGuard/R8 rules are empty and the demo ships with minify off. R8 builds are untested; verify a minified QA build before relying on it.
- Monitoring supports user context and breadcrumbs; see Monitoring. Consent decisions belong to your application: configure collection before initialization and validate both capsule and monitoring behavior.
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.