Skip to content

Added Firebase analytics for computer vision.#804

Merged
hal-eisen-adfa merged 6 commits intostagefrom
ADFA-2458
Jan 21, 2026
Merged

Added Firebase analytics for computer vision.#804
hal-eisen-adfa merged 6 commits intostagefrom
ADFA-2458

Conversation

@avestaadfa
Copy link
Contributor

No description provided.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 7, 2026

📝 Walkthrough
  • Release notes:

    • Firebase Analytics dependency added to cv-image-to-xml:
      • cv-image-to-xml/build.gradle.kts now includes implementation(platform(libs.firebase.bom)) and implementation(libs.firebase.analytics).
    • New centralized analytics helper:
      • Added org.appdevforall.codeonthego.computervision.utils.CvAnalyticsUtil.
      • Lazily initializes Firebase.analytics (try/catch fallback) and safely logs events.
      • Public tracking methods:
        • trackScreenOpened()
        • trackImageSelected(fromCamera: Boolean) — logs source ("camera" / "gallery")
        • trackDetectionStarted()
        • trackDetectionCompleted(success: Boolean, detectionCount: Int, durationMs: Long)
        • trackXmlGenerated(componentCount: Int)
        • trackXmlExported(toDownloads: Boolean) — logs export_method ("save_downloads" / "update_layout")
      • All events include a custom "timestamp" field (System.currentTimeMillis()).
    • Instrumentation added in computer-vision flow:
      • ComputerVisionViewModel:
        • New public method onScreenStarted() calls CvAnalyticsUtil.trackScreenOpened().
        • Calls inserted at these points:
          • ImageSelected (gallery): trackImageSelected(fromCamera = false)
          • ImageCaptured (camera success): trackImageSelected(fromCamera = true)
          • runDetection start: trackDetectionStarted() and start-time capture
          • runDetection completion/failure: trackDetectionCompleted(success, detectionCount, durationMs)
          • XML generation success (update layout path): trackXmlGenerated(...) and trackXmlExported(toDownloads = false)
          • Save-to-downloads path: trackXmlGenerated(...) and trackXmlExported(toDownloads = true)
      • ComputerVisionActivity:
        • Calls viewModel.onScreenStarted() in lifecycle observer at STARTED.
    • Public API surface:
      • One added public method: ComputerVisionViewModel.onScreenStarted()
      • No other public signature removals or changes.
  • Risks / Best-practice violations:

    • No consent/opt-out or user-facing analytics controls (GDPR/CCPA risk).
    • Duplicate timestamps: events add System.currentTimeMillis() though Firebase already timestamps events.
    • Missing event schema/docs: no central documentation/KDoc describing event names, param types, allowed values, or expected semantics.
    • Partial coverage of error paths: some failure branches log detection-completed; others (e.g., certain merge failures) rely on existing handlers and may not consistently emit analytics.
    • Unconditional logging: events are logged without sampling, rate limiting, or batching — may increase analytics cost or privacy exposure.
    • Dependency assumptions: relies on libs.firebase.bom and libs.firebase.analytics in the version catalog; misconfiguration will fail the build.
    • Concurrency and initialization: lazy init uses try/catch but lacks explicit thread-safety guarantees, tests, or fallbacks for concurrent access or late initialization.
    • Privacy/minimization concerns: event payloads include counts/durations and implicit device-linked analytics — verify alignment with privacy policy and minimization principles.
    • No unit/integration tests or validation for analytics calls (risk of regressions or silent failures).
    • Potential performance impact: synchronous logging around hot paths (detection flow) could add overhead; consider async/sampling strategies.

Walkthrough

Adds Firebase Analytics dep, introduces a new CvAnalyticsUtil for event logging, and integrates analytics calls into ComputerVisionViewModel and ComputerVisionActivity to emit events for screen open, image selection, detection lifecycle, and XML generation/export.

Changes

