Skip to content

feat(diagnostics): client diagnostics for Android and Android TV — capture, consent, and upload - #95

Closed
Quick104 wants to merge 1 commit into
mainfrom
feat/client-diagnostics-android
Closed

Quick104 wants to merge 1 commit into
mainfrom
feat/client-diagnostics-android

Conversation

@Quick104

@Quick104 Quick104 commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Implements the Android side of the cross-repo client-diagnostics pipeline (spec: silo-server/docs/design/2026-07-19-client-diagnostics.md, rollout slices 2–4), the counterpart to the Apple client's feat/client-diagnostics-apple (silo-apple PR #96). The server side (status + hardened ingest endpoints, schemas, admin API, retention) is already live on silo-server main.

What this adds

Capture

  • SiloLog safe-logging facade: always forwards to logcat unchanged, and feeds a redacted, pre-rendered JSONL line to an always-on lock-free in-memory ring (~4000 entries), to rotating debug segment files (5×2 MB, only while debug logging / manual capture is on), and to a persistent breadcrumb journal (2×128 KiB) for next-launch reports.
  • Crash capture: an UncaughtExceptionHandler writes one bounded (≤512 KiB) atomic marker on the dying thread — pre-rendered @Volatile context spliced verbatim, no locks/coroutines/JSON framework/probes — then chains to the prior handler. Next-launch assembly is the mandatory redaction choke point before anything becomes a pending report. ApplicationExitInfo (API 30+) supplies ANR and native-crash reports (bounded trace read; tombstones kept as opaque bytes); JVM REASON_CRASH records are deliberately skipped since the UEH already captured them with better evidence.
  • Device snapshot (device.json) from the existing playback probes plus new accessors: display mode inventory, AudioManager output/encoding enumeration, and a read-only export on PassthroughSuppressionRegistry. A pre-failure snapshot is kept warm for the crash marker.

Consent (binding-scoped: server_instance_id + account)

  • Ask / Always / Never with notice-version demotion applied at status refresh and again at upload time (frozen evidence, refreshed consent framing).
  • Child-profile fail-closed gate with a generation counter against stale async results, re-evaluated on every profile switch via ProfileRepository.profileSwitches.
  • Pending reports: 3-per-binding cap (immediately-evicted captures are not fingerprint-marked), visible 7-day expiry, global seen-fingerprint set, 24h per-(binding, fingerprint) auto-upload throttle.
  • Purge cascade on Never, sign-out (event-driven via AuthRepository.logout + a lazy token-loss backstop in the coordinator), and server removal — including debug segments and breadcrumbs.

Upload

  • Hand-rolled plain-USTAR tar writer + GZIPOutputStream (the server rejects PAX/GNU); part-1 manifest is produced by splicing the measured archive object into the embedded manifest bytes, so embedded == part-1 minus archive holds by construction; exact current-token scrub runs on every textual entry before sizing.
  • In-process orchestration mapping the server's full error vocabulary: permanent states for unsupported_schema/too_large, delete on invalid_bundle/archive_mismatch, demote-to-Ask on stale_consent, and persisted Retry-After backoff on 429/503 (a deliberate improvement over the Apple client, which ignores the header). Identity is re-checked after the slow bundle build so a mid-build account/profile switch never misposts.

UI (phone + TV, shared ViewModel)

  • State-aware Diagnostics settings (Available / Disabled by server / Storage unavailable / Offline), debug-logging toggle, crash-reports picker with account-scoped confirmation copy ("Turn Off and Delete" for Never), Start → Stop & Review manual capture plus one-shot Send Now with the ring-only warning, pending list with expiry and per-report Send/Delete, sent short-id history.
  • Crash prompt on next foreground: aggregated, type-honest copy, View Report summary before sending; phone renders a non-dismissible dialog, TV a full-screen prompt with default focus on Don't Send and D-pad exit trapping.

Deliberate deviations from the Apple client

  1. Retry-After is parsed and honored (Apple has no parsing at all).
  2. The attr registry is an exact transcription of the server's contract.go registry, enforced by a parity unit test — Apple's client registry drifted and silently loses attributes server-side.
  3. Lock-free ring instead of a ported mutex ring (os_unfair_lock has no safe JVM equivalent for the crash path); cleared by instance swap.

