The UnifiedPush connector's MessagingReceiver is a plain BroadcastReceiver
whose onReceive calls onMessage synchronously on the main thread with no
goAsync(). onMessage routes into WakeDispatcher.dispatch ->
ProviderRegistry.awaitReadyBlocking(2000), which is explicitly documented
"MUST NOT be called from the main thread". On a cold-start wake (registry
not yet ready) that blocks the main thread for up to 2s and ANRs the
receiver; the foreground notification is then left stuck on "Connecting…"
even though the relay socket actually establishes. The google/FCM path is
immune because FirebaseMessagingService.onMessageReceived already runs off
the main thread.
Override onReceive to goAsync() and run the connector's full receive
sequence (super.onReceive -> onMessage/onNewEndpoint + acknowledge) on
Dispatchers.Default, launched on the injected app scope. The broadcast's
PendingResult is finished only AFTER that work completes, so the process
keepalive AND the broadcast's temporary foreground-service-start exemption
survive across the startForegroundService call inside WakeDispatcher --
finishing early would drop both and make startForegroundService throw
ForegroundServiceStartNotAllowedException. The whole sequence stays well
within the broadcast ANR window (awaitReadyBlocking caps at 2s).
The residual "defensive reconcile so a live socket is never shown as
Connecting…" acceptance item is split to #510 to keep this PR on the ANR
root cause; the symptom's root cause (a starved state-collector) is fixed
here. No user-facing flow change, so no docs/ux-decisions.md entry.
Co-authored-by: monkopedia-coder <monkopedia+coder@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Android 15 caps dataSync foreground services at 6h cumulative per 24h. A foss
user who keeps the tunnel connected for long interactive MCP sessions can hit
that ceiling on a genuinely active day and have the service killed mid-use.
Add a foss-only, opt-in "Ignore daily time limit" setting. When ON, the tunnel
foreground service enters the foreground as specialUse instead of dataSync,
which has no 6h/24h cap. This ONLY changes the FGS type: the adaptive
idle-timeout / quick-disconnect teardown still governs when the tunnel drops,
so the type swap merely removes the hard ceiling.
It is foss-only because declaring specialUse triggers Google Play review, and
Play steers persistent-connection use cases to FCM (which the google build
already uses). The Play build stays dataSync-only and never declares the
specialUse type or the FOREGROUND_SERVICE_SPECIAL_USE permission.
Implementation:
- New FgsTypeSelector seam in :work, injected into TunnelForegroundService so
startForeground() asks for the type instead of hardcoding DATA_SYNC. Bound
per-distribution: GoogleFgsTypeSelector (constant dataSync) vs
FossFgsTypeSelector (specialUse when opted in AND API 34+, else dataSync).
- foss reads a synchronously-cached IgnoreDailyTimeLimitState mirror of the
persisted flag, since startForeground() can't suspend on a DataStore read.
- Setting persisted via AppStatePreferences.ignoreDailyTimeLimit (default OFF),
threaded through SettingsViewModel state + setter. The Settings row is gated
on an injected canIgnoreDailyLimit capability flag (true in foss
DistributionModule, false on google) — no BuildConfig.FLAVOR checks in UI.
- foss manifest overlay sets foregroundServiceType="dataSync|specialUse" and
adds PROPERTY_SPECIAL_USE_FGS_SUBTYPE; google merged manifest stays dataSync.
- Existing onTimeout / ForegroundServiceStartNotAllowedException dataSync-budget
handling is unchanged; it simply won't fire while running as specialUse.
UX decision logged in docs/ux-decisions.md (owner-approved in-session).
Co-authored-by: monkopedia-coder <monkopedia+coder@gmail.com>
Android 15 caps dataSync foreground services at 6h cumulative per 24h. A
lightweight wake (an MCP client that only lists tools/resources then idles)
previously held the tunnel CONNECTED for the full idle timeout, burning the
budget for ~1s of real work.
Make the post-session teardown adaptive: a wake cycle is "substantive" only if
its MCP stream issued at least one tools/call. The session layer flags this via
the existing AuditListener.onToolCall (SessionActivityAuditListener ->
SessionActivityTracker); IdleTimeoutManager reads it when arming and resets it
on DISCONNECTED. Substantive cycles keep the existing "Idle timeout" (minutes);
discovery-only or spurious wakes get the new, shorter "Quick disconnect"
timeout (seconds).
Add the "Quick disconnect" setting (15s/30s/1min, default 30s) below "Idle
timeout" in the Connection settings cluster, persisted via the same DataStore
mechanism. The existing "Disable timeout" switch is unchanged.
Co-authored-by: monkopedia-coder <monkopedia+coder@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
UnifiedPush endpoints can rotate at any time. When that happened while the
tunnel was DOWN, UnifiedPushBackgroundDelivery persisted the new endpoint but
deferred the relay update ("a future reconnect re-reports it") — yet the foss
ConnectPushReporter was a no-op, so no reconnect ever re-reported. The relay
kept waking the stale endpoint and the device became unwakeable until a
coincidental connected redelivery.
Replace the foss NoOpConnectPushReporter with a real UnifiedPushConnectPushReporter
that, on each successful connect, reads the persisted endpoint
(UnifiedPushBackgroundDelivery.currentEndpoint, reusing the same prefs entry as
the single source of truth) and sends it via tunnelClient.sendPushEndpoint —
mirroring the google flavor's FcmConnectPushReporter. No relay change: the WS
push_endpoint path already accepts it under the mTLS cert.
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
The google build's cold-start-via-FCM wake path has integration coverage
(ColdStartViaFcmTest et al.), but the foss UnifiedPush wake path had only a
Roborazzi screenshot test (FossDeliveryMockTest), leaving the shipping foss
cold-start-via-UnifiedPush path unvalidated in CI.
Add ColdStartViaUnifiedPushTest mirroring ColdStartViaFcmTest: provision a
device, simulate a cold start (drop in-memory state, keep disk + keypair +
relay), decode the relay's `{"type":"wake"}` UnifiedPush body and assert it
routes to StartService, then drive a fresh tunnel to CONNECTED against the
real test-mode relay and confirm the relay observed a new /ws upgrade. It
lives in src/testFoss so it only runs under the default (FOSS)
:app:integrationTest, alongside KeypairRoundTripIntegrationTest.
To give the test the foss analogue of FcmDispatch's pure dispatch seam,
extract UnifiedPushReceiver's private byte->map JSON parse into a testable
UnifiedPushPayload object; the receiver now delegates to it. This is the
in-process/test-mode wake logic only -- the real ntfy.sh hop stays
manual/on-device, as the issue notes.
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
The #480 "Open {distributor} to enable" nudge launched the chosen
distributor but never cleared: select() issues a single UnifiedPush
REGISTER, which Android drops while the distributor is in its stopped
state, and UnifiedPush never redelivers it. Launching the distributor
alone left nothing for it to act on, so no endpoint ever arrived and the
nudge stuck forever (only a manual re-select, which re-issues REGISTER,
recovered).
Re-issue registration after the distributor comes up: the nudge's "Open"
action now re-registers ~1.5s after launch (onDistributorOpened), and the
destination's ON_RESUME re-registers a selected-but-unacked distributor
(onResume) as a belt-and-suspenders for users who linger in the
distributor app. The in-flight selection job is still awaiting the
endpoint, so once it arrives the nudge clears and proceed fires; if it
still doesn't arrive the nudge stays up for retry rather than getting
stuck.
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
A freshly-installed UnifiedPush distributor (e.g. ntfy) sits in Android's
"stopped" state and silently drops broadcasts — including our `REGISTER` —
until it is launched once. A user could pick a distributor in onboarding and
have no endpoint ever arrive, leaving the device degraded with no signal that
opening the distributor once would fix it.
Detect-and-nudge (the approved option a): the picker now waits briefly for the
push endpoint after a selection. If it doesn't arrive, the picker surfaces a
dismissible nudge whose action launches the chosen distributor (clearing the
stopped state so its registration fires). The endpoint then flows back, the
nudge clears automatically, and the flow advances. Advancing past the picker is
gated on the endpoint arriving (or the user skipping) instead of firing on tap.
- BackgroundDelivery: add `endpointArrived` signal + `launchIntent(id)`; foss
wires them to the persisted/arriving endpoint and the package launch intent,
NoOp returns false/null.
- BackgroundDeliveryViewModel: wait-with-timeout after select, raise/clear the
`DistributorNudge`, emit `proceed` once the endpoint arrives.
- Picker screen: render the nudge card ("Open {distributor} to enable").
- Destination: defer advance until `proceed`, launch the distributor on the
nudge action.
Adds a docs/ux-decisions.md entry for the approved decision.
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
The "Grant access" action in notification-capture setup opened
ACTION_NOTIFICATION_LISTENER_SETTINGS, dropping the user on the full
list of every notification-listener app where they had to hunt for
ours. On API 30+ use ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS with
EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME pointing at our
NotificationCaptureService so the user lands directly on our enable
toggle. minSdk is 24, so fall back to the existing list action below
API 30. The ComponentName is built from the Context (not a hardcoded
package), so it resolves the right applicationId including the .debug
suffix on debug builds.
Closes#487
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
The shared SwitchRow Switch had no explicit colors, so its off
(unchecked) state fell back to the Material3 default unchecked palette
(track surfaceContainerHighest, thumb/border outline). In the navy+amber
theme those are low-contrast enough that an off-but-enabled switch looked
greyed-out/disabled, reading as "you can't toggle this" rather than
"this is off." Because the component is shared, every switch (e.g. the
two on Settings) was affected.
Give the Switch explicit SwitchDefaults.colors() overriding the unchecked
state with a surfaceVariant track and onSurfaceVariant thumb/border so an
off switch is clearly an interactive control, distinct from the dimmed
disabled appearance. Checked (primary) and disabled states keep Material
defaults. Verified contrast holds for on/off x enabled/disabled in light
and dark.
Add a Roborazzi screenshot test locking all four states in both themes.
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
On a fresh foss onboard, registerWithEndpoint latched DeliveryActivation
.NeedsSetup for ANY non-Success result of OnboardingFlow.execute. But
execute registers + persists the subdomain FIRST, then chains ACME cert
provisioning (#389). A cert-stage failure (CertRateLimited / CertRelayError
/ CertNetworkError / CertKeyGenerationFailed / CertStorageFailed) returns
non-Success while the device is already registered with its push endpoint
reported. Those hit the else branch and wrongly told the user "On-demand
wake is off / set up a delivery app" even though wake was configured and
only the cert hop stumbled — cert problems are already surfaced separately
by the dashboard cert-renewal banner.
Key wake-activation off the persisted subdomain (mirroring the init seeding
and refreshEndpoint) instead of full-flow success: Active when a subdomain
is persisted, NeedsSetup only for pre-subdomain failures. Still
markComplete() on Success.
Adds the first direct unit test for UnifiedPushBackgroundDelivery covering
cert-failure-with-subdomain -> Active, pre-subdomain failure -> NeedsSetup,
and Success -> Active + markComplete.
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
On the FOSS build, background wake silently fails unless the app is on the
battery-optimization allowlist: a UnifiedPush distributor cannot grant the
temporary power-allowlist that Play Services hands the FCM build, so the
background start of the tunnel foreground service is blocked and the wake is
dropped. There was no signal that this fixable condition was the cause.
Add a persistent FOSS-only Home warning banner shown when the app is not
battery-exempt, gated at runtime via BackgroundDelivery.isSupported (the same
seam the delivery banner uses) so google/FCM never shows it. The exemption is
re-read on ON_RESUME via a new batteryExemptFlow, mirroring the notification
permission flow, so the banner clears when the user returns from the dialog.
Switch the battery "Fix this" — both the new Home banner action and the
existing #453 Connection-settings action — to the one-tap OS dialog
(ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS + package: URI) instead of the
settings list, and declare REQUEST_IGNORE_BATTERY_OPTIMIZATIONS. #453 used the
list solely to dodge the Google Play policy restriction on that permission; we
don't ship to Play (Google build is GitHub-distributed, FOSS goes to F-Droid,
which accepts it), so that no longer binds.
Records both parts in docs/ux-decisions.md, superseding the 2026-06-02 #453
"Fix this opens battery-optimization settings" decision.
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
On a not-yet-registered FOSS device (one that skipped Background
delivery), tapping "Add integration" used to silently block in
IntegrationSetupViewModel.awaitRegistrationIfNeeded waiting for a
registration that never starts — it read like a hang.
Instead, detect the delivery-not-set-up state (DeliveryActivation.
NeedsSetup) at add-integration time and redirect to the existing #463
Background delivery picker, topped with a contextual strip. Remember the
integration the user was adding (PendingIntegrationSetup) and, once a
distributor is chosen, auto-resume straight into that integration's setup
flow rather than dropping the user at Home. Tapping "Skip for now"
instead drops the pending integration and returns to Add integration.
Gated on NeedsSetup, so it is a no-op on google (FCM, NotApplicable) and
on already-registered FOSS devices (Active). Adds the required
docs/ux-decisions.md entry (Option A + auto-resume, approved in-session).
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* #376: drain leaked test coroutines + route all setMain through MainDispatcherRule
The TestMainDispatcher "Dispatchers.Main is used concurrently with setting
it" flake recurs because some test in the shared single-JVM unit-test run
leaves a coroutine alive that resumes a continuation onto Dispatchers.Main
during a later test's setMain/resetMain. CI run 27505633656 caught
AuditHistoryViewModelRoomTest as the victim: its MainDispatcherRule.resetMain()
raced a "reader" still dispatching on Dispatchers.IO (LimitedDispatcher$Worker
in the captured stack), so the leaker is another class, not the victim.
This closes the fire-and-forget coroutine leaks that were auditable and makes
every setMain deterministic:
- AppIntegrationTestHarness now cancelAndJoins its injected appScope
(drainHarnessScope) instead of fire-and-forget cancel(), at stop() and the
two mid-test reboot paths. This drains every harness-based integration test
at once.
- The observer-family integration tests (Suppressed, PerCall, Runtime,
MultiTool, ToolCallHappyPath, AuditRace) cancelAndJoin their Dispatchers.IO
observer job before Main is reset.
- ToolCallViaSniPassthroughTest cancelAndJoins its tunnel scope.
- All 26 setMain-using test classes install the shared MainDispatcherRule, so
setMain is paired with resetMain in a finally (no ad-hoc @Before/@After) and
pairing is trivially auditable.
Verification of full flake elimination, plus the forkEvery structural-backstop
trade-off, are discussed in the PR.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Add Gradle test-retry as the cheap CI backstop for the #376 flake
Per Jason: ship the #376 correctness fix (drain leaked coroutines + route
setMain through the rule) WITHOUT the ~7x forkEvery=1 tax, and add the
test-retry plugin instead. It retries only FAILED tests in a fresh JVM, so an
intermittent leak-induced failure passes on the isolated retry while a real
deterministic failure still fails every attempt (no masking). Only acts on
failure -> the green path is unaffected. Applied to all Test tasks (also
neutralizes the known OAuth integration flake).
---------
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
The foss runtime classpath still pulled firebase-auth + firebase-messaging
transitively via the shared :work module, even though foss runs keypair +
UnifiedPush at runtime. F-Droid rejects APKs that link proprietary deps, so
:work must be Firebase-free.
Relocate the Firebase-coupled classes from :work into the :app `google`
source set, leaving the Firebase-free seams/interfaces in :work:
- FirebaseRenewalAuthProvider -> app/src/google (com.rousecontext.app.auth),
behind the existing RenewalAuthProvider seam (foss already binds
KeypairRenewalAuthProvider).
- FcmReceiver (FirebaseMessagingService) -> app/src/google
(com.rousecontext.app.push); its manifest entry already lived in
app/src/google. It delegates to the Firebase-free WakeDispatcher /
FcmTokenRegistrar, which stay in :work.
- TunnelForegroundService's per-connect FCM-token push (the last
FirebaseMessaging usage) now goes through a new ConnectPushReporter seam in
:work. google binds FcmConnectPushReporter (fetches the FCM token via the
existing FcmTokenProvider seam and forwards it); foss binds a no-op (its
UnifiedPush endpoint is reported by UnifiedPushBackgroundDelivery).
Drop firebase-auth/messaging from :work's build.gradle.kts; they remain
googleImplementation in :app. Moved tests to app/src/testGoogle.
google behavior is unchanged — same Firebase auth + FCM paths, just relocated.
Classpath evidence:
fossDebugRuntimeClasspath | grep firebase -> (nothing)
googleDebugRuntimeClasspath | grep firebase -> firebase-auth, firebase-messaging, firebase-crashlytics
Part of #460. Fixes#476.
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* FOSS #464: ACRA crash reporting (foss) + relay /crash → GitHub issues
App (foss flavor only):
- Add ACRA (ch.acra:acra-core + acra-http 5.13.1) as fossImplementation.
- Replace the foss NoOp CrashReporter with AcraCrashReporter; google keeps
FirebaseCrashReporter. Both sit behind the same Koin seam.
- Initialize ACRA in RouseApplication.attachBaseContext via a flavor-specific
CrashReporterInitializer (foss = ACRA.init with an HttpSender POSTing JSON to
the relay's /crash; google = no-op, Crashlytics self-inits via its plugin).
- Respect the existing debug/release collection toggle: ACRA collection is
disabled in debug, and setCollectionEnabled() forwards to ACRA.errorReporter.
Relay (Rust):
- New POST /crash endpoint + crash module. Pipeline: sanitize (field allowlist
+ redact emails/IPs/on-device paths/long tokens from the stack trace) →
fingerprint+dedup → per-fingerprint spike-cap → global new-issue cap →
file/append a GitHub issue labeled `crash`.
- Security (abuse surface): no device auth (ACRA can't present the device mTLS
cert and crashes must be reportable pre-provisioning); instead a per-IP
token-bucket rate limit (429), the per-fingerprint spike-cap, and a global
new-issue cap that bounds issues/window even under IP/fingerprint rotation.
- GitHub token is an ops dependency: [github] crash_repo + token_env
(GITHUB_CRASH_TOKEN). When unconfigured the endpoint sanitizes+dedups+logs
and returns 202 (graceful no-op, never crashes).
- In-memory dedup/limiter maps swept by the existing rate-limit sweep loop.
- Unit + endpoint tests: sanitization, fingerprint stability, dedup,
spike-cap, global cap, per-IP rejection, filing orchestration.
Part of #460. Fixes#464.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Defang @mention / #ref injection in crash-issue sanitization (#464)
sanitize_text now inserts a zero-width space after @ and # so a crafted
crash report can't inject @mention notification spam or #issue cross-ref
spam into the public GitHub issue it files (the allowlisted fields render
outside the fenced code block). Display is unchanged. Addresses the
monkopedia-reviewer finding on #475; extends the prescribed @ fix to # for
the same class. Added a unit test.
---------
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Adds the foss-flavor UnifiedPush on-demand wake path — the Firebase-free
counterpart of the FCM wake path — behind a flavor-agnostic BackgroundDelivery
seam so all UnifiedPush API use stays out of the shared source set.
Option A (deferred activation): a foss device has no push endpoint until a
distributor is chosen, and the merged relay (#472) requires a push target to
register. So foss onboarding completes WITHOUT registering — a skipped device
lands on a degraded Home with a "set up a delivery app" banner; registration
fires later when a distributor reports its endpoint, which activates the device.
- core/tunnel: RegisterRequest.push_endpoint + TunnelClient.sendPushEndpoint
({"type":"push_endpoint",...}); threaded through OnboardingFlow/register.
- foss UnifiedPushReceiver routes wake/renew through a shared WakeDispatcher
(extracted from FcmReceiver) and reports endpoints via UnifiedPushBackgroundDelivery.
- "Background delivery" picker (after Welcome; foss-only nav), ON_RESUME rescan,
ntfy-only-when-empty, Settings row, degraded Home banner.
- Home gate relaxed for foss (onboarding-complete flag, not subdomain).
- Roborazzi goldens for the shipping picker/banner/Settings-row.
- docs/ux-decisions entry (deferred-activation correction).
Fixes#463.
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* Add foss-variant integration path + keypair register→cert→renew round-trip test (#469)
Closes the #462 gap: the foss keypair register/renew auth path had relay-side
(Rust) and client-unit (proof byte-contract) coverage, but nothing exercised
the foss Android client talking to a running relay binary with keypair auth.
Approach
- New `:app:fossIntegrationTest` Gradle task mirroring `integrationTest` but
reusing `testFossDebugUnitTest`'s classpath, so the foss `distributionModule`
(KeypairDeviceCredentialProvider / KeypairRenewalAuthProvider) is the flavor
module live in the existing AppIntegrationTestHarness Koin graph.
- New keypair round-trip test in the `app/src/testFoss` source set (so it only
runs under the foss task, never under the google `integrationTest`). It drives
the real foss DI seams against the real relay subprocess: register via a signed
keypair proof (zero Firebase) → provision certs keyed on the CSR thumbprint →
renew via the production CertRenewer bridge through the foss
KeypairRenewalAuthProvider (keypair Path B). Asserts: providers are the keypair
impls, registration skips the Firebase-only /request-subdomain reservation,
certs are issued (1 /register/certs), renewal succeeds (1 /renew) and rolls the
relay-issued client cert — i.e. the relay accepted every keypair proof.
- Harness: added a software DeviceKeystoreSigner override backed by the harness's
in-memory DeviceKeyManager keypair, since production binds AndroidKeystoreSigner
(no AndroidKeyStore on Robolectric, and a different key than the harness uses).
- CI: android-ci.yml now runs `:app:fossIntegrationTest` alongside the existing
google `integrationTest`, sharing the same test-mode relay binary.
Surfaced friction
- testFossDebugUnitTest never compiled: FirebaseCrashReporterTest lived in the
shared `test/` source set but references the google-only Firebase Crashlytics
SDK + FirebaseCrashReporter. CI only ever compiled the google unit-test
variant, so this was latent. Moved it to `app/src/testGoogle/` (where the class
under test lives); it still runs under testGoogleDebugUnitTest.
- The relay requires a non-empty fcm_token on /register (a push-wake concern,
not keypair-auth), while the foss NoOpFcmTokenProvider returns "" until
UnifiedPush (#463). The round-trip test passes a placeholder push token so the
keypair-auth round trip — the actual #469 gap — is exercised independently of
the push transport. Flagged here rather than papered over; the real foss push
endpoint is #463-shaped.
Part of #460. Fixes#469.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Bump integration-step CI timeout to 30m for the third (foss) suite (#469/#470)
Adding :app:fossIntegrationTest as a third serial integration suite on the
15-min step pushed it over the limit (the step timed out while foss was
running — not a hang). Two suites fit 15m; three need ~30m. Also merges
main (#471 flake fix) for a clean base.
---------
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
AuditHistoryViewModelRoomTest pointed Dispatchers.Main at the shared
Dispatchers.IO pool and tore down with a fire-and-forget
testScope.coroutineContext[Job]?.cancel() (no join) before resetMain(),
and never cancelled the VM's viewModelScope at all. A viewModelScope
coroutine (the stateIn upstream / Room flow collector) could therefore
still be dispatching on Main when resetMain() ran, and could outlive it.
Unit tests run in a single JVM (no forkEvery), so the leaked Main override
surfaces as an IllegalStateException from kotlinx.coroutines.test's internal
TestMainDispatcher in a random later test's setMain. That is the moving-target
flake in #376 (CI run 27476494784 attempt 1: failures in
AuditHistoryViewModelRoomTest.kt:83 at resetMain and, downstream,
OnboardingViewModelTest).
Fix:
- Add MainDispatcherRule: pairs setMain/resetMain in a TestRule so the reset
always runs in a finally around the whole test.
- Route Main to a dedicated single-thread executor the test owns (not shared
IO), preserving the real cross-thread scheduler Room's invalidation tracker
needs while making the dispatcher drainable.
- Own the VM in a ViewModelStore; in tearDown cancel viewModelScope via
clear(), then shutdown()+awaitTermination() the executor so Main is fully
quiescent (worker thread dead) before the rule's resetMain() fires. Join the
warmup collector with cancelAndJoin on the runBlocking scope.
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* Keypair device identity for foss flavor (#462)
Replace Firebase Anonymous Auth with a hardware-keypair identity for the
`foss` flavor, while the relay accepts BOTH Firebase (google) and keypair
(foss) auth simultaneously.
Relay:
- DeviceRecord gains an optional key_thumbprint (base64 SHA-256 of SPKI DER);
find_device_by_thumbprint mirrors find_device_by_uid.
- New keypair_auth module: canonical proof message, bounded-timestamp replay
check, signature verify, thumbprint derivation (+ unit tests).
- POST /register, /register/certs, /renew accept a keypair variant alongside
the unchanged Firebase path.
App (foss only):
- Real keypair DeviceCredentialProvider + RenewalAuthProvider replace the
stub auth bindings; google keeps its Firebase impls.
- Flows thread a flavor-agnostic DeviceCredential.
Part of #460. Fixes#462.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* cargo fmt the keypair_auth relay code (#462)
CI Format check (rustfmt) flagged the new keypair_auth/register/renew
Rust code. Pure formatting; no logic change.
---------
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* Add google/foss product flavors (#461)
Introduce a `distribution` flavor dimension on `:app` with two flavors:
- `google` — the unchanged shipping build (Firebase/FCM/Crashlytics).
- `foss` — compiles with zero firebase-*/google-services/Play-Services
dependencies; google-services.json is not required to assemble it.
The google-services and firebase-crashlytics Gradle plugins are now applied
conditionally (skipped for a foss-only build, detected by requested task name),
and the Firebase deps are scoped to `googleImplementation`. The three runtime
seams get flavor-specific Koin bindings via a new `distributionModule`:
CrashReporter, AnonymousAuthClient/FcmTokenProvider/DeviceAuthTokenProvider, and
RenewalAuthProvider. The foss flavor binds NoOp/stub placeholders — real impls
land in #462-#464; #461 only needs both flavors to assemble.
Two direct FirebaseAuth call sites in shared `:app`/debug code
(IntegrationSetupViewModel, AddIntegrationDestination, TestCommandProvider) are
moved behind the seams so `main`/`debug`/`foss` compile Firebase-free.
The shared `:work` module keeps its Firebase types for now; only the FCM
`FcmReceiver` manifest entry moves to the google-flavor manifest so it is absent
from the foss build's merged manifest.
CI/task renames: assembleDebug -> assembleGoogle/FossDebug, testDebugUnitTest ->
testGoogleDebugUnitTest, release builds the google flavor only (dual-flavor
release is #465). Kover excludes the foss debug + flavored release test tasks.
Part of #460. Fixes#461.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Load flavor distributionModule in integration test harness
PR #461 moved CrashReporter, AnonymousAuthClient, FcmTokenProvider,
DeviceAuthTokenProvider, and RenewalAuthProvider out of the base appModule
into per-flavor distributionModule. RouseApplication registers both, but the
integration-test Koin bootstrap (AppIntegrationTestHarness.bootKoin) only
loaded appModule, so those five definitions were missing and every
com.rousecontext.app.integration.* test failed with NoDefinitionFoundException.
Add distributionModule (google variant on the integrationTest classpath) to
the startKoin module list, between appModule and the test overrides so any
harness fake still wins. Mirrors RouseApplication's base + distribution
composition.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Fix stale variant-task references missed in the flavor rename (#461)
- docs/self-hosting.md: :app:compileDebugKotlin -> :app:compileGoogleDebugKotlin
- app/build.gradle.kts comment: testDebugUnitTest -> testGoogleDebugUnitTest
Flagged by reviewer on PR #466.
---------
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Four classes independently hand-rolled the identical "suspend/block until
the backing flow has emitted at least once" primitive — a
CompletableDeferred<Unit> + CountDownLatch(1) pair with byte-for-byte
identical signalReady()/awaitReady()/awaitReadyBlocking(timeoutMs) bodies.
This gate is load-bearing on the cold-start FCM-wake path (#414/#416), so
the duplicated correctness logic (idempotent signal, deferred + latch kept
in sync) should live in one tested place.
Add ReadinessGate to :core:mcp, alongside the ProviderRegistry interface
that already documents this awaitReady/awaitReadyBlocking contract. :app
already depends on :core:mcp, so all four consumers can import it without a
new dependency edge. Each class now delegates to the gate; observable
behavior is unchanged (pure refactor).
Add a focused unit test on the helper (idempotent signal; awaitReady
suspends until signalled then resumes; awaitReadyBlocking false before /
true after; double-signal is safe).
Migrated:
- IntegrationProviderRegistry
- DeviceRegistrationStatus
- SecurityAlertGate
- OutreachIntegration
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
crt.sh (community-run, maintained by Sectigo) returns 502/503 for minutes
at a time, longer than HttpCtLogFetcher's 1s/3s/9s retry window (#256) and
the cross-run debounce (#256/#429). The residual user-facing "Could not
reach CT log service" warnings were crt.sh outages, not real reachability
problems.
Add a second, independent CT source (Certspotter) consulted only after
crt.sh has already failed, so a crt.sh outage becomes a silent successful
check instead of a warning -- while preserving real security coverage.
- CertspotterCtLogFetcher: GET api.certspotter.com/v1/issuances and translate
each issuance's issuer.name into a crt.sh-shaped CtLogEntry. Certspotter's
issuer.name is byte-identical to crt.sh's issuer_name (verified against live
data: same C=US, O=..., CN=... DN order + comma-space), so no normalization
is needed and there is zero false-Alert risk. Non-2xx throws IOException.
- CompositeCtLogFetcher(primary, fallback): try crt.sh; on any failure try
certspotter; if both fail, rethrow the PRIMARY error so the monitor's
warning text stays meaningful. CancellationException is rethrown.
- Wire AppModule's CtLogFetcher to the composite.
CtLogMonitor, HttpCtLogFetcher, SecurityCheckWorker, and the notification
path are unchanged -- this only makes the underlying fetch succeed more
often, so there is no UX/error-surface change.
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
The #446 teardown sequence (withTimeoutOrNull { mcpSession.shutdown() }
then tunnelClient.disconnect()) was duplicated in two modules:
TunnelForegroundService.onDestroy (:work) and the IdleTimeoutManager
onTimeout lambda wired in AppModule (:app), each with its own copy of the
GRACEFUL_SHUTDOWN_TIMEOUT_MS = 5_000L constant. Tuning one (timeout,
ordering, an added step) would silently drift the other across modules.
Factor the sequence into a single `suspend fun gracefulTunnelShutdown`
plus one GRACEFUL_SHUTDOWN_TIMEOUT_MS constant in :work (the lowest module
that already depends on both :core:mcp and :core:tunnel, and is depended on
by :app). Both call sites now invoke it. Pure refactor: ordering, the 5s
value, and the onDestroy lifecycleScope.launch structure are unchanged.
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
The entire "Connection" settings group was built as UI but never connected
to the ViewModel/destination, so four controls were silently inert:
- the idle-timeout dropdown discarded its selection (`setIdleTimeout` threw
away its argument; the displayed value was a hardcoded 5);
- the "Disable timeout" switch's callback was unwired and it was gated on a
`batteryOptimizationExempt` flag hardcoded to false (permanently greyed);
- the battery-optimization warning's `showBatteryWarning` was hardcoded true,
so every user saw a permanent, non-actionable warning;
- the "Fix this" button's callback was unwired.
Wire all four to behave as their labels promise:
- persist idle-timeout minutes + the disable flag in AppStatePreferences;
- IdleTimeoutManager now reads its timeout from a `suspend () -> Long?`
provider each CONNECTED cycle (null = disabled => timer never arms), so a
settings change takes effect on the next wake without a service restart;
- derive batteryOptimizationExempt + showBatteryWarning from the real
PowerManager status via a shared BatteryOptimization helper (lifted from
BugReportUriBuilder), re-read on Settings resume;
- "Fix this" opens ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS (no
Play-restricted permission, unlike the direct-request intent).
Tests cover the prefs round-trip, the dynamic/disabled timeout provider, the
battery helper, and the ViewModel persist + state-reflection paths. Verified
on a Pixel 6 Pro (Android 17): selecting 10 min updates live and survives a
process restart. docs/ux-decisions.md records activating the battery-opt
system screen via the existing "Fix this" button.
With the timeout disabled the tunnel stays foregrounded until the 6h dataSync
FGS cap stops it (the #452 path) — intended semantics.
Fixes#453
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
When the phone's idle timeout fires, abrupt tunnel teardown kills active
SSE streams. Claude Code counts each disconnect as a terminal error and
after 3 sleep/wake cycles marks the server as permanently dead.
Add McpRoutes.shutdown() that cleanly closes all session transports
before the tunnel is torn down. SSE handlers exit their keepalive loop
normally so the client sees a server-initiated close instead of a reset.
Wire the shutdown into both IdleTimeoutManager.onTimeout and
TunnelForegroundService.onDestroy with a 5-second timeout guard.
Closes#446
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Debug builds now send prefix: "test" in /request-subdomain requests,
producing subdomains like test-cliff instead of cliff. This stops
testing from burning the finite single-word pool.
Relay: accept optional prefix field (validated: alphanumeric+hyphen,
max 10 chars), prepend to single-word candidates only.
Android: pass subdomainPrefix through RelayApiClient constructor,
wired from BuildConfig.DEBUG in AppModule.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1. Replace newRequestFlow (SharedFlow replay=0) with pendingRequestsFlow
(StateFlow) in IntegrationEnabledDestination so pre-existing auth
requests trigger navigation immediately on composition entry.
2. Add navigate_to=auth_approval extra to AuthRequestNotifier's
contentIntent so notification taps route to the approval screen
instead of whatever route was last visible.
3. Handle navigate_to extra in MainActivity.destinationForNotificationIntent
and add onNewIntent override for warm-start notification deep links.
Closes#435
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Delete 13 orphan screenshot PNGs that had no backing tests (disabled
picker, add-client, bottom-inset, quick-render variants). Remove
ManageScreenQuickRender.kt (duplicated by ScreenScreenshotTest) and
stop BottomInsetScreenshotTest from writing screenshot side-effects
so the deleted files stay gone.
Add screenshot tests for IntegrationEnabledScreen with Loading URL
state (16b) and AllClientsContent (20). Update gallery index.html
to match.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Three sibling instances of the cold-start async-state-not-loaded-yet race
that #416 fixed for ProviderRegistry (issue #414). Each used the same
shape: async state seeded into a StateFlow with a default value, read
synchronously by callers that fire during the cold-start window between
process spawn and the first DataStore emission.
Finding #1 (HIGH) - securityAlertCheck
The McpSession `securityAlertCheck` lambda was `() -> Boolean` reading
`alertFlag.value` from a `combine().stateIn(..., initialValue = false)`
flow. On cold-start FCM wake the very first request arrived before the
flow had emitted, so a device whose security check reported `alert`
answered the request anyway. Subsequent requests refused correctly.
Fix: introduce SecurityAlertGate (mirrors ProviderRegistry's awaitReady
shape) that suspends until the underlying combined flow has emitted
once, then exposes `suspend fun isAlerting()`. McpRouting's
`securityAlertCheck` lambda type changes to `suspend () -> Boolean`;
existing test lambdas (`{ true }` / `{ false }`) auto-cast.
Finding #2 (MEDIUM) - OutreachIntegration._directLaunchEnabled
`canLaunchDirectly` was a `() -> Boolean` reading
`_directLaunchEnabled.value` from a MutableStateFlow seeded by an
`appScope.launch{}` collector. First tool call after cold-start could
mis-route through the notification fallback even when the user had
opted into direct launch.
Fix: convert `canLaunchDirectly` to `suspend () -> Boolean` through the
chain (LaunchAppTool, OpenLinkTool, launchActivitySafely). Add
`awaitReady` / `awaitReadyBlocking` to OutreachIntegration; the lambda
becomes `{ isDirectLaunchAllowed() }` which suspends on awaitReady
before reading the flow value.
Finding #3 (MEDIUM, latent) - DeviceRegistrationStatus
Constructed with `initiallyRegistered = false` and an
`appScope.launch{ if (certStore.getSubdomain() != null) markComplete() }`.
Currently safe only because IntegrationSetupViewModel.awaitRegistrationIfNeeded
(issue #242) consults the cert store directly; future readers that add
`.complete.value` without copying the workaround re-introduce the bug.
Fix: add `DeviceRegistrationStatus.create(scope, suspend isRegistered)`
factory that runs the check in `scope` and signals `awaitReady` once it
resolves. AppModule's Koin binding switches to `create()`. The
synchronous constructor is preserved for tests; both code paths signal
readiness eagerly when the answer is known up front.
Per #419 hard rules:
- Workaround in IntegrationSetupViewModel.awaitRegistrationIfNeeded
left in place; no UX-flow files touched.
- No runBlocking added to production code.
Tests:
- SecurityAlertGateTest (new): slow-flow regression + idempotent
awaitReady + empty-first-emission ready signal.
- DeviceRegistrationStatusTest (extended): create() defers awaitReady
until check resolves; both true/false verdicts unblock.
- OutreachIntegrationTest (extended): mockk-based slow settings store
proves awaitReady waits for first emission.
- HttpRoutingTest (extended): suspend-awaiting securityAlertCheck still
rejects with 503.
Verification:
- `./gradlew :app:testDebugUnitTest :work:testDebugUnitTest :core:mcp:jvmTest :integrations:testDebugUnitTest` all green.
- `./gradlew ktlintCheck detekt` clean.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
On a cold-start FCM wake, FcmReceiver and TunnelForegroundService both read
ProviderRegistry.enabledPaths() synchronously to decide whether to honor the
wake. The app-side IntegrationProviderRegistry is DataStore-backed: its
_enabledIds StateFlow starts at emptySet() and only populates after the first
async combine() emission lands. In a freshly-spawned process the FCM message
arrives before that emission, the synchronous read returns emptySet(), and the
wake is silently dropped — every subsequent AI-client request EOFs after the
relay's 20s wakeup timeout.
This fix introduces ProviderRegistry.awaitReady()/awaitReadyBlocking() and
routes the three production callers through it before checking enabledPaths():
- FcmReceiver.onMessageReceived blocks the FCM worker thread (NOT main) on a
CountDownLatch with a 2s timeout, then runs the empty-check and dispatches.
- TunnelForegroundService.onStartCommand defers the empty-check into a
lifecycleScope coroutine that suspends on awaitReady() first.
- The state-store collector signals readiness on its first emission (which is
emptySet() if nothing is enabled on disk — still a valid loaded state).
Empty integrations list → registry is trivially ready (no flow to wait on).
On timeout, drop the wake rather than spin up the tunnel against unknown state.
Reproduced via /tmp/probe-fresh and /tmp/probe-warm1: relay sends FCM, device
logs "Ignoring wake: no integrations enabled" and returns, relay's 20s timer
fires, client gets TLS EOF. The new FcmReceiverTest.`wake dispatches to
startService once registry becomes ready with enabled state` regression test
fails on the pre-fix code (verified) and passes here.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
NotificationPreferences previously resolved its own
`koinViewModel<OnboardingViewModel>()` scoped to its NavBackStackEntry,
called `startOnboarding()` on that VM, then navigated to the onboarding
destination. Because Compose Navigation scopes VMs per backstack entry,
the onboarding destination then instantiated a *second* VM whose init
read a still-null subdomain and parked at NotOnboarded forever. The
first VM's appScope coroutine succeeded — subdomain + certs landed on
disk — but no UI observer saw it, so fresh installs were stuck on the
Welcome screen despite a perfectly healthy backend onboarding.
Scope the startOnboarding trigger to the onboarding destination itself
via an optional `autostart=true` nav arg (Option 3 from the bug). The
NotificationPreferences Continue handler now just navigates to
`Routes.ONBOARDING_AUTOSTART`, popping ONBOARDING inclusive; the new
destination entry's VM reads the arg, fires startOnboarding(), drives
the flow on appScope, flips to Onboarded on completion, and navigates
to Home. One VM owns the whole lifecycle.
Avoided Option 1 (nested nav graph + koinNavGraphViewModel) because it
would have restructured AppNavigation's root NavHost for a two-screen
flow. Avoided Option 2 (CertificateStore Flow<String?>) because it
bloats the store contract for what is fundamentally a UI-layer bug.
Tests:
- OnboardingDestinationContentTest drives the extracted
OnboardingDestinationContent composable to prove autostart=true fires
onStartOnboarding exactly once, autostart=false does not, and an
Onboarded state transition fires onOnboarded for the Home navigation.
- BackStackFlowTest updated to model the Welcome -> NotifPrefs ->
Onboarding(autostart) -> Home path with the right popUpTo semantics.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Fix#389: Provision certs during onboarding so fresh installs land in a usable state
Extend OnboardingFlow to chain CertProvisioningFlow.execute after subdomain
registration succeeds so a fresh install ends with all three PEMs (ACME
server cert, relay-CA client cert, relay CA) persisted on disk instead of
just the subdomain file. Without this hop the device appeared functional
(dashboard rendered, pending integrations visible) but every incoming AI
TLS handshake EOF'd and every WS reconnect 401'd because the store had no
certs to present — the root cause of #386 and #387.
OnboardingViewModel now routes cert-provisioning outcomes into retryable
OnboardingState.Failed / RateLimited surfaces with a "Try again" entry
point, and the UI holds on the onboarding screen during the several-second
ACME hop instead of silently dropping the user on Home with a half-
configured install. The subdomain is preserved across cert failures (#163)
so retry re-runs only the cert issuance step.
Idempotency via CertProvisioningFlow.AlreadyProvisioned means the existing
IntegrationSetupViewModel path is unchanged: enabling an integration on a
device that already has certs short-circuits as before.
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Fix#389 (follow-up): Keep integration harness OnboardingFlow without chained cert provisioning
The initial commit wired CertProvisioningFlow into the integration harness's
OnboardingFlow override to mirror production. That broke every integration
scenario that drives both flows explicitly (HarnessSmokeTest +
OnboardingHappyPathTest pattern) because the second explicit cert call
returns AlreadyProvisioned instead of Success, tripping the asserts, and
also inflated the per-test /register/certs counter assertions.
Flip the override back to an OnboardingFlow without the chained cert step
so ProvisioningExtensions.provisionDevice keeps its "call both flows
explicitly" contract. Production still chains — the change in appModule
and the OnboardingFlow surface are untouched.
OnboardingInterruptedResumableTest can go back to using the Koin-supplied
flow now that the harness override is no-cert-chain again.
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Three tightly-coupled bugs in the shared audit-row surfaces:
1. ListRow previously used `defaultMinSize(minHeight = 56.dp)` with no
vertical padding. Single-line rows looked right (floor set by
min-height, content centered) but multi-line content (e.g. a long
JSON `arguments` string in ToolCallRow) grew the row height and then
pressed flush against the top and bottom edges of the card. Replace
the min-height floor with `padding(vertical = 12.dp)`: single-line
rows keep a ~48 dp height which matches existing density, multi-line
rows now have breathing room. Applied to `ListRow`,
`ListRowWithIcon`, and `ListRowWithTrailing`.
2. `AuditHistoryViewModel.toHistoryEntry` fell back to the raw
`entry.argumentsJson` / `entry.resultJson` columns whenever the
FieldEncryptor was null or `decrypt()` returned null. Those columns
hold ciphertext at rest, so the fallback rendered base64-looking
blobs into the dashboard's Recent Activity teaser and the audit
detail screen. Root cause of the null-encryptor path was that
MainDashboardViewModel and IntegrationManageViewModel never received
the encryptor. Fix both:
- Remove the raw-column fallback everywhere. Render "" (empty) when
decrypt is unavailable; ciphertext is never rendered as plaintext
even if future call sites forget to wire the encryptor.
- Thread `FieldEncryptor` through MainDashboardViewModel and
IntegrationManageViewModel via Koin so production paths always
decrypt.
- Apply the same fix to `AuditDetailDestination` and to
`NotificationMcpProvider.recordToJson` (which returned ciphertext
over the MCP wire to the AI client when the encryptor was null).
3. In ToolCallRow's row 2 the outer Row was
`verticalAlignment = CenterVertically`. When a long `arguments`
string wrapped to multiple lines, the timestamp on the right floated
to the vertical center of the wrapped block while the duration
stayed pinned to the top, looking misaligned. Switch to
`Alignment.Top` so the time stays pinned alongside the duration on
the first wrapped line.
Tests:
- New AuditHistoryViewModelTest cases pin the fallback contract: with
a null FieldEncryptor or a decrypt that returns null, the resulting
AuditHistoryEntry.arguments is "" and argumentsJson / resultJson are
null, never raw ciphertext.
- New screenshot case 34b_audit_history_long_args (light + dark)
renders a multi-line JSON `arguments` block. Locks in the padding
+ top-alignment fix; regressions will show immediately as a visual
diff.
- Re-record affected goldens (08 dashboard, 17/18a integration manage,
34/36/36a audit history, 99 bottom-inset manage, quick_* preview set).
Trust-card 50* goldens intentionally NOT re-recorded (different
issue area).
- Update NotificationMcpToolExecutionTest to use a passthrough
encryptor by default so existing plaintext-round-trip tests keep
working under the stricter no-ciphertext-fallback contract.
Closes#383
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
- Add a Privacy row in the Settings About section that opens
`https://rousecontext.com/privacy` via `ACTION_VIEW`. The docs page
itself already lives at `docs/user/privacy.md`; this PR wires the
in-app link and adds the label string.
- Add a debug-only Developer section with a "Renew cert now" button
that enqueues a one-shot cert renewal through a new
`CertRenewalScheduler.enqueueOneShot` entrypoint (distinct unique-work
slot, REPLACE policy so spammed taps collapse to a single pending
request). Gated on `BuildConfig.DEBUG` so the section is not rendered
for release users.
- Extract a `renewalConstraints()` helper in `CertRenewalScheduler` so
the periodic, delayed, expiring-immediate, and one-shot paths all
share the same `NetworkType.CONNECTED + requiresBatteryNotLow`
constraints instead of duplicating the builder three times.
- Force `showDeveloperSection = false` in the Settings Roborazzi
screenshot tests so the recorded goldens match what release users
see, regardless of `BuildConfig.DEBUG` in the test variant. The
Privacy row is visible in release builds so it does appear in the
goldens (though the Settings layout happens to render it below the
800dp test viewport, so the existing PNGs remain pixel-identical).
Tests:
- `CertRenewalSchedulerTest` covers the new one-shot path: enqueue,
REPLACE-on-re-enqueue, and slot distinctness from the periodic and
immediate slots.
- `SettingsPrivacyRowTest` (new) asserts the Privacy row renders and
fires its callback, that the Developer section is hidden when
`showDeveloperSection = false`, and that tapping "Renew cert now"
fires the callback and surfaces the "Renewal enqueued" confirmation.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Auditted every production log site in Kotlin and Rust against the
sensitivity list in #379. Two real leaks found and fixed; a logging
policy is documented and a CI grep gate catches known-bad patterns in
future PRs.
Scrubbed:
- `OnboardingViewModel`: was logging 20-char prefixes of the Firebase
ID token and the FCM token. Both are bearer credentials and `logcat`
is reachable via adb / `READ_LOGS` on older Android, so even prefixes
are sensitive. Replaced with length-only summaries.
- `relay/src/main.rs` connection handler: the "Routing decision" log
used `?decision` (Debug format) on `RouteDecision`, which includes
the `integration_secret` string on `DevicePassthrough`. That secret
is the bearer credential an AI client presents in the SNI label to
route to a specific integration -- logging it defeats the point.
Added a `route_decision_log` helper that renders the variant plus the
subdomain (public routing identity) without the secret.
Everything else on the priority list (McpRouting, RoomTokenStore,
CertRenewalScheduler/Worker, AcmeClient, TunnelClientImpl, MuxDemux,
FcmReceiver, relay main/tls/ws) was already scrub-clean: they log
state transitions, counts, durations, error types, and the relay's
operational subdomain -- never tokens, bodies, tool-call arguments,
cert material, or secrets.
Regression protection:
- CI grep gate in `.github/workflows/ci.yml` fails the build if known
bad patterns (`Log.<level>(... "$token"` etc., `args: $...`) appear
in Kotlin production sources.
- `docs/internal/logging.md` documents what we log, what we don't,
and how to add new log lines safely.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
DataStore enforces one active instance per file path via a static
`activeFiles` set in `FileStorage`. The "second labeler backed by same
file" test simulates process death by cancelling the first scope before
opening a second DataStore pointed at the same file.
`CoroutineScope.cancel()` is asynchronous: the connection's
`invokeOnCompletion` handler (which removes the file from `activeFiles`)
has not necessarily run by the time control returns. The second
`PreferenceDataStoreFactory.create(...)` call then races with the
cleanup and throws `IllegalStateException` at `FileStorage.kt:52` when
it sees the file still in the active set.
Join the scope's job after cancellation so we observe the completion
handler's effects before opening the new DataStore. Mirrors the pattern
applied in PR #360 for `NotificationIdCounterTest` (#359). No production
code changes.
Verified stable across 20 rerun-task iterations locally.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Matches the dashboard's RECENT_LIMIT for consistency now that both
surfaces use the shared ToolCallRow widget (see #370). Users wanted
the card to stay a teaser; 20 felt too dense for that role.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Brings the three "Recent Activity" surfaces (dashboard teaser,
integration-manage, audit history) in line with each other and removes
two rough edges around the audit date filter.
1. Audit default filter flips from TODAY to LAST_7_DAYS so "View all"
from the dashboard's rolling-24h teaser always lands on a filter
that encloses the row the user just saw.
2. Summary notification taps no longer override the audit date filter
with the session time window — users pushed back on the silent
override added in #347. Removes EXTRA_START_MILLIS / EXTRA_END_MILLIS
from SessionSummaryNotifier's tap PendingIntent and cuts the
startMillis / endMillis nav args from Routes.AUDIT; the
applySessionWindow / clearSessionWindow / sessionWindow state on
AuditHistoryViewModel is gone. Per-tool-call taps still carry
scrollToCallId.
3. Dashboard's rolling-24h cutoff now recomputes reactively. A 60 s
ticker flow drives flatMapLatest over observeRecent so entries that
age out drop off naturally; previously the cutoff was pinned at VM
init and never rolled forward. The ticker is injectable for
deterministic test control.
4. "View all" nav is consistent: dashboard → plain Routes.audit()
(default LAST_7_DAYS now encloses the 24h teaser); integration
manage → Routes.audit(provider = id) (unchanged).
5. A single shared ToolCallRow widget replaces the three separate row
implementations. The variant-7 layout (#366) moves from private in
AuditHistoryScreen to ui/components/ToolCallRow.kt. All three
surfaces render tool calls as AuditHistoryEntry via the shared
AuditHistoryViewModel.toHistoryEntry mapper.
Tests updated:
- AuditHistoryViewModelTest asserts LAST_7_DAYS default; session-window
tests removed (feature is gone).
- MainDashboardViewModelTest adds a rolling-24h window advances test
driven by a MutableStateFlow ticker (virtual time, no real sleep).
- MainActivityNotificationRoutingTest replaces the "summary tap
encodes start/end millis" case with one that asserts the summary
tap returns the bare audit route with no window extras.
- SessionSummaryNotifierTest renames the corresponding notifier test
and drops the EXTRA_START_MILLIS / EXTRA_END_MILLIS assertions.
- Roborazzi goldens re-recorded for dashboard + integration-manage +
audit surfaces that changed. Trust-card goldens untouched (#364).
Related: #347 (notification copy + deep-links, session-window override
reverted here), #366 (variant 7 production rollout, widget extracted
here), #368 (stale-empty + nav extras, deep-link behaviour cleanup
continues here).
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Bug A: AuditHistoryViewModel.state used
SharingStarted.WhileSubscribed(5_000L). When the user left the audit
screen and a tool call inserted an audit row during the grace window,
a re-subscribing consumer (notification tap) was served the cached
empty-state snapshot because Room's invalidation-tracker re-emission
through a still-alive-but-subscriberless upstream is not guaranteed.
Root cause confirmed by a Robolectric + in-memory Room repro test that
subscribes, unsubscribes, inserts a row, re-subscribes, and asserts the
new row surfaces. The test hangs with the 5s grace (bug reproduced)
and passes with a 0s grace (tear down + rebuild on every subscribe).
The grace provided no measurable benefit — the audit screen is not a
hot re-entry surface — so the minimum-invasive fix is to drop it.
Bug B: MainActivity.destinationForNotificationIntent returned bare
Routes.AUDIT_BASE for both notifier actions, discarding the
per-tool-call scrollToCallId and the session-summary start/end-millis
extras. The destination reads nav args, not intent extras, so those
deep-link targets never reached the ViewModel: per-tool-call taps
never scrolled to the called row and summary taps never applied the
session time window.
Builds the route via Routes.audit(...) populated from intent extras,
falling back to the plain Routes.AUDIT_BASE when no extras are present.
Tests:
- AuditHistoryViewModelRoomTest: stale-empty-state repro (Robolectric
+ in-memory Room).
- MainActivityNotificationRoutingTest: scroll-to-call, session-window,
bare-route, manage-with-id, manage-without-id, open-home, unrelated-
intent, null-intent branches of destinationForNotificationIntent.
- AuditHistoryViewModelTest: new coverage for requestScrollTo /
consumeScrollTarget lifecycle and applySessionWindow overriding the
date filter in the DAO query.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Tighten variant 7 time right-edge (4dp end padding)
The user felt the pill in variant 7 looked like it had extra padding
to its right. The cause is optical: the pill has 8dp internal
horizontal padding, so its inner text ends ~9dp left of its outer
border. The time text below had no end padding, so its last glyph
sat at the row's full right-inset edge — making the time read as
"further right" than the pill's text.
Adding 4dp of end padding to the time pulls its glyph inward to
partially match the pill's internal right inset, bringing the two
text right-edges closer optically.
Only variant 7's time is touched; production ToolCallRow and
ListRow are unchanged.
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Fix#366: Land variant 7 in production ToolCallRow and drop preview scaffolding
Ships the winning audit-row design (variant 7 from the #343 preview review,
tuned in #363 / #365) into the production audit history screen, wiring the
real `AuditEntry.clientLabel` added in #344 through the ViewModel and
rendering it as a right-aligned client pill on row 1 with the call time
stacked directly below. Rows whose `clientLabel` is null (predate the
schema v3 -> v4 migration) omit the pill entirely rather than render a
placeholder that would collide with the real `Unknown (#N)` labels the
[UnknownClientLabeler] produces (#345).
Extracts `ClientPill` as a shared composable in `ui/components/` so the
pill is now part of the app's real design language — not a preview helper.
Deletes the preview scaffolding (`AuditRowVariants.kt`,
`AuditRowVariantsScreenshotTest.kt`, `AuditRowCatalogHtmlWriter.kt`, the
`app/screenshots/audit-row-variants/` directory, and
`docs/internal/audit-row-variants/index.html`), removes the corresponding
tab from the unified internal dashboard (#348) and drops the matching
copy step from `pages.yml`.
Regenerates the four audit-screen Roborazzi goldens
(`34_audit_history_populated_*`, `36_audit_history_filtered_*`,
`36a_audit_history_show_all_mcp_messages_*`) with representative
clientLabel values (short, long, null, and `Unknown (#1)`) so the pill
behaviour is visible across all three length classes.
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
The user felt the pill in variant 7 looked like it had extra padding
to its right. The cause is optical: the pill has 8dp internal
horizontal padding, so its inner text ends ~9dp left of its outer
border. The time text below had no end padding, so its last glyph
sat at the row's full right-inset edge — making the time read as
"further right" than the pill's text.
Adding 4dp of end padding to the time pulls its glyph inward to
partially match the pill's internal right inset, bringing the two
text right-edges closer optically.
Only variant 7's time is touched; production ToolCallRow and
ListRow are unchanged.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Fix#347: Client-subject notification copy + deep-link taps + Manage action
Rewrite per-tool-call and session-summary notification copy per the locked
#342 design, wire up notification tap deep-links, and add a Manage action
button.
Per-tool-call notifications now read "${clientLabel} used ${humanized(toolName)}"
with the integration display name as body and the call timestamp rendered
natively via setWhen(). Session-summary notifications partition by client
label and emit one notification per client titled "${clientLabel} used
${count} ${tool|tools}" with up to 3 unique humanized tool names in the
body (Oxford comma, "and N more" past the cap).
Tap deep-links route to the audit-history screen — scrolled to the
specific call (per-tool-call) or filtered to the session time window
(summary) — and a single Manage action button points at the integration
manage page (or home, when a summary's calls span multiple integrations).
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Update integration tests for per-client summary notification ids
#347 changed SessionSummaryNotifier from a single-id summary to one
notification per client, keyed by the clientLabel hash. The existing
:app:integrationTest fixtures still asserted against the legacy
SessionSummaryNotifier.NOTIFICATION_ID constant, so they failed in CI.
Updated each affected test to compute the expected id via
SessionSummaryNotifier.idForClient(<clientLabel>) and dropped the
now-unused NOTIFICATION_ID companion constant. The InMemoryTokenStore
resolves clientName=null to the clientId, so for tests that pass
clientName=null the expected label is their clientId string (e.g.
"race-test", "multi-test", "runtime-mode-switch"). ToolCallHappyPathTest
passes clientName = "Test Client" explicitly.
Also retargeted the MultiToolSessionTest title-string assertion from the
old "{count} calls across {N} integrations" copy to the new
"{clientLabel} used {count} tools" title shape.
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Move summary notification id bucket below per-call range
The previous summary id bucket (6000..15999) overlapped with
PerToolCallNotifier.BASE_ID = 7000, so any clientLabel whose hash
.mod(10000) landed in 1000..9999 produced an id that collided with
per-call notifications. RuntimeNotificationModeSwitchTest failed in CI
because its clientLabel "runtime-mode-switch" hashes to
idForClient(...) = 7465, which the test's "id >= PerToolCallNotifier.BASE_ID"
probe flagged as a per-call notification during phase 1 (SUMMARY mode).
Narrow the bucket to 4000..4999 so summary ids stay clear of the per-call
range. Collisions inside the 1000-entry bucket remain acceptable for the
expected <100-clients-on-a-device cardinality.
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Add audit row variant 7 (pill top-right, time below)
Extends the #343 design-review catalog with a seventh client-label
placement option: the client pill sits alone at the top-right of row 1
and the timestamp right-aligns on row 2 directly beneath it. Unlike
variant 3, which packs the pill and time together on row 1, this layout
keeps the pill prominent without crowding the time next to it.
Preview-only; production `ToolCallRow` and `AuditEntry` are unchanged.
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Fix#347: Client-subject notification copy + deep-link taps + Manage action
Rewrite per-tool-call and session-summary notification copy per the locked
#342 design, wire up notification tap deep-links, and add a Manage action
button.
Per-tool-call notifications now read "${clientLabel} used ${humanized(toolName)}"
with the integration display name as body and the call timestamp rendered
natively via setWhen(). Session-summary notifications partition by client
label and emit one notification per client titled "${clientLabel} used
${count} ${tool|tools}" with up to 3 unique humanized tool names in the
body (Oxford comma, "and N more" past the cap).
Tap deep-links route to the audit-history screen — scrolled to the
specific call (per-tool-call) or filtered to the session time window
(summary) — and a single Manage action button points at the integration
manage page (or home, when a summary's calls span multiple integrations).
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Update integration tests for per-client summary notification ids
#347 changed SessionSummaryNotifier from a single-id summary to one
notification per client, keyed by the clientLabel hash. The existing
:app:integrationTest fixtures still asserted against the legacy
SessionSummaryNotifier.NOTIFICATION_ID constant, so they failed in CI.
Updated each affected test to compute the expected id via
SessionSummaryNotifier.idForClient(<clientLabel>) and dropped the
now-unused NOTIFICATION_ID companion constant. The InMemoryTokenStore
resolves clientName=null to the clientId, so for tests that pass
clientName=null the expected label is their clientId string (e.g.
"race-test", "multi-test", "runtime-mode-switch"). ToolCallHappyPathTest
passes clientName = "Test Client" explicitly.
Also retargeted the MultiToolSessionTest title-string assertion from the
old "{count} calls across {N} integrations" copy to the new
"{clientLabel} used {count} tools" title shape.
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
* Move summary notification id bucket below per-call range
The previous summary id bucket (6000..15999) overlapped with
PerToolCallNotifier.BASE_ID = 7000, so any clientLabel whose hash
.mod(10000) landed in 1000..9999 produced an id that collided with
per-call notifications. RuntimeNotificationModeSwitchTest failed in CI
because its clientLabel "runtime-mode-switch" hashes to
idForClient(...) = 7465, which the test's "id >= PerToolCallNotifier.BASE_ID"
probe flagged as a per-call notification during phase 1 (SUMMARY mode).
Narrow the bucket to 4000..4999 so summary ids stay clear of the per-call
range. Collisions inside the 1000-entry bucket remain acceptable for the
expected <100-clients-on-a-device cardinality.
Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Dynamic Client Registration that omits client_name used to persist the
literal string "unknown" as the audit label, collapsing every
unauthenticated-at-DCR caller into one indistinguishable row. Introduce a
DataStore-backed UnknownClientLabeler that maps each client_id to a
monotonic "Unknown (#N)" label, wired through configureMcpRouting and
McpSession.
Changes:
- `UnknownClientLabeler` interface in `:core:mcp`, `DataStoreUnknownClientLabeler`
in `:app` with per-client `stringPreferencesKey` + monotonic `next_index`
counter in a dedicated `unknown_client_labels` DataStore file.
- `/register` replaces `?: "unknown"` with `?: labeler.labelFor(clientId)`
so new rows start life with the proper label.
- Pre-#345 rows are lazily upgraded on first MCP tool call via a new
`TokenStore.upgradeClientLabel(integrationId, clientId, label)` method,
so the authorized-clients list picks up the label without a schema
migration.
- `null` labeler keeps the legacy literal fallback so older tests and
embed paths keep compiling unchanged.
Tests:
- `DataStoreUnknownClientLabelerTest` (idempotency, monotonicity,
persistence, concurrent assignment, format).
- `UnknownClientLabelerRoutingTest` (DCR w/ and w/o client_name, legacy
upgrade on tool call, stability across sessions).
- `RoomTokenStoreTest` coverage for `upgradeClientLabel` (multi-row,
integration-scoped, no-op).
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Every tool-call audit event now carries a clientLabel captured once per
MCP session from the OAuth Bearer token, and every persisted audit row
stores the same label so the UI can attribute tool calls to the AI
client that invoked them.
- `ToolCallEvent` gains a non-null `clientLabel: String` field with a
fallback literal `UNKNOWN_CLIENT_LABEL = "Unknown"` for unauthenticated
sessions. #345 will replace the literal with monotonic
`Unknown (#N)` numbering.
- `TokenStore.resolveClientLabel(integrationId, token)` returns the
audit-facing label (clientName fallback to clientId) for valid tokens
and null otherwise; implemented in both `InMemoryTokenStore` and
`RoomTokenStore`.
- `McpRouting.handleMcp()` resolves the label once on successful auth
and caches it on the per-session `SessionEntry` so every subsequent
tool-call emit within the session carries the same label without
re-reading the token store.
- `AuditEntry` gains a nullable `clientLabel` column; `RoomAuditListener`
populates it from the event. `AuditDatabase` bumps to v4 with a
`MIGRATION_3_4` that `ALTER TABLE audit_entries ADD COLUMN
clientLabel TEXT`.
- Room schema export enabled for `:notifications`; v4 schema checked in
under `notifications/schemas/`.
Tests (TDD):
- `ClientLabelCaptureTest` drives the full McpRouting stack and asserts
three tool calls in the same session all carry the cached label,
a clientName-less DCR registration falls back to the clientId label,
and `resolveClientLabel` returns null for invalid tokens.
- `RoomAuditListenerTest` adds a regression that `onToolCall` persists
`clientLabel` onto the row.
- `AuditMigrationTest` (Robolectric) hand-builds a v3 `audit_entries`
table, reopens the DB with Room at v4 to run `MIGRATION_3_4`, and
verifies pre-migration rows survive with `clientLabel = null` while a
fresh row round-trips the populated column. Room's schema validator
running on the reopened DB doubles as a regression check that the
`ALTER TABLE` matches the entity definition.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
The EACH_USAGE per-tool-call notifier was collapsing/overwriting
notifications in two ways:
1. Its AtomicInteger id counter lived only in memory, so every FCM-driven
cold start reset ids back to BASE_ID (7000). A notification posted by
process A with id 7000 was silently overwritten when process B posted
its first per-call notification. Replace the in-memory counter with
NotificationIdCounter — a DataStore-backed monotonic counter
(wrapping at 10,000 to stay within the reserved id window) so the
sequence survives process death.
2. Each notification set a group key but no group summary was ever
posted. Android visually collapses grouped children into the most
recent entry when no summary is present, so users saw just one row
for N tool calls. Drop setGroup entirely; each call is its own row.
Android still clusters same-app notifications under one header in the
shade — that is OS-level behaviour and out of scope here.
Wire NotificationIdCounter through Koin (AppModule.kt) and update tests
to verify: monotonic across a simulated cold start, distinct ids for
successive calls, wraparound at WRAP_AT, and that the posted
Notification.group is null. Screenshot goldens unchanged (verified via
verifyRoborazziDebug).
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
The periodic SecurityCheckWorker was enqueued with no Constraints, so it
fired while offline or behind a captive portal. Captive portals respond
to the crt.sh lookup with an HTML interstitial, which the worker reported
as "crt.sh returned HTTP 404 body=<!DOCTYPE H..." — a false-positive
notification every time a user walked into a hotel lobby, cafe, or metro.
Extract the scheduling into a new SecurityCheckScheduler object under
:work (mirroring CertRenewalScheduler) and apply the same constraints
the cert-renewal worker already uses:
- NetworkType.CONNECTED — the whole point: don't fire when the only
reachable host is a captive-portal interstitial.
- requiresBatteryNotLow=true — consistent with renewal; no reason to
spend the last 10% on a monitoring check.
Extracting to a scheduler object makes the constraints unit-testable in
:work without needing to drive the Application subclass through
Robolectric — the same pattern CertRenewalScheduler established for #277.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Produces six candidate layouts for the audit history's ToolCallRow so the
client-label placement decision (#342) can be approved against actual
screenshots. Each variant renders three client-label length classes
(short, long, unknown) in both light and dark theme, publishing the
catalog to rousecontext.com/internal/audit-row-variants/ via the existing
Pages workflow.
- New `AuditRowVariants.kt` preview composables for:
1. Third row, full-width client label
2. Second-row prefix (`Claude . 142ms . {args...}`)
3. Right-aligned pill between tool name and time
4. Leading colored initial chip
5. Session-grouped header (client shown once per session)
6. Variant 1 + Variant 5 combined
- Roborazzi screenshot test writes to
`app/screenshots/audit-row-variants/` and emits the catalog HTML to
`docs/internal/audit-row-variants/index.html` via a `@ClassRule` mirror
of `NotificationCatalogHtmlWriter` from #335.
- Pages workflow path trigger extended to include `docs/internal/**` and
`app/screenshots/audit-row-variants/**`; new copy step serves the
catalog and its screenshots under `/internal/audit-row-variants/`.
Production `ToolCallRow` at `AuditHistoryScreen.kt:413` is not modified;
`AuditEntry.clientLabel` is not introduced. Both are deferred to the
follow-up that implements the chosen variant after design review.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
On cold-start FCM wakes, Application.onCreate (Koin graph, Firebase,
notification channels) consumed most of the 5-second FGS timer budget,
leaving almost no margin for TunnelForegroundService.startForeground().
When the budget was exceeded, Android killed the process with
ForegroundServiceDidNotStartInTimeException, closing the WebSocket ~4s
after connection.
Two changes eliminate the race:
1. TunnelForegroundService.onCreate now calls startForeground() as its
very first action after super.onCreate(), before
NotificationChannels.createAll() or any coroutine work. The
notification channel already exists from Application.onCreate; the
defensive createAll() is moved after startForeground.
2. RouseApplication.onCreate defers non-critical init (crash reporting,
security-check scheduling, cert renewal scheduling) to a posted
Handler message. This lets the service's onCreate run sooner after
Application.onCreate returns.
A new Robolectric test verifies that the foreground notification is set
synchronously in onCreate, before the main looper drains any coroutines.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Replace `adolin.lan`, device serial `84TY004PW`, and LAN IPs
`192.168.68.*` scattered across e2e tests, device-tests, and docs
with placeholder syntax (`<your-dev-host>`, `<your-device-serial>`,
`<your-lan-ip>`). These values were defaults for local development
and had no reason to live in a public repo.
- `e2e/build.gradle.kts` no longer defaults `adb.host`; the `e2eTest`
task now fails fast via `doFirst` if it's unset.
- e2e test classes read `adb.host` and throw a helpful error when
missing instead of silently falling back to a host that only exists
on the author's LAN.
- `device-tests/DeviceIntegrationTest` reads `lan.ip` from a system
property (or env var) and skips via JUnit `assumeTrue` when unset.
- README grows a short "End-to-end tests" section documenting the
required properties.
Git history still contains the leaked values — per the issue,
rewriting history is disruptive and unlikely to undo exposure on an
already-public repo.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>