Cohort / File(s) Summary
Firebase Dependency
cv-image-to-xml/build.gradle.kts
Added implementation(platform(libs.firebase.bom)) and implementation(libs.firebase.analytics) to dependencies.
Analytics Utility
cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/utils/CvAnalyticsUtils.kt
New CvAnalyticsUtil object: safe lazy Firebase init, logEvent helper, and public tracking methods (trackScreenOpened, trackImageSelected, trackDetectionStarted, trackDetectionCompleted, trackXmlGenerated, trackXmlExported) that include timestamps and contextual params.
ViewModel Integration
cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/viewmodel/ComputerVisionViewModel.kt
Inserted analytics calls at lifecycle and user-action points (screen start, image selection/capture, detection start/completion with duration/count, XML generation/export). Added public onScreenStarted() method.
Activity Hook
cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/ComputerVisionActivity.kt
Calls viewModel.onScreenStarted() in the STARTED lifecycle observer; added related imports.

Sequence Diagram(s)

sequenceDiagram
    participant UI as User / UI
    participant Activity as ComputerVisionActivity
    participant VM as ComputerVisionViewModel
    participant UTIL as CvAnalyticsUtil
    participant FB as Firebase Analytics

    UI->>Activity: Open screen
    Activity->>VM: lifecycle STARTED
    VM->>UTIL: trackScreenOpened()
    UTIL->>FB: logEvent "cv_screen_opened"

    UI->>VM: Select image / Capture photo
    VM->>UTIL: trackImageSelected(fromCamera)
    UTIL->>FB: logEvent "cv_image_selected"
    VM->>VM: load image and start detection
    VM->>UTIL: trackDetectionStarted()
    UTIL->>FB: logEvent "cv_detection_started"

    VM->>VM: detection completes
    VM->>UTIL: trackDetectionCompleted(success, count, durationMs)
    UTIL->>FB: logEvent "cv_detection_completed"

    VM->>VM: generate/export XML
    VM->>UTIL: trackXmlGenerated(componentCount)
    UTIL->>FB: logEvent "cv_xml_generated"
    VM->>UTIL: trackXmlExported(toDownloads)
    UTIL->>FB: logEvent "cv_xml_exported"
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through code with a tiny twitch,

I planted events by the Firebase ditch,
Screens and snaps and detections I sing,
XMLs counted — a neat little thing,
Metrics snug in my fur, ready to stitch.

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive No pull request description was provided by the author, making it impossible to assess relevance to the changeset. Add a description explaining the purpose of the analytics integration, what events are tracked, and any configuration or testing notes.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the main change: adding Firebase analytics integration to the computer vision module.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In
@cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/viewmodel/ComputerVisionViewModel.kt:
- Around line 50-55: Analytics for camera-captured images is missing: modify the
handler for ComputerVisionEvent.ImageCaptured by updating the
handleCameraResult(uri: Uri, success: Boolean) method so that when success is
true it calls CvAnalyticsUtil.trackImageSelected(fromCamera = true) before
invoking loadImageFromUri(uri), and when success is false it preserves the
existing behavior of sending
ComputerVisionEffect.ShowToast(R.string.msg_image_capture_cancelled) via
viewModelScope; ensure references to ComputerVisionEvent.ImageCaptured,
handleCameraResult, CvAnalyticsUtil.trackImageSelected, loadImageFromUri, and
ComputerVisionEffect.ShowToast are used to locate and update the code.
🧹 Nitpick comments (2)
cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/viewmodel/ComputerVisionViewModel.kt (1)

161-171: Move analytics call outside the state update lambda.

The trackDetectionCompleted call inside _uiState.update { } is a side effect within a state transformation. This violates the expectation that update lambdas are pure functions.

Proposed fix
 mergeResult
     .onSuccess { mergedDetections ->
+        CvAnalyticsUtil.trackDetectionCompleted(
+            success = true,
+            detectionCount = mergedDetections.size,
+            durationMs = System.currentTimeMillis() - startTime
+        )
         _uiState.update {
-            CvAnalyticsUtil.trackDetectionCompleted(
-                success = true,
-                detectionCount = mergedDetections.size,
-                durationMs = System.currentTimeMillis() - startTime
-            )
             it.copy(
                 detections = mergedDetections,
                 currentOperation = CvOperation.Idle
             )
         }
cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/utils/CvAnalyticsUtils.kt (1)

7-14: Consider removing redundant timestamp parameters.

Firebase Analytics automatically records the timestamp when each event is logged. Adding putLong("timestamp", System.currentTimeMillis()) to every event is redundant and increases payload size without adding value. The automatic timestamp is more reliable as it's captured at the Firebase SDK level.

Example for one method
 fun trackScreenOpened() {
-    analytics.logEvent("cv_screen_opened", Bundle().apply {
-        putLong("timestamp", System.currentTimeMillis())
-    })
+    analytics.logEvent("cv_screen_opened", null)
 }

Apply similar changes to other methods, keeping only the meaningful custom parameters.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0ab4116 and 4180247.

📒 Files selected for processing (3)
  • cv-image-to-xml/build.gradle.kts
  • cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/viewmodel/ComputerVisionViewModel.kt
  • cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/utils/CvAnalyticsUtils.kt
🔇 Additional comments (5)
cv-image-to-xml/build.gradle.kts (1)

51-54: LGTM! Firebase dependencies added correctly using BOM.

Using platform(libs.firebase.bom) ensures consistent versioning across Firebase libraries. Verify that the com.google.gms.google-services plugin is applied in the main application module (not this library module) and that google-services.json is properly configured.

cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/viewmodel/ComputerVisionViewModel.kt (2)

43-46: LGTM! Screen open tracking appropriately placed in init.


213-218: LGTM! XML generation and export tracking implemented correctly.

Analytics calls are properly placed outside state update lambdas and capture the relevant metadata.

cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/utils/CvAnalyticsUtils.kt (2)

28-35: Good event design with meaningful parameters.

The trackDetectionCompleted event captures useful metrics (success status, detection count, duration) that will enable meaningful funnel analysis.


1-51: Overall structure is well-designed.

Using a Kotlin object with lazy initialization for Firebase Analytics is the correct pattern. Event naming with cv_ prefix provides good namespacing. Consider adding a brief KDoc comment to the object describing its purpose.

@jatezzz jatezzz self-requested a review January 8, 2026 15:21
@avestaadfa avestaadfa requested a review from jatezzz January 14, 2026 21:21
…ate screen open event to be LifeCycle.Started event
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/viewmodel/ComputerVisionViewModel.kt (1)

159-172: Move analytics call outside the _uiState.update lambda.

The update lambda should be a pure state transformation without side effects. Placing analytics calls inside risks issues if the lambda is retried due to CAS failures in MutableStateFlow.update().

Proposed fix
 mergeResult
     .onSuccess { mergedDetections ->
+        CvAnalyticsUtil.trackDetectionCompleted(
+            success = true,
+            detectionCount = mergedDetections.size,
+            durationMs = System.currentTimeMillis() - startTime
+        )
         _uiState.update {
-            CvAnalyticsUtil.trackDetectionCompleted(
-                success = true,
-                detectionCount = mergedDetections.size,
-                durationMs = System.currentTimeMillis() - startTime
-            )
             it.copy(
                 detections = mergedDetections,
                 currentOperation = CvOperation.Idle
             )
         }
         Log.d(TAG, "Detection complete. ${mergedDetections.size} objects detected.")
     }
🤖 Fix all issues with AI agents
In
`@cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/ComputerVisionActivity.kt`:
- Around line 126-132: The call to viewModel.onScreenStarted() inside
ComputerVisionActivity.observeViewModel fires every time the lifecycle reaches
STARTED; move that single-shot event out of repeatOnLifecycle to run only once
per Activity instance by either (A) calling viewModel.onScreenStarted() from
onCreate() instead of inside observeViewModel, or (B) add an Activity-level
Boolean flag (e.g., var screenOpened = false) and inside observeViewModel only
invoke viewModel.onScreenStarted() when screenOpened is false then set it true;
keep the viewModel.uiState.collect { state -> updateUi(state) } inside
repeatOnLifecycle as-is.
♻️ Duplicate comments (1)
cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/viewmodel/ComputerVisionViewModel.kt (1)

115-123: Missing analytics tracking for camera-captured images.

trackImageSelected(fromCamera = false) is called for gallery selection, but handleCameraResult loads an image on success without corresponding analytics tracking.

Proposed fix
 private fun handleCameraResult(uri: Uri, success: Boolean) {
     if (success) {
+        CvAnalyticsUtil.trackImageSelected(fromCamera = true)
         loadImageFromUri(uri)
     } else {
         viewModelScope.launch {
             _uiEffect.send(ComputerVisionEffect.ShowToast(R.string.msg_image_capture_cancelled))
         }
     }
 }
🧹 Nitpick comments (2)
cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/utils/CvAnalyticsUtils.kt (2)

16-17: Remove extra blank line.

 object CvAnalyticsUtil {
     private const val TAG = "CvAnalyticsUtil"
-
 
     private val analytics by lazy {

35-74: Consider removing redundant timestamp parameter.

Firebase Analytics automatically records event timestamps server-side. Adding a custom timestamp to every event is redundant and increases payload size without benefit.

Example for trackScreenOpened
 fun trackScreenOpened() {
-    logEvent(CV_SCREEN_OPENED, Bundle().apply {
-        putLong("timestamp", System.currentTimeMillis())
-    })
+    logEvent(CV_SCREEN_OPENED, Bundle())
 }
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2938db5 and 7fba335.

📒 Files selected for processing (3)
  • cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/ComputerVisionActivity.kt
  • cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/viewmodel/ComputerVisionViewModel.kt
  • cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/utils/CvAnalyticsUtils.kt
⏰ Context from checks skipped due to timeout of 300000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Build Universal APK
🔇 Additional comments (9)
cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/ComputerVisionActivity.kt (1)

24-28: LGTM!

Import additions are appropriate for the binding, model, viewmodel, and Koin integration.

cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/viewmodel/ComputerVisionViewModel.kt (5)

49-52: LGTM!

Analytics tracking for gallery image selection is correctly placed before loading the image.


89-91: LGTM!

The onScreenStarted() method properly delegates to the analytics utility. This addresses the past feedback to move tracking to a lifecycle-aware call.


135-136: LGTM!

Detection start and failure tracking are correctly placed outside state update lambdas.

Also applies to: 141-143


214-215: LGTM!

Analytics calls are correctly placed in the success callback, outside any state update lambdas.


245-246: LGTM!

Analytics calls for download export are correctly placed.

cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/utils/CvAnalyticsUtils.kt (3)

14-25: LGTM!

Good defensive initialization with try-catch to handle cases where Firebase Analytics is unavailable. The lazy initialization pattern is appropriate here.


27-33: LGTM!

The logEvent wrapper with try-catch ensures analytics failures don't crash the app.


76-83: LGTM!

Event names are properly centralized as constants, addressing previous feedback.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@Daniel-ADFA Daniel-ADFA requested a review from jatezzz January 16, 2026 19:15
@jatezzz jatezzz requested a review from itsaky-adfa January 16, 2026 21:02
@jatezzz jatezzz removed the request for review from itsaky-adfa January 16, 2026 21:03
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cv-image-to-xml/src/main/java/org/appdevforall/codeonthego/computervision/ui/viewmodel/ComputerVisionViewModel.kt (1)

160-176: Track detection completion on merge failure too.

The mergeResult failure path doesn’t emit trackDetectionCompleted, so analytics will miss completion for that failure case.

✅ Proposed fix
-            mergeResult
-                .onSuccess { mergedDetections ->
+            mergeResult
+                .onSuccess { mergedDetections ->
                     CvAnalyticsUtil.trackDetectionCompleted(
                         success = true,
                         detectionCount = mergedDetections.size,
                         durationMs = System.currentTimeMillis() - startTime
                     )
                     _uiState.update {
                         it.copy(
                             detections = mergedDetections,
                             currentOperation = CvOperation.Idle
                         )
                     }
                     Log.d(TAG, "Detection complete. ${mergedDetections.size} objects detected.")
                 }
-                .onFailure { handleDetectionError(it) }
+                .onFailure { exception ->
+                    CvAnalyticsUtil.trackDetectionCompleted(
+                        success = false,
+                        detectionCount = 0,
+                        durationMs = System.currentTimeMillis() - startTime
+                    )
+                    handleDetectionError(exception)
+                }

@hal-eisen-adfa hal-eisen-adfa merged commit c350545 into stage Jan 21, 2026
2 checks passed
@hal-eisen-adfa hal-eisen-adfa deleted the ADFA-2458 branch January 21, 2026 23:04
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.

4 participants