Testing

  • 82 new unit tests: golden leak fixtures for the redaction pipeline, a strict USTAR reader verifying wire compatibility byte-for-byte (magic/version/checksum/order/sha256/uncompressed accounting, embedded-manifest equality, redaction-before-sizing), store lifecycle rules (cap-eviction/fingerprint ordering, expiry, throttle, Retry-After persistence), the registry parity test, and contract fixtures vendored byte-identical from silo-server (all valid fixtures decode + validate; all invalid fixtures rejected).
  • Full builds green: :androidApp:assembleDebug, :androidTvApp:assembleDebug, and all four modules' unit-test suites.
  • Three adversarial review passes (correctness vs. the server's Go validation, privacy-contract audit of every log call site and purge path, simplification) ran before this PR; the two convergent findings — incomplete sign-out purge and unwired profile-switch/sign-out hooks — are fixed in this diff.

Feature remains dark in practice until a server enables diagnostics.uploads_enabled; nothing uploads without the documented consent paths.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added end-to-end client diagnostics across Android phone and TV, including a Settings → Diagnostics experience, consent prompt UX, and manual capture/report sending.
    • Collects crash/ANR, playback, network, device, lifecycle, and breadcrumb context; stores pending reports locally with retention and retry behavior.
    • Improves diagnostics logging with redaction plus ring/file/breadcrumb journaling, and enables bundle creation/upload via the diagnostics API.
  • Tests
    • Added contract and validation tests for diagnostics logs, manifests, bundle wire compatibility, consent storage, crash markers, redaction, and upload/error handling.

…pture, consent, and upload

Implements rollout slices 2-4 of the cross-repo client-diagnostics spec
(silo-server docs/design/2026-07-19-client-diagnostics.md), mirroring the
Apple client (PR #96) with Android-native mechanisms:

- Wire contract v1 in shared/commonMain: manifest/device/logline models with
  server-parity validation, an attr registry transcribed exactly from the
  server's contract.go (enforced by a parity test), DiagnosticsApi (status +
  strict two-part multipart upload with Retry-After parsing), feature store.
- Safe-logging facade (SiloLog) with collection-time redaction (URL
  normalization, token/JWT/cookie/email scrubbing, typed registered attrs),
  a lock-free always-on ring, debug-mode rotating segment files, and a
  persistent breadcrumb journal for next-launch reports.
- Crash capture: UEH writes one bounded atomic marker on the dying thread
  (pre-rendered context, no locks/JSON/probes); next-launch assembly is the
  mandatory redaction choke point. ApplicationExitInfo supplies ANR + native
  crash (fingerprint-deduped; JVM crashes deliberately left to the UEH).
- Device snapshot from the existing probes plus new accessors (display mode
  inventory, audio output enumeration, passthrough-suppression export).
- Binding-scoped consent (server_instance_id + account): Ask/Always/Never
  with notice-version demotion at refresh AND upload time, child-profile
  fail-closed gating (profile-switch subscription), pending reports with
  3-cap/7-day expiry/global fingerprint set/24h auto-upload throttle, purge
  cascade on Never, sign-out, and server removal (event-driven plus a lazy
  token-loss backstop).
- Plain-USTAR + gzip bundle builder; part-1 manifest is the embedded bytes
  with the archive object spliced in, so embedded == part-1 minus archive by
  construction; exact-token scrub before entry sizing.
- In-process upload orchestration honoring the server's full error
  vocabulary, including persisted Retry-After backoff (an intentional
  improvement over the Apple client).
- Curated log wiring: playback analytics events + ~5s stats timeline,
  Ktor network hook (method/templated path/status/duration only), TV focus
  logging, lifecycle breadcrumbs, recent-playback-session tracker.
- UI on both platforms: state-aware Diagnostics settings (phone screen, TV
  pane), Ask/Always/Never with scoped confirmation copy, Start/Stop-and-
  review manual capture plus one-shot Send Now with ring-only warning,
  pending list with expiry, sent short-id history, and the crash prompt
  (phone dialog; TV full-screen defaulting focus to Don't Send).
- Contract fixtures vendored byte-identical from silo-server; 82 new unit
  tests including leak fixtures, USTAR wire-compat verification, store
  lifecycle rules, and the registry parity test.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds an Android diagnostics platform for phone and TV, including wire models, validation, logging and redaction, crash capture, durable pending reports, upload orchestration, lifecycle integration, and Compose-based diagnostics interfaces.

Changes

Diagnostics platform

Layer / File(s) Summary
Diagnostics contracts and transport
shared/..., android-shared/...
Adds serializable diagnostics models, validation rules, consent and feature-state contracts, network instrumentation, status/report APIs, repositories, and Koin bindings.
Runtime capture and orchestration
android-shared/...
Adds redacted logging, device snapshots, consent and pending-report persistence, crash/exit capture, bundle creation, playback/session tracking, and coordinator lifecycle/upload handling.
Application and phone/TV interfaces
androidApp/..., androidTvApp/...
Wires diagnostics into application startup, account events, navigation, settings, manual capture, pending reports, and crash-consent prompts.
Contract fixtures and tests
android-shared/src/androidUnitTest/...
Adds model, validation, storage, redaction, logging, bundle, crash-marker, and API-path tests with vendored schemas and fixtures.

Estimated code review effort: 5 (Critical) | ~120 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.81% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: client diagnostics support for Android and Android TV, including capture, consent, and upload.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/client-diagnostics-android

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ca8daa4eda

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +13 to +15
interface DiagnosticsAccountEvents {
fun onSignedOut(localServerId: String?)
fun onServerRemoved(localServerId: String)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Refresh diagnostics when switching servers

Because this lifecycle bridge only exposes sign-out and removal, the new wiring never notifies DiagnosticsCoordinator when ServerListViewModel.onSelect/TvServerListViewModel.onSelect switches the active server. In the common foreground case of selecting another saved server, the coordinator's crash context and pending prompt state can remain bound to the previous server until a later diagnostics refresh, so a crash (or stale prompt action) after the switch can be packaged under the wrong server account. Add an active-server-changed event/refresh at the switch point, similar to the immediate profile-switch invalidation.

Useful? React with 👍 / 👎.

Comment on lines +87 to +89
consent = DiagnosticsManifest.Consent(
mode = if (session.consentMode == "always") DiagnosticsConsentMode.ALWAYS else DiagnosticsConsentMode.PROMPT,
noticeVersion = session.noticeVersion,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Drop crash markers captured after Never consent

When the user has selected Never, the crash context still records consentMode = "never", but this line maps every non-always marker back to PROMPT. A crash after opt-out is therefore saved as a pending crash report and can surface/send later if the user changes settings, despite the Never flow promising to turn off and delete crash reports. Skip markers with consentMode == "never" (and mirror that for exit-info captures) or clear the crash context when Never is selected.

Useful? React with 👍 / 👎.

accountUserId = binding.accountUserId,
// Attribution only for confirmed non-child profiles; the server
// rejects child-profile attribution outright.
profileId = resolvedProfile?.takeIf { !it.isChild }?.id,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Disarm crash capture for child profiles

When the active profile is a child, this only omits profileId but still publishes a valid server/account crash session. The UI and uploader are gated while the child profile is active, but the marker assembler persists that crash with no child marker, so switching later to an adult profile can expose and send a report captured during the child session. Clear the crash context (or otherwise mark and drop the marker) whenever the resolved profile is a child.

Useful? React with 👍 / 👎.

Comment on lines +66 to +68
fun purge() {
closeStreamQuietly()
segmentFiles().forEach { it.delete() }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Drain queued diagnostics logs before purging

This purge deletes the segment files but leaves the file logger's channel and writer job intact. If debug logging is running during sign-out, server removal, or Never-mode purge, already queued lines from the departing account can be written after the files are deleted and then included in a later user's manual diagnostics report. Stop/drain the writer and clear pending channel contents as part of purge before allowing logging to resume.

Useful? React with 👍 / 👎.

Comment on lines +271 to +273
captureActive = false
applyDebugLogging(settingsStore.debugLogging.value)
val review = buildManualReport()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve queued logs when stopping manual capture

In the common case where persistent debug logging is off, stopManualCaptureAndBuildReview() turns off the file logger before building the report. DiagnosticsFileLogger.stop() cancels its writer coroutine rather than flushing the channel, so the last log lines generated while reproducing the issue can be dropped exactly when the user presses Stop & Review. Build after an explicit flush/drain, or keep the logger alive until the report has read the captured segments.

Useful? React with 👍 / 👎.

Comment on lines +607 to +609
publishCrashContext(binding, status, profile)
_state.value = _state.value.copy(serverName = serverHost)
rebuildState(binding, availability, status)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reset evidence when diagnostics binding changes

After resolving a new server/account binding, this publishes it without clearing the device-wide evidence stores. Since manual reports read the current ring/file segments and crash reports can attach breadcrumbs from the app run, logs collected under the previous binding can be uploaded to the newly active server account after a server/profile change. Compare the previous binding with the resolved one and reset/purge the ring, segment logger, and breadcrumb journal when it changes.

Useful? React with 👍 / 👎.

Comment on lines +572 to +583
if (accountUserId == null) {
// Offline (or /me failed): fall back to the last-known snapshot so
// crash capture can still bind. Transient failures only — a signed-
// out account never reaches here (token check above).
val cached = consentStore.cachedStatus(localServerId)
if (cached != null) {
status = status ?: cached.status
if (availability == DiagnosticsAvailability.UNKNOWN) {
availability = DiagnosticsAvailability.OFFLINE
}
accountUserId = cached.accountUserId
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Re-check auth before using cached diagnostics binding

This fallback also runs after /me returns an auth error or after the auth plugin clears tokens during a failed refresh, because hasToken was captured before the request. In that case the coordinator can resurrect the last cached account ID and republish a crash context for a signed-out account, so a crash on the login screen can still be packaged for the old user. Only use the cached status for true offline/network failures after re-checking that credentials are still present, and clear the cached account snapshot on sign-out.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (2)
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsCoordinator.kt (1)

404-413: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Use MutableStateFlow.update {} for the isUploading transitions.

_state.value = _state.value.copy(...) is a non-atomic read-modify-write. With several entry points (onForeground, onProfileChanged, refreshNow, auto-uploads) launching on the shared IO scope concurrently, a rebuild interleaving here can drop the isUploading flag. update {} makes the transition atomic.

♻️ Suggested change
-        try {
-            _state.value = _state.value.copy(isUploading = true)
-            doUpload(report)
-        } finally {
-            inFlightReportIds.remove(report.id)
-            _state.value = _state.value.copy(isUploading = false)
-            rebuildState()
-        }
+        try {
+            _state.update { it.copy(isUploading = true) }
+            doUpload(report)
+        } finally {
+            inFlightReportIds.remove(report.id)
+            _state.update { it.copy(isUploading = false) }
+            rebuildState()
+        }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsCoordinator.kt`
around lines 404 - 413, In the upload flow surrounding doUpload, replace both
non-atomic _state.value copy assignments for isUploading with atomic
MutableStateFlow.update { } transitions. Preserve the existing true transition
before doUpload, false transition in finally, and all surrounding in-flight ID
cleanup and rebuildState behavior.
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/ExitInfoCollector.kt (1)

209-215: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Three identical lenient-Json configs duplicated across crash files.

Json { ignoreUnknownKeys = true; isLenient = true } is independently defined in three places with identical settings, risking silent divergence if one is tuned later without updating the others.

  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/ExitInfoCollector.kt#L209-L215: extract a shared internal val DiagnosticsLenientJson = Json { ignoreUnknownKeys = true; isLenient = true } and reuse it here.
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/CrashMarker.kt#L44-L49: reuse the shared instance instead of the local json companion val.
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/CrashMarkerAssembler.kt#L159-L161: reuse the shared instance instead of the local lenientJson companion val.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/ExitInfoCollector.kt`
around lines 209 - 215, The three crash components duplicate the same lenient
Json configuration. In
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/ExitInfoCollector.kt:209-215,
extract an internal shared DiagnosticsLenientJson instance; in
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/CrashMarker.kt:44-49
and
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/CrashMarkerAssembler.kt:159-161,
remove the local json/lenientJson values and reuse DiagnosticsLenientJson.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/bundle/DiagnosticsBundleBuilder.kt`:
- Around line 152-161: Update scrub() to decode bytes using strict UTF-8
validation, such as decodeToString with throwOnInvalidSequence enabled or a
CharsetDecoder configured to REPORT malformed input. Preserve the
REDACTION_FAILED_PLACEHOLDER fallback when decoding fails, while retaining the
existing token replacement behavior for valid UTF-8.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/consent/DiagnosticsProfileGate.kt`:
- Around line 35-44: The generation check and eligibleNonChild assignment in
reevaluate must be atomic so invalidate() cannot race between them. Protect both
operations with the existing synchronization mechanism, or replace them with a
shared-state CAS that only publishes when gen still matches generation; preserve
dropping superseded reevaluation results.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsViewModel.kt`:
- Around line 107-117: Update acceptPrompt in DiagnosticsViewModel so Discarded
and Skipped outcomes preserve the same user-facing feedback provided by
upload(), rather than falling through to null or an unsafe Kept cast. Reuse the
existing outcome-to-message handling and retain the Uploaded reference-ID
message and Kept behavior.
- Around line 39-121: Guard every coordinator call in the affected
DiagnosticsViewModel methods—setConsentChoice, setDebugLogging,
stopCaptureAndReview, buildSendNowReview, upload, deletePending, acceptPrompt,
and declinePrompt—so exceptions are caught within each viewModelScope coroutine
instead of escaping to the uncaught-exception handler. Preserve successful state
updates and surface failures through the existing _notice mechanism, while
ensuring _busy is reset on all paths in stopCaptureAndReview,
buildSendNowReview, and upload.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/DiagnosticsFileLogger.kt`:
- Around line 39-101: Coordinate writer-owned file state in
DiagnosticsFileLogger.kt (lines 39-101): guard stop(), purge(), writeLine(),
openStreamIfNeeded(), and rotate() with a shared lock, or route control
operations through the writer channel so close/delete cannot race an in-flight
write. In BreadcrumbJournal.kt (lines 24-142), update purge() to enqueue a
control message processed by the writer coroutine, reusing the existing
CLOSE_SENTINEL pattern so deletion occurs after pending writes quiesce.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/LogRing.kt`:
- Around line 54-62: Update the snapshot loop in LogRing’s sequence/data read
block to re-read slotSeq after loading slotData. Add the entry only when the
initial and final sequence reads both equal seq, preventing overwritten data
from being returned under an older sequence.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/PlaybackDiagnosticsLogger.kt`:
- Around line 43-55: Add an exception guard around the per-event processing in
the eventsJob launched by the diagnostics logger, covering reducePlayerStats and
logEvent so malformed events are dropped without terminating collection or the
app. Keep events.collect active for subsequent events and preserve the existing
stats update and logging behavior for successful events.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/diagnostics/CrashPromptDialog.kt`:
- Around line 50-118: Gate the primary AlertDialog rendering on !confirmAlways
so it is hidden while the “Always Send” confirmation dialog is displayed. Keep
the existing confirmAlways state transitions and confirmation dialog behavior
unchanged.

---

Nitpick comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/ExitInfoCollector.kt`:
- Around line 209-215: The three crash components duplicate the same lenient
Json configuration. In
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/ExitInfoCollector.kt:209-215,
extract an internal shared DiagnosticsLenientJson instance; in
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/CrashMarker.kt:44-49
and
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/CrashMarkerAssembler.kt:159-161,
remove the local json/lenientJson values and reuse DiagnosticsLenientJson.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsCoordinator.kt`:
- Around line 404-413: In the upload flow surrounding doUpload, replace both
non-atomic _state.value copy assignments for isUploading with atomic
MutableStateFlow.update { } transitions. Preserve the existing true transition
before doUpload, false transition in finally, and all surrounding in-flight ID
cleanup and rebuildState behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3fb15196-f3a9-44ad-84c1-d2036e8dfee8

📥 Commits

Reviewing files that changed from the base of the PR and between 91f7125 and ca8daa4.

📒 Files selected for processing (102)
  • android-shared/build.gradle.kts
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/di/DiagnosticsModule.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/CrashContextCache.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DeviceSnapshotCollector.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsAppStarter.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsCoordinator.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsHashing.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsIo.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsViewModel.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/PlaybackDiagnosticsLogger.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/SiloLogNetworkDiagnosticsHook.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/bundle/DiagnosticsBundleBuilder.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/bundle/UstarTarWriter.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/consent/DiagnosticsBinding.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/consent/DiagnosticsConsentStore.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/consent/DiagnosticsProfileGate.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/consent/DiagnosticsSettingsStore.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/consent/PendingReportStore.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/consent/RecentSessionTracker.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/CrashCapture.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/CrashMarker.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/CrashMarkerAssembler.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/crash/ExitInfoCollector.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/BreadcrumbJournal.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/DiagRedactor.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/DiagnosticsFileLogger.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/LogRing.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/RenderedLogLine.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/SiloLog.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/UrlNormalizer.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/DisplayHdrProbe.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackSessionManager.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/audio/PassthroughSuppressionRegistry.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsAttrRegistryTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsErrorCodeTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsManifestFixtureTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsManifestInvalidFixtureTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/TemplateApiPathTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/TestDrafts.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/TestResources.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/bundle/DiagnosticsBundleBuilderTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/consent/DiagnosticsConsentStoreTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/consent/DiagnosticsProfileGateTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/consent/PendingReportStoreTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/crash/CrashMarkerTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/logging/DiagRedactorTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/logging/LogRingTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/logging/RenderedLogLineTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/logging/UrlNormalizerTest.kt
  • android-shared/src/androidUnitTest/resources/diagnostics/README.md
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/attr-registry.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/device.schema.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/invalid/archive-entry-outside-allowlist.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/invalid/bad-schema-version.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/invalid/missing-consent.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/invalid/platform-macos-reserved.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/invalid/stack-excerpt-over-8kib.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/invalid/unknown-report-type.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/valid/android-manual-no-profile.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/valid/android-manual.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/valid/android-tv-crash-ueh.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/valid/device.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/valid/ios-hang-metrickit.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/valid/loglines.jsonl
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/fixtures/valid/tvos-abnormal-exit.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/logline.schema.json
  • android-shared/src/androidUnitTest/resources/diagnostics/v1/manifest.schema.json
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/SiloApplication.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/AppNavigation.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/Routes.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/diagnostics/CrashPromptDialog.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/diagnostics/DiagnosticsScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/servers/ServerListViewModel.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/SiloTvApplication.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/navigation/TvAppNavigation.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/diagnostics/TvCrashPromptScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/servers/TvServerListViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvDiagnosticsPane.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/theme/TvTypographyReadabilityTest.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/di/NetworkModule.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/diagnostics/DiagnosticsAttrRegistry.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/diagnostics/DiagnosticsDeviceSnapshot.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/diagnostics/DiagnosticsEnums.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/diagnostics/DiagnosticsLogLine.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/diagnostics/DiagnosticsManifest.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/diagnostics/DiagnosticsStatus.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/diagnostics/DiagnosticsUpload.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/diagnostics/DiagnosticsValidation.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/feature/DiagnosticsAccountEvents.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/feature/DiagnosticsFeatureStore.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/NetworkDiagnosticsHook.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/NetworkDiagnosticsPlugin.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/SiloHttpClientImpl.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/api/DiagnosticsApi.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/AuthRepository.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/DiagnosticsRepository.kt

Comment on lines +152 to +161
private fun scrub(bytes: ByteArray, tokens: List<String>): ByteArray {
if (tokens.isEmpty() || bytes.isEmpty()) return bytes
val text = runCatching { bytes.toString(Charsets.UTF_8) }.getOrNull()
?: return REDACTION_FAILED_PLACEHOLDER.encodeToByteArray()
var out = text
for (token in tokens) {
out = out.replace(token, "[redacted_token]")
}
return if (out === text) bytes else out.encodeToByteArray()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does Kotlin's String(bytes, Charset) constructor throw on malformed UTF-8 input, or does it always substitute the replacement character?

💡 Result:

When using Kotlin on the JVM, the String(bytes, charset) constructor is an inline call to the corresponding java.lang.String constructor [1]. This Java constructor does not throw an exception when encountering malformed UTF-8 input; instead, it automatically replaces malformed-input and unmappable-character sequences with the charset's default replacement string, which is typically the Unicode replacement character \uFFFD [2][3][4]. If you require control over this behavior—such as throwing an exception when malformed sequences are detected—you should not use the String constructor. Instead, you can use the Kotlin standard library function ByteArray.decodeToString(throwOnInvalidSequence = true) [5][6], or use java.nio.charset.CharsetDecoder directly to configure custom error handling via CodingErrorAction [7][8][9]. The decodeToString extension function explicitly allows you to specify whether to replace invalid sequences with \uFFFD (the default) or to throw a CharacterCodingException if throwOnInvalidSequence is set to true [6].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/bundle/DiagnosticsBundleBuilder.kt'

wc -l "$file"
printf '\n--- outline ---\n'
ast-grep outline "$file" --view expanded || true
printf '\n--- relevant lines ---\n'
sed -n '120,220p' "$file" | cat -n
printf '\n--- search for archive key usage ---\n'
rg -n '"archive"|archive\s*=' android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/bundle -S

Repository: Silo-Server/silo-android

Length of output: 4046


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect related manifest types and the build flow around spliceArchive.
rg -n "class DiagnosticsManifestDraft|data class DiagnosticsManifestDraft|object DiagnosticsManifestDraft|archive" \
  android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics -S

printf '\n--- build() region ---\n'
sed -n '56,140p' android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/bundle/DiagnosticsBundleBuilder.kt | cat -n

Repository: Silo-Server/silo-android

Length of output: 8238


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the manifest model definitions and their serialization annotations.
fd -a 'DiagnosticsManifest*.kt' android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics

Repository: Silo-Server/silo-android

Length of output: 162


scrub() should use strict UTF-8 decoding
String(bytes, Charsets.UTF_8) replaces malformed sequences with \uFFFD instead of throwing, so the REDACTION_FAILED_PLACEHOLDER fallback never fires. If non-UTF8 payloads must be dropped, decode with ByteArray.decodeToString(throwOnInvalidSequence = true) or a CharsetDecoder in REPORT mode.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/bundle/DiagnosticsBundleBuilder.kt`
around lines 152 - 161, Update scrub() to decode bytes using strict UTF-8
validation, such as decodeToString with throwOnInvalidSequence enabled or a
CharsetDecoder configured to REPORT malformed input. Preserve the
REDACTION_FAILED_PLACEHOLDER fallback when decoding fails, while retaining the
existing token replacement behavior for valid UTF-8.

Comment on lines +35 to +44
suspend fun reevaluate(activeProfileId: String?, noProfileIsEligible: Boolean = false) {
val gen = generation.incrementAndGet()
val eligible = if (activeProfileId == null) {
noProfileIsEligible
} else {
resolveIsChild(activeProfileId) == false
}
if (gen != generation.get()) return // superseded meanwhile — drop stale result
eligibleNonChild = eligible
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm reevaluate() and invalidate() can be invoked concurrently (different threads/coroutines).
rg -nP -C3 '\b(reevaluate|invalidate)\s*\(' --type=kotlin

Repository: Silo-Server/silo-android

Length of output: 162


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/consent/DiagnosticsProfileGate.kt'

echo "== outline =="
ast-grep outline "$file" --view expanded || true

echo
echo "== file slice =="
cat -n "$file" | sed -n '1,220p'

echo
echo "== call sites =="
rg -n -C 2 '\b(reevaluate|invalidate)\s*\(' android-shared/src --type kotlin

Repository: Silo-Server/silo-android

Length of output: 12591


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/diagnostics/consent/DiagnosticsProfileGateTest.kt'
cat -n "$file" | sed -n '1,220p'

Repository: Silo-Server/silo-android

Length of output: 3234


Guard the publish with the generation check.
invalidate() can still race this method: a stale reevaluate() may pass the generation check and then overwrite eligibleNonChild after a profile switch. The current test covers a resolver that finishes after invalidate(), not the window between the check and the write. Keep the guard and the write in the same atomic section (lock/CAS or shared state).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/consent/DiagnosticsProfileGate.kt`
around lines 35 - 44, The generation check and eligibleNonChild assignment in
reevaluate must be atomic so invalidate() cannot race between them. Protect both
operations with the existing synchronization mechanism, or replace them with a
shared-state CAS that only publishes when gen still matches generation; preserve
dropping superseded reevaluation results.

Comment on lines +39 to +121
fun refresh() {
viewModelScope.launch { runCatching { coordinator.refreshNow() } }
}

fun setConsentChoice(choice: ConsentChoice) {
viewModelScope.launch { coordinator.setConsentChoice(choice) }
}

fun setDebugLogging(enabled: Boolean) {
viewModelScope.launch { coordinator.setDebugLogging(enabled) }
}

fun startCapture() {
coordinator.startManualCapture()
}

fun stopCaptureAndReview() {
viewModelScope.launch {
_busy.value = true
_manualReview.value = coordinator.stopManualCaptureAndBuildReview()
_busy.value = false
}
}

/** One-shot "Send Diagnostics Now": build + review in one step. */
fun buildSendNowReview() {
viewModelScope.launch {
_busy.value = true
_manualReview.value = coordinator.buildManualReport()
_busy.value = false
if (_manualReview.value == null) {
_notice.value = "Diagnostics can't be captured right now."
}
}
}

fun sendManualReview() {
val review = _manualReview.value ?: return
_manualReview.value = null
upload(review.report)
}

/** Cancel review: the user chose not to send — remove the built report. */
fun cancelManualReview() {
val review = _manualReview.value ?: return
_manualReview.value = null
viewModelScope.launch { coordinator.deletePending(review.report) }
}

fun upload(report: PendingReportStore.PendingReport) {
viewModelScope.launch {
_busy.value = true
_notice.value = when (val outcome = coordinator.uploadPending(report)) {
is DiagnosticsCoordinator.UploadOutcome.Uploaded ->
"Report sent. Reference ID: ${outcome.shortId}"
is DiagnosticsCoordinator.UploadOutcome.Kept -> outcome.userMessage
is DiagnosticsCoordinator.UploadOutcome.Discarded ->
"This report couldn't be packaged and was discarded."
is DiagnosticsCoordinator.UploadOutcome.Skipped -> null
}
_busy.value = false
}
}

fun deletePending(report: PendingReportStore.PendingReport) {
viewModelScope.launch { coordinator.deletePending(report) }
}

fun acceptPrompt(always: Boolean) {
viewModelScope.launch {
val outcomes = coordinator.acceptPrompt(always)
val sent = outcomes.filterIsInstance<DiagnosticsCoordinator.UploadOutcome.Uploaded>()
_notice.value = when {
sent.isNotEmpty() -> "Report sent. Reference ID: ${sent.joinToString { it.shortId }}"
outcomes.isEmpty() -> null
else -> (outcomes.firstOrNull() as? DiagnosticsCoordinator.UploadOutcome.Kept)?.userMessage
}
}
}

fun declinePrompt() {
viewModelScope.launch { coordinator.declinePrompt() }
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Unhandled exceptions in coroutine bodies can crash the app.

Only refresh() (Line 40) wraps its coordinator call in runCatching. Every other viewModelScope.launch block (setConsentChoice, setDebugLogging, stopCaptureAndReview, buildSendNowReview, upload, deletePending, acceptPrompt, declinePrompt) calls into coordinator unguarded. Since viewModelScope uses a SupervisorJob with no installed CoroutineExceptionHandler, an exception thrown by any of these suspend calls (I/O, serialization, etc.) propagates to the default uncaught-exception handler and can crash the process instead of being surfaced as a notice.

🛡️ Example fix pattern for one of the affected functions
 fun upload(report: PendingReportStore.PendingReport) {
     viewModelScope.launch {
         _busy.value = true
-        _notice.value = when (val outcome = coordinator.uploadPending(report)) {
+        _notice.value = runCatching { coordinator.uploadPending(report) }.fold(
+            onSuccess = { outcome -> when (outcome) {
                 is DiagnosticsCoordinator.UploadOutcome.Uploaded ->
                     "Report sent. Reference ID: ${outcome.shortId}"
                 is DiagnosticsCoordinator.UploadOutcome.Kept -> outcome.userMessage
                 is DiagnosticsCoordinator.UploadOutcome.Discarded ->
                     "This report couldn't be packaged and was discarded."
                 is DiagnosticsCoordinator.UploadOutcome.Skipped -> null
-            }
+            } },
+            onFailure = { "Something went wrong while sending the report." },
+        )
         _busy.value = false
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fun refresh() {
viewModelScope.launch { runCatching { coordinator.refreshNow() } }
}
fun setConsentChoice(choice: ConsentChoice) {
viewModelScope.launch { coordinator.setConsentChoice(choice) }
}
fun setDebugLogging(enabled: Boolean) {
viewModelScope.launch { coordinator.setDebugLogging(enabled) }
}
fun startCapture() {
coordinator.startManualCapture()
}
fun stopCaptureAndReview() {
viewModelScope.launch {
_busy.value = true
_manualReview.value = coordinator.stopManualCaptureAndBuildReview()
_busy.value = false
}
}
/** One-shot "Send Diagnostics Now": build + review in one step. */
fun buildSendNowReview() {
viewModelScope.launch {
_busy.value = true
_manualReview.value = coordinator.buildManualReport()
_busy.value = false
if (_manualReview.value == null) {
_notice.value = "Diagnostics can't be captured right now."
}
}
}
fun sendManualReview() {
val review = _manualReview.value ?: return
_manualReview.value = null
upload(review.report)
}
/** Cancel review: the user chose not to send — remove the built report. */
fun cancelManualReview() {
val review = _manualReview.value ?: return
_manualReview.value = null
viewModelScope.launch { coordinator.deletePending(review.report) }
}
fun upload(report: PendingReportStore.PendingReport) {
viewModelScope.launch {
_busy.value = true
_notice.value = when (val outcome = coordinator.uploadPending(report)) {
is DiagnosticsCoordinator.UploadOutcome.Uploaded ->
"Report sent. Reference ID: ${outcome.shortId}"
is DiagnosticsCoordinator.UploadOutcome.Kept -> outcome.userMessage
is DiagnosticsCoordinator.UploadOutcome.Discarded ->
"This report couldn't be packaged and was discarded."
is DiagnosticsCoordinator.UploadOutcome.Skipped -> null
}
_busy.value = false
}
}
fun deletePending(report: PendingReportStore.PendingReport) {
viewModelScope.launch { coordinator.deletePending(report) }
}
fun acceptPrompt(always: Boolean) {
viewModelScope.launch {
val outcomes = coordinator.acceptPrompt(always)
val sent = outcomes.filterIsInstance<DiagnosticsCoordinator.UploadOutcome.Uploaded>()
_notice.value = when {
sent.isNotEmpty() -> "Report sent. Reference ID: ${sent.joinToString { it.shortId }}"
outcomes.isEmpty() -> null
else -> (outcomes.firstOrNull() as? DiagnosticsCoordinator.UploadOutcome.Kept)?.userMessage
}
}
}
fun declinePrompt() {
viewModelScope.launch { coordinator.declinePrompt() }
}
fun refresh() {
viewModelScope.launch { runCatching { coordinator.refreshNow() } }
}
fun setConsentChoice(choice: ConsentChoice) {
viewModelScope.launch { coordinator.setConsentChoice(choice) }
}
fun setDebugLogging(enabled: Boolean) {
viewModelScope.launch { coordinator.setDebugLogging(enabled) }
}
fun startCapture() {
coordinator.startManualCapture()
}
fun stopCaptureAndReview() {
viewModelScope.launch {
_busy.value = true
_manualReview.value = coordinator.stopManualCaptureAndBuildReview()
_busy.value = false
}
}
/** One-shot "Send Diagnostics Now": build + review in one step. */
fun buildSendNowReview() {
viewModelScope.launch {
_busy.value = true
_manualReview.value = coordinator.buildManualReport()
_busy.value = false
if (_manualReview.value == null) {
_notice.value = "Diagnostics can't be captured right now."
}
}
}
fun sendManualReview() {
val review = _manualReview.value ?: return
_manualReview.value = null
upload(review.report)
}
/** Cancel review: the user chose not to send — remove the built report. */
fun cancelManualReview() {
val review = _manualReview.value ?: return
_manualReview.value = null
viewModelScope.launch { coordinator.deletePending(review.report) }
}
fun upload(report: PendingReportStore.PendingReport) {
viewModelScope.launch {
_busy.value = true
_notice.value = runCatching { coordinator.uploadPending(report) }.fold(
onSuccess = { outcome -> when (outcome) {
is DiagnosticsCoordinator.UploadOutcome.Uploaded ->
"Report sent. Reference ID: ${outcome.shortId}"
is DiagnosticsCoordinator.UploadOutcome.Kept -> outcome.userMessage
is DiagnosticsCoordinator.UploadOutcome.Discarded ->
"This report couldn't be packaged and was discarded."
is DiagnosticsCoordinator.UploadOutcome.Skipped -> null
} },
onFailure = { "Something went wrong while sending the report." },
)
_busy.value = false
}
}
fun deletePending(report: PendingReportStore.PendingReport) {
viewModelScope.launch { coordinator.deletePending(report) }
}
fun acceptPrompt(always: Boolean) {
viewModelScope.launch {
val outcomes = coordinator.acceptPrompt(always)
val sent = outcomes.filterIsInstance<DiagnosticsCoordinator.UploadOutcome.Uploaded>()
_notice.value = when {
sent.isNotEmpty() -> "Report sent. Reference ID: ${sent.joinToString { it.shortId }}"
outcomes.isEmpty() -> null
else -> (outcomes.firstOrNull() as? DiagnosticsCoordinator.UploadOutcome.Kept)?.userMessage
}
}
}
fun declinePrompt() {
viewModelScope.launch { coordinator.declinePrompt() }
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsViewModel.kt`
around lines 39 - 121, Guard every coordinator call in the affected
DiagnosticsViewModel methods—setConsentChoice, setDebugLogging,
stopCaptureAndReview, buildSendNowReview, upload, deletePending, acceptPrompt,
and declinePrompt—so exceptions are caught within each viewModelScope coroutine
instead of escaping to the uncaught-exception handler. Preserve successful state
updates and surface failures through the existing _notice mechanism, while
ensuring _busy is reset on all paths in stopCaptureAndReview,
buildSendNowReview, and upload.

Comment on lines +107 to +117
fun acceptPrompt(always: Boolean) {
viewModelScope.launch {
val outcomes = coordinator.acceptPrompt(always)
val sent = outcomes.filterIsInstance<DiagnosticsCoordinator.UploadOutcome.Uploaded>()
_notice.value = when {
sent.isNotEmpty() -> "Report sent. Reference ID: ${sent.joinToString { it.shortId }}"
outcomes.isEmpty() -> null
else -> (outcomes.firstOrNull() as? DiagnosticsCoordinator.UploadOutcome.Kept)?.userMessage
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

acceptPrompt silently drops Discarded/Skipped feedback.

upload() explicitly surfaces a message for Discarded outcomes (Line 95-96), but acceptPrompt's else branch only handles Kept via an unsafe cast (Line 114), so a Discarded or Skipped outcome here silently sets _notice to null — the user gets no feedback that a report failed to package.

💡 Suggested fix
             _notice.value = when {
                 sent.isNotEmpty() -> "Report sent. Reference ID: ${sent.joinToString { it.shortId }}"
                 outcomes.isEmpty() -> null
-                else -> (outcomes.firstOrNull() as? DiagnosticsCoordinator.UploadOutcome.Kept)?.userMessage
+                else -> when (val outcome = outcomes.firstOrNull()) {
+                    is DiagnosticsCoordinator.UploadOutcome.Kept -> outcome.userMessage
+                    is DiagnosticsCoordinator.UploadOutcome.Discarded ->
+                        "This report couldn't be packaged and was discarded."
+                    else -> null
+                }
             }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/DiagnosticsViewModel.kt`
around lines 107 - 117, Update acceptPrompt in DiagnosticsViewModel so Discarded
and Skipped outcomes preserve the same user-facing feedback provided by
upload(), rather than falling through to null or an unsafe Kept cast. Reuse the
existing outcome-to-message handling and retain the Uploaded reference-ID
message and Kept behavior.

Comment on lines +39 to +101
fun start() {
if (running) return
running = true
job = scope.launch { writerLoop() }
}

fun stop() {
running = false
job?.cancel()
job = null
closeStreamQuietly()
}

/** Non-blocking. No-op while stopped (debug logging off). */
fun offer(lineUtf8: ByteArray) {
if (!running) return
if (channel.trySend(lineUtf8).isFailure) dropped.incrementAndGet()
}

fun droppedLines(): Long = dropped.get()

/** Current segments, oldest first. */
fun segmentFiles(): List<File> =
dir.listFiles { f -> f.name.startsWith(SEGMENT_PREFIX) && f.name.endsWith(SEGMENT_SUFFIX) }
?.sortedBy { it.name }
.orEmpty()

fun purge() {
closeStreamQuietly()
segmentFiles().forEach { it.delete() }
}

private suspend fun writerLoop() {
for (line in channel) {
if (!running) continue
runCatching { writeLine(line) }
.onFailure { Log.w(TAG, "segment write failed", it) }
}
}

private fun writeLine(line: ByteArray) {
val out = openStreamIfNeeded() ?: return
out.write(line)
out.write('\n'.code)
out.flush()
activeSize += line.size + 1
if (activeSize >= MAX_SEGMENT_BYTES) rotate()
}

private fun openStreamIfNeeded(): FileOutputStream? {
stream?.let { return it }
dir.mkdirs()
// Resume the newest under-sized segment across runs, else start fresh.
val newest = segmentFiles().lastOrNull()?.takeIf { it.length() < MAX_SEGMENT_BYTES }
val target = newest ?: newSegmentFile()
return runCatching {
FileOutputStream(target, true).also {
stream = it
activeFile = target
activeSize = target.length()
}
}.onFailure { Log.w(TAG, "segment open failed", it) }.getOrNull()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Control methods race with the single-writer coroutine on writer-owned file-handle state.

Both classes use a single-consumer coroutine to own stream/segment-tracking fields, but their stop()/purge() methods reach into that state directly from the caller's thread instead of coordinating through the channel (as BreadcrumbJournal.setEnabled correctly does via CLOSE_SENTINEL). job.cancel() is non-blocking and doesn't preempt a non-suspending writeLine(), so a concurrent closeStreamQuietly()/file-delete can race with an in-flight write.

  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/DiagnosticsFileLogger.kt#L39-L101: guard stop(), purge(), and writeLine()/openStreamIfNeeded()/rotate() with a shared lock (or route stop/purge as channel messages the writer coroutine processes itself, mirroring BreadcrumbJournal's sentinel pattern).
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/BreadcrumbJournal.kt#L24-L142: make purge() send a control message through channel (like the existing CLOSE_SENTINEL for disable) so file deletion happens on the writer coroutine after it has quiesced, rather than racing the writer from the caller thread.
📍 Affects 2 files
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/DiagnosticsFileLogger.kt#L39-L101 (this comment)
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/BreadcrumbJournal.kt#L24-L142
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/DiagnosticsFileLogger.kt`
around lines 39 - 101, Coordinate writer-owned file state in
DiagnosticsFileLogger.kt (lines 39-101): guard stop(), purge(), writeLine(),
openStreamIfNeeded(), and rotate() with a shared lock, or route control
operations through the writer channel so close/delete cannot race an in-flight
write. In BreadcrumbJournal.kt (lines 24-142), update purge() to enqueue a
control message processed by the writer coroutine, reusing the existing
CLOSE_SENTINEL pattern so deletion occurs after pending writes quiesce.

Comment on lines +54 to +62
while (seq < endSeq) {
val idx = (seq % capacity).toInt()
// Seq first, then data: a slot whose seq doesn't match was either
// not yet published or already overwritten — skip, never tear.
if (slotSeq.get(idx) == seq) {
slotData.get(idx)?.let(out::add)
}
seq++
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm LogRing is snapshotted from the crash path while live threads may still append.
rg -nP -C3 '\b(append|snapshot(Newest|Range)?)\s*\(' --type=kotlin -g '*LogRing*' -g '*CrashCapture*' -g '*SiloLog*'

Repository: Silo-Server/silo-android

Length of output: 162


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the target file and nearby symbols.
ast-grep outline android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/LogRing.kt --view expanded || true

echo
echo "--- LogRing.kt (selected lines) ---"
sed -n '1,220p' android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/LogRing.kt

echo
echo "--- References to LogRing and snapshot methods ---"
rg -n -C 3 'LogRing|snapshotRange|snapshotNewest|append\(' android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging -g '*.kt'

echo
echo "--- Crash/logging call sites in androidMain ---"
rg -n -C 3 'snapshotRange|snapshotNewest|LogRing' android-shared/src/androidMain -g '*.kt'

Repository: Silo-Server/silo-android

Length of output: 21003


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- SiloLog.kt crash snapshot context ---"
sed -n '1,180p' android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/SiloLog.kt

echo
echo "--- Search for ringSnapshotForCrash usage across android-shared ---"
rg -n -C 3 'ringSnapshotForCrash|snapshotNewest|snapshotRange|LogRing' android-shared -g '*.kt'

echo
echo "--- Look for crash handler / uncaught exception handling ---"
rg -n -C 4 'UncaughtExceptionHandler|crash|fatal|ringSnapshotForCrash|snapshotNewest' android-shared/src/androidMain -g '*.kt'

Repository: Silo-Server/silo-android

Length of output: 50381


Re-read the sequence after loading the slot data The current check can race with a wraparound append: slotSeq may still equal seq while another thread overwrites the slot before slotData.get(idx) runs, so the snapshot can return a newer line under the old sequence. Read slotSeq again after the data load and only accept the entry if both reads match.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/logging/LogRing.kt`
around lines 54 - 62, Update the snapshot loop in LogRing’s sequence/data read
block to re-read slotSeq after loading slotData. Add the entry only when the
initial and final sequence reads both equal seq, preventing overwritten data
from being returned under an older sequence.

Comment on lines +43 to +55
eventsJob = scope.launch {
events.collect { event ->
stats = reducePlayerStats(stats, event)
logEvent(event)
}
}
tickerJob = scope.launch {
while (isActive) {
delay(STATS_INTERVAL_MS)
if (statsTimelineEnabled()) logStatsSnapshot()
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

No exception guard around events.collect.

If reducePlayerStats or logEvent throws for an unexpected event shape, the exception propagates uncaught through this SupervisorJob-rooted scope (no installed CoroutineExceptionHandler), which can terminate the collecting thread/crash the app rather than just dropping that one diagnostics event.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/diagnostics/PlaybackDiagnosticsLogger.kt`
around lines 43 - 55, Add an exception guard around the per-event processing in
the eventsJob launched by the diagnostics logger, covering reducePlayerStats and
logEvent so malformed events are dropped without terminating collection or the
app. Keep events.collect active for subsequent events and preserve the existing
stats update and logging behavior for successful events.

Comment on lines +50 to +118
AlertDialog(
onDismissRequest = { /* must be resolved by an explicit button */ },
properties = DialogProperties(
dismissOnClickOutside = false,
dismissOnBackPress = false,
),
title = {
Text(if (plural) "Send diagnostics reports?" else "Send a diagnostics report?")
},
text = {
Column(
modifier = Modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(promptMessage(reports))
TextButton(onClick = { showDetails = !showDetails }) {
Text(if (showDetails) "Hide Report" else "View Report")
}
if (showDetails) {
reports.forEach { report ->
PromptReportSummary(report = report, serverName = state.serverName)
}
}
}
},
confirmButton = {
// iOS-style stacked actions: AlertDialog only offers two slots,
// so the three choices stack vertically in the confirm slot.
Column(horizontalAlignment = Alignment.End) {
TextButton(onClick = { viewModel.acceptPrompt(false) }) {
Text("Send")
}
TextButton(onClick = { confirmAlways = true }) {
Text("Always Send")
}
TextButton(onClick = { viewModel.declinePrompt() }) {
Text("Don't Send")
}
}
},
)

if (confirmAlways) {
AlertDialog(
onDismissRequest = { confirmAlways = false },
title = { Text("Always Send Crash Reports?") },
text = {
Text(
"Any pending reports and future crash or hang reports for this " +
"server account will be sent automatically.",
)
},
confirmButton = {
TextButton(
onClick = {
confirmAlways = false
viewModel.acceptPrompt(true)
},
) {
Text("Always Send")
}
},
dismissButton = {
TextButton(onClick = { confirmAlways = false }) {
Text("Cancel")
}
},
)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Primary prompt dialog stays visible while the "Always Send" confirmation is shown.

The primary AlertDialog (lines 50-90) isn't gated on confirmAlways, so once the user taps "Always Send" both this dialog and the confirmation dialog (lines 92-118) render simultaneously — two stacked dialog surfaces instead of a single confirmation replacing the prompt.

🐛 Proposed fix: hide the primary dialog while the confirmation is up
-    AlertDialog(
-        onDismissRequest = { /* must be resolved by an explicit button */ },
-        properties = DialogProperties(
-            dismissOnClickOutside = false,
-            dismissOnBackPress = false,
-        ),
-        title = {
+    if (!confirmAlways) {
+    AlertDialog(
+        onDismissRequest = { /* must be resolved by an explicit button */ },
+        properties = DialogProperties(
+            dismissOnClickOutside = false,
+            dismissOnBackPress = false,
+        ),
+        title = {
             Text(if (plural) "Send diagnostics reports?" else "Send a diagnostics report?")
         },
         ...
-    )
+    )
+    }

     if (confirmAlways) {
         AlertDialog(
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AlertDialog(
onDismissRequest = { /* must be resolved by an explicit button */ },
properties = DialogProperties(
dismissOnClickOutside = false,
dismissOnBackPress = false,
),
title = {
Text(if (plural) "Send diagnostics reports?" else "Send a diagnostics report?")
},
text = {
Column(
modifier = Modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(promptMessage(reports))
TextButton(onClick = { showDetails = !showDetails }) {
Text(if (showDetails) "Hide Report" else "View Report")
}
if (showDetails) {
reports.forEach { report ->
PromptReportSummary(report = report, serverName = state.serverName)
}
}
}
},
confirmButton = {
// iOS-style stacked actions: AlertDialog only offers two slots,
// so the three choices stack vertically in the confirm slot.
Column(horizontalAlignment = Alignment.End) {
TextButton(onClick = { viewModel.acceptPrompt(false) }) {
Text("Send")
}
TextButton(onClick = { confirmAlways = true }) {
Text("Always Send")
}
TextButton(onClick = { viewModel.declinePrompt() }) {
Text("Don't Send")
}
}
},
)
if (confirmAlways) {
AlertDialog(
onDismissRequest = { confirmAlways = false },
title = { Text("Always Send Crash Reports?") },
text = {
Text(
"Any pending reports and future crash or hang reports for this " +
"server account will be sent automatically.",
)
},
confirmButton = {
TextButton(
onClick = {
confirmAlways = false
viewModel.acceptPrompt(true)
},
) {
Text("Always Send")
}
},
dismissButton = {
TextButton(onClick = { confirmAlways = false }) {
Text("Cancel")
}
},
)
}
if (!confirmAlways) {
AlertDialog(
onDismissRequest = { /* must be resolved by an explicit button */ },
properties = DialogProperties(
dismissOnClickOutside = false,
dismissOnBackPress = false,
),
title = {
Text(if (plural) "Send diagnostics reports?" else "Send a diagnostics report?")
},
text = {
Column(
modifier = Modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(promptMessage(reports))
TextButton(onClick = { showDetails = !showDetails }) {
Text(if (showDetails) "Hide Report" else "View Report")
}
if (showDetails) {
reports.forEach { report ->
PromptReportSummary(report = report, serverName = state.serverName)
}
}
}
},
confirmButton = {
// iOS-style stacked actions: AlertDialog only offers two slots,
// so the three choices stack vertically in the confirm slot.
Column(horizontalAlignment = Alignment.End) {
TextButton(onClick = { viewModel.acceptPrompt(false) }) {
Text("Send")
}
TextButton(onClick = { confirmAlways = true }) {
Text("Always Send")
}
TextButton(onClick = { viewModel.declinePrompt() }) {
Text("Don't Send")
}
}
},
)
}
if (confirmAlways) {
AlertDialog(
onDismissRequest = { confirmAlways = false },
title = { Text("Always Send Crash Reports?") },
text = {
Text(
"Any pending reports and future crash or hang reports for this " +
"server account will be sent automatically.",
)
},
confirmButton = {
TextButton(
onClick = {
confirmAlways = false
viewModel.acceptPrompt(true)
},
) {
Text("Always Send")
}
},
dismissButton = {
TextButton(onClick = { confirmAlways = false }) {
Text("Cancel")
}
},
)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/diagnostics/CrashPromptDialog.kt`
around lines 50 - 118, Gate the primary AlertDialog rendering on !confirmAlways
so it is hidden while the “Always Send” confirmation dialog is displayed. Keep
the existing confirmAlways state transitions and confirmation dialog behavior
unchanged.

@Quick104
Quick104 force-pushed the feat/client-diagnostics-android branch from db3f6e9 to ca8daa4 Compare July 22, 2026 22:16

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: db3f6e9beb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


val choice = binding?.let { consentStore.record(it, status?.consentNoticeVersion ?: 1).mode }
?: ConsentChoice.ASK
breadcrumbJournal.setEnabled(binding != null && choice != ConsentChoice.NEVER)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Register breadcrumb journal before enabling it

For crash/hang reports that rely on breadcrumbs (especially ANR/native exits collected after restart), enabling the BreadcrumbJournal here is not enough because SiloLog.breadcrumb(...) only writes to a journal after SiloLog.installBreadcrumbJournal(...) has been called. I searched the repo for installBreadcrumbJournal and found only the declaration, so the sink stays null and CrashMarkerAssembler/ExitInfoCollector will read an empty journal, stripping the intended pre-crash context from those reports.

Useful? React with 👍 / 👎.

SettingsActionRow(
label = "Start Diagnostic Capture",
onClick = viewModel::startCapture,
enabled = sendEnabled,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allow TV capture while uploads are offline

When the diagnostics status is OFFLINE but a cached binding exists, this disables Start Diagnostic Capture because sendEnabled requires AVAILABLE. The coordinator can still build a pending manual report under the cached binding and keep the upload for later, and the phone UI does not availability-gate starting capture, so TV users lose the ability to capture the issue during exactly the outage/offline scenario diagnostics is meant to help investigate.

Useful? React with 👍 / 👎.

breadcrumbJournal.setEnabled(binding != null && choice != ConsentChoice.NEVER)
applyDebugLogging(settingsStore.debugLogging.value || captureActive)

publishCrashContext(binding, status, profile)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Disarm crash context when diagnostics is disabled

When the status response is disabled, storage_unavailable, or another non-available state, this still publishes a valid binding into CrashContextCache. A crash or ANR captured while the server has diagnostics gated off will be persisted as a pending report and can later be prompted or auto-uploaded if the server becomes available within the retention window; clear the crash context unless the current/cached status actually allows capture.

Useful? React with 👍 / 👎.

occurredAt = occurredAt,
),
deviceSummary = deviceSnapshotCollector.deviceSummary(),
playbackSessionIds = emptyList(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Attach recent sessions to exit-info reports

For API 30+ ANR/native-crash captures, this hard-codes playback_session_ids to empty even though playback session starts are now recorded in RecentSessionTracker for exactly this kind of next-launch report. When an ANR or native crash happens during playback, the uploaded report loses the session IDs operators need to pivot into server playback logs; populate this from the binding's recent sessions like manual reports do.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant