FcmTokenRegistrar.registerToken was a no-op that only logged. When FCM
rotated the device token mid-session, the relay kept the stale token
until the next reconnect (could be hours). The pull-on-connect path in
TunnelForegroundService covered the disconnected case but not the
live-session case.
Inject TunnelClient into FcmTokenRegistrar; on token refresh, push via
TunnelClient.sendFcmToken when state is CONNECTED or ACTIVE. Treat
CONNECTING as disconnected to avoid racing a half-open connection.
Swallow send exceptions so a racing disconnect can't crash the FCM
service thread — the next wake's pull will re-sync.
Drop registerCurrentToken() and the RouseApplication.onCreate call site.
It was pure overhead: the tunnel already pulls a fresh token on every
connect, so a startup push adds nothing.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
SecurityCheckNotifier was declared as open class with open methods purely
so test fakes could subclass it. Convert to a proper interface + concrete
AndroidSecurityCheckNotifier implementation. Test fake now implements the
interface directly -- no more open keyword, no surprise overrides.
Koin binding updated to single<SecurityCheckNotifier> { AndroidSecurityCheckNotifier(...) }.
Worker's notifier field type stays the interface.
Id scheme (4210-4213) unchanged; SecurityCheck enum remains nested on the
interface so existing callers need no import changes.
Completes the notifier-pattern cleanup. NotificationAdapter and
NotificationAction had no production call sites — they were exercised
only by their own tests and NotificationIconTest. Their private
buildSessionNotification / buildErrorNotification / buildAlertNotification
helpers were the last classes in :notifications that built-and-returned
a Notification without the startForeground justification.
Every :notifications class now either posts-via-postX (all notifiers) or
is the single documented exception (ForegroundNotifier). Rule satisfied.
NotificationIconTest is rewritten to exercise live notifiers
(ForegroundNotifier, FgsLimitNotifier, SecurityCheckNotifier,
AuthRequestNotifier) instead of the dead adapter. Icon coverage is now
routed through real production code paths.
TunnelForegroundService.updateNotification() still calls
NotificationManager.notify() with the FGS id — Android treats that as an
in-place update of the ongoing foreground notification, so this is an
intentional extension of the startForeground contract. A comment on the
method documents the rationale.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Aligns the session-summary class with the :notifications Notifier naming
convention from issue #125. The class already exposed postSummary(...),
so no method changes are required — only the type name, the file name,
and the test file name. Also updates the KDoc cross-reference in
PerToolCallNotifier and the Koin binding in AppModule.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Aligns the foreground-service notification with the :notifications
notifier naming convention. Since the FGS notification MUST be returned
(to pass to startForeground), the class is documented as the ONE
exception to the 'postX builds and posts' rule.
Renames the top-level createForegroundNotification(...) function into an
object ForegroundNotifier with a build(...) method, and updates the two
call sites (TunnelForegroundService, NotificationAdapter) plus the
Roborazzi screenshot test and icon test.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Move notification posting out of SecurityCheckWorker into a new
SecurityCheckNotifier in :notifications, matching the pattern used by
FgsLimitNotifier. Replace the per-worker-instance nextNotificationId
counter (which started at 200 on every run and silently overwrote prior
runs' alerts) with four stable, semantic ids keyed by (check, severity).
Same-check same-severity reposts now replace the existing notification
(desired for persistent alerts), and different-check alerts no longer
clobber each other. The worker keeps orchestration and SharedPreferences
writes; the notifier is injected via KoinWorkerFactory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Hold the wakelock for 3s after the tunnel transitions to CONNECTED before
releasing. This closes the CONNECTED->ACTIVE window where the relay's first
request frame could be deferred by Doze on non-battery-exempt devices.
- ACTIVE within grace: cancel the pending release, wakelock stays held
- DISCONNECTING/DISCONNECTED within grace: cancel pending release AND release
immediately (no point holding)
- Duplicate CONNECTED emissions reset the timer, never double-release
Tests use runTest + virtual time (advanceTimeBy/advanceUntilIdle) rather
than real delays.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Move completes the refactor: notification-posting logic no longer crosses
the :work -> :notifications boundary. FgsLimitNotifier now follows the
*Notifier convention alongside AuthRequestNotifier, LaunchRequestNotifier,
PerToolCallNotifier, and SessionSummaryPoster.
No behavior change.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Production DI always passed batteryExempt = false, so the short-circuit
branch was unreachable. The mental model was also wrong: battery
exemption excuses Doze restrictions but does not excuse the FGS 6h/24h
cap on dataSync (issue #110), so the flag would have made things worse
if ever enabled.
Removed the constructor parameter, the short-circuit in observe(), the
hardcoded argument in AppModule, and the single test exercising the
removed branch. Idle timeout is now unconditionally on.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Before this fix, when `startForeground(...)` was called after the
cumulative `dataSync` foreground-service budget had been exhausted
(6h / 24h on Android 14+), the resulting
`ForegroundServiceStartNotAllowedException` propagated out of
`TunnelForegroundService.onCreate` and crashed the process. Every
subsequent FCM wake re-crashed until the rolling 24h window reset,
producing a crash loop for affected users.
Keep `foregroundServiceType=dataSync` — masking the cap via specialUse
would hide a real signal. Instead, catch the exception, post a
user-visible HIGH-importance notification on a new `rouse_fgs_limit`
channel explaining the situation, and call `stopSelf()`. No retry is
scheduled: the next FCM wake naturally re-attempts `startForeground`,
and once the rolling window gives budget back, the service starts
normally.
A fixed notification id is used so repeated exhausted wakes update the
same notification rather than spamming the shade.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replaces the TODO stub that always returned null, unblocking the
expired-cert renewal branch of CertRenewalWorker.
The provider now bridges FirebaseAuth (fresh ID token via getIdToken)
and the Android Keystore (SHA256withECDSA signature over the raw DER
bytes of the renewal CSR) using the P-256 key minted by
FileCertificateStore under the 'rouse_device_key' alias. Returning null
on any transient failure (no signed-in user, Keystore locked, empty
token) keeps the worker retry-safe.
To make the signature actually verify at the relay, this plumbs the CSR
DER through to the provider. CsrResult now carries csrDer alongside the
PEM; CertRenewalFlow.renewWithFirebase grows an overload that receives
a FirebaseRenewalCredentialsProvider, generates the CSR first, and then
asks the provider to sign those exact bytes before submitting to the
relay. The previous (token, signature) overload is retained as a
delegator for the existing tunnel tests.
The old RenewalAuthProvider interface took no arguments and therefore
could not know which CSR to sign. It now receives the csrDer bytes,
which required touching CertRenewer / CertRenewalFlowRenewer so the
worker invokes the provider through the renewer (flow owns the CSR
lifecycle). A new RenewalResult.FirebaseAuthUnavailable preserves the
EXPIRED_NO_AUTH outcome that signalled 'no creds, retry later'.
DeviceKeystoreSigner is a thin interface; AndroidKeystoreSigner is the
production Keystore-backed impl. The provider takes a FirebaseIdTokenSource
seam as well so unit tests can exercise the decision logic without
Robolectric-initialising Firebase. Robolectric is used only to no-op
android.util.Log; no real Keystore or Firebase is exercised by the
provider tests.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Covers the three RenewalResult branches that lacked direct tests:
- RelayError returns retry, records RELAY_ERROR (non-terminal), does
not invoke the rate-limit reschedule callback.
- KeyGenerationFailed returns success and records KEY_GEN_FAILED so
downstream banners can surface the terminal failure.
- CnMismatch returns success and records CN_MISMATCH for the same
reason.
Adds a small readLastOutcome() helper that reads CertRenewalWorker's
PREFS_NAME/KEY_LAST_OUTCOME via the Robolectric-provided application
context, matching what MainDashboard consumes.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
IdleTimeoutManager previously required at least one ACTIVE transition before
arming the idle timer, so an FCM wake that never produced a client stream
kept the foreground service alive indefinitely (reported 27+ min CONNECTED
with no streams).
Drop the `hasBeenActive` gate: every entry into CONNECTED arms a 5 min timer,
every ACTIVE cancels it. Preserves the existing stream-resumes-timer
behavior and adds a cap on pre-first-stream waits.
Also adds wake-cycle observability so the relay-side spurious-wake theory
can be confirmed on-device:
- SpuriousWakeRecorder interface (kept in :work for testability)
- SharedPreferencesSpuriousWakeRecorder persists lifetime total + up to 64
recent spurious timestamps (plain-text CSV, parseable in JVM unit tests)
- Settings diagnostics row shows "Background wakes without client (24h):
N / total: M" once at least one spurious wake has been seen
- Dashboard SpuriousWakeBanner (low-severity, surface container) surfaces
when the rolling-24h count exceeds 10; tapping navigates to Settings
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
SecurityCheckWorker declares `lateinit var` fields for its security-check
sources, expecting a WorkerFactory to populate them. Without a custom factory
WorkManager only calls the no-arg `(Context, WorkerParameters)` constructor,
leaving those fields uninitialized, so `doWork()` throws
`UninitializedPropertyAccessException` on the first scheduled run. This
silently zeroed out the production value of #83 and #84.
Changes:
- New `KoinWorkerFactory` in :work. Dispatches on class name, pulls
collaborators from the root Koin instance, and returns null for unknown
workers so WorkManager falls back to its default factory for anything we
didn't explicitly handle.
- `RouseApplication` now implements `Configuration.Provider` and supplies a
configuration that wires the factory.
- AndroidManifest disables WorkManager's default startup initializer so our
Configuration.Provider is the sole source of truth — otherwise WorkManager
eagerly initializes with its default WorkerFactory before the provider is
consulted.
Tests:
- `KoinWorkerFactoryTest` exercises the factory directly: builds workers for
both SecurityCheckWorker and CertRenewalWorker, verifies injection, and
confirms null return for unknown class names.
- `WorkManagerFactoryIntegrationTest` runs SecurityCheckWorker end-to-end via
`WorkManagerTestInitHelper` configured with `KoinWorkerFactory`. The prefs
assertion only passes if the lateinit fields were populated before
`doWork()` ran.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Observes tunnel state via new SessionSummaryPoster rooted in
TunnelForegroundService. On ACTIVE it captures the current audit log
high-watermark id; on DISCONNECTED it queries entries created since and
dispatches by PostSessionMode:
- SUMMARY: posts one low-importance notification with counts per
integration (e.g. "7 tool calls across 3 integrations" / "health 4,
usage 2, notifications 1"). Tap-through carries start/end timestamps
as intent extras for audit-history filtering.
- SUPPRESS: no-op.
- EACH_USAGE: deferred — per-entry posting requires wrapping
RoomAuditListener or tail-observing the DAO, which is more invasive
than this initial wiring; TODO noted in SessionSummaryPoster.
Adds a new SESSION_SUMMARY channel (low importance, no heads-up) and
two AuditDao queries: latestId() and queryCreatedAfter(sinceId).
Observer is rooted in TunnelForegroundService.lifecycleScope alongside
the existing wakelock / idle-timeout observers so it follows the
natural session-observation lifecycle.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The existing CertRenewalWorker was a stub against a local CertRenewalStore
interface that nothing implemented, so certs silently aged out at their
~90 day ACME lifetime. Rewrite the worker to drive the real CertRenewalFlow
from :core:tunnel and register it as a daily PeriodicWorkRequest from
RouseApplication.onCreate().
Decision logic:
- No cert → skip.
- Cert expires in more than DEFAULT_RENEWAL_WINDOW_DAYS (21) → skip.
- Cert inside window, still valid → renewWithMtls(BASE_DOMAIN).
- Cert already expired → renewWithFirebase(...) via a RenewalAuthProvider
seam. Production binding (FirebaseRenewalAuthProvider) returns null today
and logs a follow-up TODO — completing it needs FirebaseAuth.getIdToken()
plus an Android Keystore SHA256withECDSA signature over the CSR DER,
which is out of scope for this issue. The worker reacts by returning
Result.retry() so the next periodic tick picks it up once that provider
ships.
On RenewalResult.RateLimited the worker calls a rescheduleWithDelay hook
(default implementation enqueues a one-time CertRenewalWorker via
CertRenewalScheduler.enqueueDelayed) and returns Result.retry(), matching
the relay's retry_after semantics.
Also: passes BuildConfig.BASE_DOMAIN explicitly into CertRenewalFlow at
the Koin binding site, closing the CertRenewalFlow half of #80 without
touching the call sites in existing tests (constructor default is kept
for test ergonomics but production never relies on it now).
Tests (Robolectric, TestListenableWorkerBuilder):
- cert valid & far from expiry → skip, no renew call
- cert inside window → mTLS renew with correct baseDomain
- cert expired + auth credentials available → Firebase renew with token/sig
- cert expired + no auth credentials → Result.retry()
- RateLimited(90s) → Result.retry() + reschedule callback fires with 90
- no cert → no-op
- network error → Result.retry() without reschedule
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Adds Koin bindings so CtLogMonitor runs alongside SelfCertVerifier from
SecurityCheckWorker, populating KEY_CT_LOG_RESULT and triggering the same
alert gate used by McpSession.
- Add HttpCtLogFetcher production implementation (ktor -> crt.sh)
- Add StoredCertVerifierSource and CtLogMonitorSource adapters that satisfy
SecurityCheckSource using the store's leaf cert / parameterless CT check
- Bind CtLogMonitor, CtLogFetcher, SelfCertVerifier, and both sources in
AppModule, named "selfCert" and "ctLog" for later WorkerFactory wiring
- Pass BuildConfig.BASE_DOMAIN explicitly; remove the "rousecontext.com"
default on CtLogMonitor (closes the CtLogMonitor half of #80)
- Add SecurityCheckWorker test that a CT log Alert populates
KEY_CT_LOG_RESULT="alert" and satisfies the self==alert || ct==alert gate
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The app was writing FCM tokens directly to Firestore via the client SDK,
but security rules block client writes. The relay already handles FCM
token delivery via the tunnel WebSocket using its service account.
Remove firebase-firestore dependency from :app and :work modules,
simplify FcmTokenRegistrar to log-only (token delivery happens via tunnel),
and update Koin wiring to match the no-arg constructor.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Move ic_stat_rouse drawable from :notifications to :api so that
:outreach can reference it without depending on :notifications.
Replace :notifications dependency with :api in outreach/build.gradle.kts.
Add :api dependency to :work for the same icon reference.
Update all R.drawable.ic_stat_rouse references to use ApiR import alias
in notifications module sources (required by nonTransitiveRClass=true).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Changed periodic interval from 4h to 12h (configurable in Settings)
- Added opportunistic check in TunnelForegroundService when last check >6h stale
- Added security check interval setting (6h/12h/24h) in Settings screen
- SettingsViewModel reads/writes interval preference
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
ConnectionStateMachine.transition() threw IllegalStateException on
invalid transitions, which killed all active streams when a reconnect
was triggered while the tunnel was ACTIVE. Changed to return false and
log a warning instead of throwing.
Also guard TunnelClientImpl.connect() to no-op when already connected,
and skip reconnect in TunnelForegroundService when tunnel is ACTIVE
with live streams.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
FCM wake failed to restart tunnel after idle timeout because
intentionalDisconnect and timeoutFired persisted across service
restarts (Koin singletons). Now onStartCommand resets both flags.
Also fix ktlint: rename underscore-prefixed StateFlow backing fields,
format SettingsViewModelTest constructor call.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1. Replace all em-dashes with hyphens or rewording across app/, core/, notifications/, work/, outreach/
2. Integration picker: remove DISABLED state, show "Set up" for all, make full row clickable
3. IntegrationEnabledScreen: change "Done" to "Finish Later"
4. Remove AddClientScreen and AddClientViewModel, replace "Add Client" card with "Add Integration"
5. Add appBarColors() using ExtendedColors.topBarContainer, apply to all TopAppBars
6. Outreach: use ic_stat_rouse from :notifications instead of android ic_dialog_info
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Enable core library desugaring for java.time and java.util.Base64 usage
in app, core:mcp, health, and notifications modules
- Guard NotificationChannel creation (API 26+) in NotificationChannels
and OutreachMcpProvider
- Guard FOREGROUND_SERVICE_TYPE_DATA_SYNC (API 29+) in
TunnelForegroundService, fall back to type-less startForeground
- Use ContextCompat.startForegroundService() in FcmReceiver and
TestWakeReceiver for pre-API-26 compatibility
- Guard Health Connect availability check for API 28+ in
HealthConnectIntegration
- Add tools:overrideLibrary for Health Connect in health manifest
- Pin Robolectric to SDK 33 in outreach, work, and notifications test
resources to match app module
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Channels were only created in the foreground service, so auth request
notifications posted before the service started would silently fail.
Call NotificationChannels.createAll() in RouseApplication.onCreate()
to ensure channels exist early.
Replace all system drawable icons (ic_dialog_alert, ic_menu_manage)
with a dedicated ic_stat_rouse vector drawable in the notifications
module so every notification uses the app's own branding.
Extract postAuthRequestNotification from a private AppModule function
into a testable AuthRequestNotifier class in :notifications, wired
through Koin.
Add Robolectric tests for NotificationChannels, NotificationAdapter,
AuthRequestNotifier, and AuthApprovalReceiver.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Observer coroutines (state, sessions, wakelock, idle timeout) were
launched in onStartCommand, which runs on every wake broadcast. Duplicate
collectors caused conflicting reconnect attempts: the state observer saw
DISCONNECTED during a refresh disconnect and raced with the explicit
reconnect. Move observers to onCreate (runs once) and mark refresh
disconnects as intentional so the state observer does not trigger
spurious reconnect loops.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Skip FCM wake (tunnel service start) and cert renewal when no
integrations are enabled. This avoids wasting the 50/week ACME cert
quota and unnecessary foreground service starts when the device has
nothing to serve.
Checks are in FcmReceiver (primary gate) and TunnelForegroundService
onStartCommand (defensive fallback).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The relay accepts {"type":"fcm_token","token":"..."} as a text WebSocket
message to register a device's FCM token. This adds:
- sendText() to WebSocketHandle for text frame support
- sendFcmToken() to TunnelClient interface and TunnelClientImpl
- FCM token sending in TunnelForegroundService after connect and reconnect
- Tests verifying token JSON is sent and no-op behavior before connect
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The idle timer previously started on any CONNECTED transition, including
initial connect --- disconnecting the tunnel before any client had a chance
to arrive. Now it only starts after a stream has been ACTIVE and returns
to CONNECTED (i.e. all clients left).
Also adds exponential-backoff reconnect (1s-30s, give up after 5min) for
unexpected disconnects, 15-second OkHttp WebSocket ping interval for dead
connection detection, and restores the 5-minute idle timeout from the
testing value of 30 minutes.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- HttpTransport: add handleNotification() for fire-and-forget JSON-RPC
messages (no response expected). Without this, notifications/initialized
hung forever waiting for a response that never came.
- McpRouting: detect JSON-RPC notifications (no "id" field) and return
202 Accepted immediately instead of dispatching through handleRequest.
Also add 5s timeout on receiveText() for /register to prevent hangs.
- TlsInputStream: same multi-record fix as TlsAcceptor handshake —
check netIn.position() before reading from stream. HTTP headers and
body arriving in the same mux DATA frame caused the body read to block.
- TunnelClientImpl: catch ClosedSendChannelException in onBinaryMessage
to prevent crash when WebSocket frames arrive after disconnect.
- TunnelForegroundService: handle double-wake by disconnecting stale
connection before reconnecting.
- Increase idle timeout to 30 minutes for testing (was 5 minutes, which
caused the connection to drop right when Claude tried tool calls).
Verified: Claude connected via OAuth, called echo and device_info tools
successfully through the full relay → device → MCP pipeline.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
When the relay sends an OPEN frame (AI client connected), the device now:
1. Performs TLS server-side accept using the ACME cert/key
2. Bridges the plaintext I/O to the local Ktor MCP HTTP server
3. Routes MCP JSON-RPC requests to the registered integration tools
Key changes:
- SessionHandler interface in :work for the foreground service to dispatch streams
- McpSessionBridge in :app implements TLS accept + TCP bridge to MCP
- TlsAcceptor.fromPem() factory for PEM-based cert/key loading
- McpSession.resolvePort() to get the ephemeral port after start
- Koin wiring for McpSession singleton and SessionHandler
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Three root causes prevented the wake flow test from passing:
1. TunnelForegroundService and FcmReceiver were not declared in the work
module's AndroidManifest.xml, so Android couldn't find or start them.
2. ADB broadcasts to FirebaseInstanceIdReceiver require the C2DM sender
permission, which the ADB shell (uid 2000) lacks. Added a debug-only
TestWakeReceiver that starts TunnelForegroundService without requiring
any sender permission.
3. The relay URL was hardcoded to wss:// but the test relay runs without
TLS. Added configurable relay.scheme build property (defaults to wss,
tests pass ws). The relay now injects a test DeviceIdentity when running
without TLS so /ws accepts connections. Added cleartext network security
config for debug builds.
Also fixed: TunnelForegroundService now catches connection errors instead
of crashing, and installApk() auto-uninstalls on signature mismatch.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The service had lateinit var fields that were never set, causing a crash
on FCM wake. Convert to Koin by inject() delegation and register
TunnelClient, WakelockManager, IdleTimeoutManager, and relayUrl in AppModule.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Wire SelfCertVerifier and CtLogMonitor into a WorkManager periodic task
that runs every 4 hours. Results are persisted to SharedPreferences for
UI consumption, and alerts/warnings trigger appropriate notifications.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Security: the device no longer reads relay host/port from the FCM message
payload, preventing a spoofed message from redirecting connections. The relay
URL is baked into the APK via BuildConfig at compile time.
- FCM payload now only contains {"type": "wake"} or {"type": "renew"}
- Relay URL configurable via Gradle properties: -Prelay.host=x -Prelay.port=y
- Defaults to relay.rousecontext.com:443 if no property set
- TunnelForegroundService.relayUrl injected by :app module
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add the Android service lifecycle layer that bridges FCM wakeups to
TunnelClient, manages wakelocks based on tunnel state, enforces idle
timeouts, and schedules certificate renewal via WorkManager.
Components:
- FcmDispatch/FcmReceiver: route FCM messages to service start or cert renewal
- WakelockManager: acquire during CONNECTING/ACTIVE, release otherwise
- IdleTimeoutManager: disconnect after idle period, respects battery exemption
- CertRenewalWorker: WorkManager worker, renews certs expiring within 14 days
- TunnelForegroundService: lifecycle service wiring it all together
21 unit tests covering all four test scenarios from the task spec.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>