Skip to content

Ya/user id migration#2189

Draft
yagarwal1307 wants to merge 1 commit intodevfrom
ya/user-id-migration
Draft

Ya/user id migration#2189
yagarwal1307 wants to merge 1 commit intodevfrom
ya/user-id-migration

Conversation

@yagarwal1307
Copy link
Copy Markdown
Member

@yagarwal1307 yagarwal1307 commented Mar 5, 2026

Summary by CodeRabbit

Release Notes

  • New Features

    • BES firmware log collection and upload to incident backend
    • Separate flash and sound controls for photo/video capture and streaming
    • Image thumbnail generation and syncing
    • Video duration metadata in gallery
    • Incident log upload reporting
    • Firebase Analytics integration
  • Bug Fixes

    • Improved concurrent organization creation robustness
    • Enhanced gallery sync connectivity validation
  • Documentation

    • Added user identity migration roadmap

@yagarwal1307 yagarwal1307 requested a review from a team as a code owner March 5, 2026 03:18
@github-actions
Copy link
Copy Markdown

github-actions bot commented Mar 5, 2026

📋 PR Review Helper

📱 Mobile App Build

Ready to test! (commit a34cce5)

📥 Download APK

🕶️ ASG Client Build

Ready to test! (commit a34cce5)

📥 Download ASG APK


🔀 Test Locally

gh pr checkout 2189

@yagarwal1307 yagarwal1307 changed the base branch from main to dev March 5, 2026 03:18
@yagarwal1307 yagarwal1307 marked this pull request as draft March 5, 2026 03:18
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 5, 2026

Caution

Review failed

Failed to post review comments

📝 Walkthrough

Walkthrough

This PR introduces BES chip log collection and upload capabilities, refactors media controls by replacing a single "silent" flag with separate "flash" and "sound" parameters across mobile, cloud, and glasses platforms, adds a canonical userId field with race-condition fixes for personal org creation, integrates Firebase analytics and incident reporting, and enhances incident log storage to support glasses firmware logs.

Changes

Cohort / File(s) Summary
BES Log Collection
asg_client/.../io/bes/log/BesLogManager.java, asg_client/.../service/core/handlers/K900CommandHandler.java
New BesLogManager class for assembling sr_log packets with timeout watchdogs, upload to incident backend in structured JSON format, and robust error handling. K900CommandHandler extended with requestBesLogs method to initiate collection and handleBesLogPacket to process streamed packets.
Incident Reporting Handlers
asg_client/.../service/core/handlers/UploadIncidentLogsCommandHandler.java, asg_client/.../service/core/handlers/KeepAwakeCommandHandler.java
New command handlers: UploadIncidentLogsCommandHandler posts glasses logs to /api/incidents/{id}/logs with JSON payload and optional BES log collection; KeepAwakeCommandHandler logs and acknowledges keep_awake commands.
Media Control Refactoring (Silent → Flash/Sound)
asg_client/.../io/media/core/MediaCaptureService.java, asg_client/.../service/core/handlers/PhotoCommandHandler.java, asg_client/.../service/core/handlers/VideoCommandHandler.java, asg_client/.../service/core/handlers/RtmpCommandHandler.java
Replaced single enableLed/silent flag with separate enableFlash and enableSound booleans throughout video recording, photo capture, and RTMP streaming APIs; updated internal routing, logging, and control flow accordingly.
Streaming Sound Control
asg_client/.../io/streaming/services/RtmpStreamingService.java
Added mSoundEnabled flag and new overloaded startStreaming variants with enableSound parameter; added start/stop sound playback gated by mSoundEnabled and hardware capabilities.
Media Metadata & Thumbnails
asg_client/.../io/file/managers/ThumbnailManager.java, asg_client/.../io/server/services/AsgCameraServer.java
ThumbnailManager now supports image thumbnails with calculateInSampleSize utility; added deleteThumbnailForFile for both videos and images. AsgCameraServer extracts video duration via MediaMetadataRetriever and includes thumbnail_data in sync responses when include_thumbnails is enabled.
Log Aggregation Utilities
asg_client/.../reporting/GlassesLogBuffer.java, cloud/.../src/api/hono/client/incident-logs.api.ts
New GlassesLogBuffer class for on-demand extraction of recent logcat output as JSON; incident-logs API extended with glassesFirmwareLogs category, routing body.source "glasses_firmware" to dedicated log array, and verbose logging for debugging.
User Identity & Race Condition Fixes
cloud/.../src/models/user.model.ts, cloud/.../src/services/core/organization.service.ts, cloud/.../src/services/console/console.account.service.ts, cloud/.../src/services/console/console.apps.service.ts, cloud/.../src/services/console/orgs.service.ts, cloud/.../src/routes/developer.routes.ts
Added userId field (UUID, unique, indexed) to User model with toJSON exposure; replaced user.save() with atomic updateOne operations for organizations and defaultOrg to prevent concurrent VersionError; createPersonalOrg now idempotent with admin role check and deterministic slug from user ID; retry logic on E11000 duplicate key errors.
User Identity Migration Infrastructure
cloud/.../src/scripts/migrate-user-ids.ts, docs/USER_IDENTITY_MIGRATION_PLAN.md
New migration script to backfill missing userId fields in batches; comprehensive phased migration plan (4 phases) detailing user model changes, identifier array introduction, and email deprecation strategy with rollout safety checks.
Organization Bootstrap & Concurrency
cloud/websites/console/src/context/OrganizationContext.tsx, cloud/websites/console/src/pages/OrganizationSettings.tsx
Added useCallback/useRef-based mutex to prevent concurrent ensurePersonalOrg calls; enhanced error handling with retry backoff and toast feedback; single-run guard via orgCreationAttemptedRef to prevent infinite retry loops.
Incident Log Storage & Routing
cloud/packages/cloud/src/services/storage/incident-storage.service.ts, cloud/packages/cloud/src/services/session/PhotoManager.ts, cloud/packages/cloud/src/services/session/UnmanagedStreamingExtension.ts, cloud/packages/cloud/src/services/streaming/ManagedStreamingExtension.ts
Extended IncidentLogs interface with glassesFirmwareLogs field; appendLogs now accepts glassesFirmwareLogs category; PhotoManager and streaming extensions replaced SILENT_PHOTO_PACKAGES logic with flash and sound controls in message payloads.
Cloud SDK Message Types
cloud/packages/sdk/src/types/messages/app-to-cloud.ts, cloud/packages/sdk/src/types/messages/cloud-to-glasses.ts, cloud/packages/sdk/src/app/session/modules/camera.ts, cloud/packages/sdk/src/app/session/modules/camera-managed-extension.ts
Added optional sound?: boolean to PhotoRequest, RtmpStreamRequest, and ManagedStreamRequest; replaced silent with flash and sound in PhotoRequestToGlasses and StartRtmpStream message types.
Console UI - Incident Details
cloud/websites/console/src/pages/IncidentDetail.tsx, cloud/websites/console/src/services/api.service.ts
Added new "glasses_firmware" (Glasses firmware (BES)) tab to incident details with Cpu icon; renamed Glasses logs tab to "Glasses Logs (ASG Client)"; updated IncidentLogs interface to include glassesFirmwareLogs field.
Mobile Core Module Refactoring
mobile/modules/core/android/src/main/java/com/mentra/core/CoreManager.kt, mobile/modules/core/android/src/main/java/com/mentra/core/CoreModule.kt, mobile/modules/core/android/src/main/java/com/mentra/core/sgcs/*, mobile/modules/core/ios/Source/*
New sendIncidentId API across all SGC implementations (G1, Mach1, MentraLive, MentraNex, Simulated); replaced silent parameter with flash and sound in requestPhoto and startVideoRecording across Android and iOS implementations; added auth token persistence in SharedPreferences and token retry mechanism in MentraLive.
Mobile Socket & REST Communications
mobile/src/services/SocketComms.ts, mobile/src/services/RestComms.ts, mobile/src/services/asg/gallerySyncService.ts
Updated photoRequest and startVideoRecording calls to use flash and sound instead of silent; added CoreModule.update("core", {auth_token}) in setCoreToken; added connectivity pre-flight checks in gallerySyncService startSync and hotspot handling.
Mobile Gallery & Media Display
mobile/src/components/glasses/Gallery/GalleryScreen.tsx, mobile/src/components/glasses/Gallery/PhotoImage.tsx, mobile/src/types/asg/index.ts, mobile/src/services/asg/localStorageService.ts
Added duration field to PhotoInfo interface; gallery now displays video duration using formatDuration helper; PhotoImage prefers thumbnail_data (base64-converted) over full URLs for both photos and videos; clearAllFiles now removes entire photos directory and recreates required directories.
Mobile Firebase Integration
mobile/src/utils/analytics.ts, mobile/src/effects/FirebaseAnalyticsSetup.tsx, mobile/app.config.ts, mobile/modules/core/plugin/src/withIos.ts, mobile/package.json, mobile/GoogleService-Info.plist, mobile/google-services.json
New analytics utility with initAnalytics, logEvent, setUserId, setUserProperty, logScreenView with China deployment guard; FirebaseAnalyticsSetup component; Firebase configuration files for iOS (GoogleService-Info.plist) and Android (google-services.json); Pod dependencies added for Firebase/Google utilities; @react-native-firebase dependencies added to package.json.
Mobile UI & Layout Adjustments
mobile/src/app/onboarding/welcome.tsx, mobile/src/app/pairing/prep.tsx, mobile/src/app/pairing/scan.tsx, mobile/src/components/onboarding/OnboardingGuide.tsx, mobile/src/components/ignite/Button.tsx, mobile/src/app/settings/feedback.tsx
Welcome card button uses flex:1 with maxHeight for responsive sizing; prep and scan screens adjusted for ScrollView wrapper and centered layout; OnboardingGuide bottom controls repositioned to absolute bottom bar; Button component adds disabled opacity styling; feedback form adds phone backend URL logging and CoreModule.sendIncidentId trigger after incident creation.
Mobile Release Automation
mobile/scripts/release-android.mjs
New Android release script orchestrating version bumping, prebuild, asset bundling, APK/AAB building via Fastlane and Gradle, GitHub release creation, and Google Play upload with conditional logic for missing service key.
Minor & Cleanup
asg_client/.../io/bluetooth/managers/K900BluetoothManager.java, asg_client/service/core/AsgClientService.java, mobile/src/utils/PermissionsUtils.tsx
Removed comments above BES system version request; removed blank line before catch block; updated permission descriptive text from AugmentOS to Mentra.

Sequence Diagram(s)

sequenceDiagram
    participant Glasses as Glasses Device
    participant BesLog as BesLogManager
    participant Handler as K900CommandHandler
    participant Service as AsgCameraServer
    participant Backend as Backend API

    Glasses->>Handler: requestBesLogs(incidentId)
    activate Handler
    Handler->>Handler: validate Bluetooth connection
    Handler->>BesLog: new BesLogManager(incidentId, context, configMgr)
    activate BesLog
    BesLog->>BesLog: startTimeouts() - first packet 2s, overall 20s
    Handler->>Glasses: send mh_logs command (C,V,B framing)
    Glasses->>BesLog: onLogPacketReceived(cur, body) - sr_log packets
    BesLog->>BesLog: reassemble packets, detect terminator (cur=255)
    BesLog->>BesLog: finalize logs, build JSON array per-line
    BesLog->>Backend: POST /api/incidents/{id}/logs with structured JSON
    activate Backend
    Backend->>Backend: route to glassesFirmwareLogs category
    Backend-->>BesLog: 200 OK
    deactivate Backend
    BesLog-->>Handler: logs uploaded or printed if no incidentId
    deactivate BesLog
    Handler-->>Glasses: session complete
    deactivate Handler
Loading
sequenceDiagram
    participant Mobile as Mobile App
    participant Cloud as Cloud Console API
    participant OrgService as Organization Service
    participant UserModel as User Model
    participant DB as MongoDB

    Mobile->>Cloud: GET /api/console/account
    activate Cloud
    Cloud->>OrgService: ensurePersonalOrg(userId)
    activate OrgService
    OrgService->>UserModel: find existing admin org
    alt Admin org exists
        OrgService-->>Cloud: return existing org ID
    else Create new org
        OrgService->>OrgService: generate deterministic slug with user._id suffix
        OrgService->>DB: save org (with retry on E11000)
        DB-->>OrgService: org created
        OrgService->>UserModel: atomic updateOne({organizations, defaultOrg})
        UserModel->>DB: $addToSet + $set (no VersionError)
        DB-->>UserModel: updated
        OrgService-->>Cloud: return new org ID
    end
    deactivate OrgService
    Cloud->>Cloud: re-fetch user with new org state
    Cloud-->>Mobile: 200 OK with orgs list
    deactivate Cloud
    Mobile->>Mobile: apply orgs, persist to localStorage
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Suggested reviewers

  • isaiahb

Poem

🐰 Whiskers twitch with joy!
Logs collected, orgs fixed right,
Flash and sound controls
Firebase ignites the night—
Identity in flight! ✨📱

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ya/user-id-migration

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