From 0dedf82dea4c42e460e90f5580afd05fb8dbf379 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 8 Jul 2026 06:00:32 -0700 Subject: [PATCH] feat(mobile): add Android Live Update preview --- apps/mobile/README.md | 40 ++++ apps/mobile/app.config.ts | 1 + .../t3-agent-live-update/android/build.gradle | 20 ++ .../android/src/main/AndroidManifest.xml | 10 + .../AgentLiveUpdateDismissReceiver.kt | 11 + .../AgentLiveUpdateManager.kt | 194 ++++++++++++++++++ .../t3agentliveupdate/LiveUpdateSnapshot.kt | 18 ++ .../T3AgentLiveUpdateModule.kt | 38 ++++ .../res/drawable/t3_agent_live_update.xml | 10 + .../expo-module.config.json | 6 + .../modules/t3-agent-live-update/package.json | 12 ++ apps/mobile/plugins/withAndroidUnifiedNdk.cjs | 36 ++++ .../agent-awareness/androidLiveUpdate.ts | 96 +++++++++ .../AndroidLiveUpdatePreviewSection.tsx | 130 ++++++++++++ .../features/settings/SettingsRouteScreen.tsx | 5 + 15 files changed, 627 insertions(+) create mode 100644 apps/mobile/modules/t3-agent-live-update/android/build.gradle create mode 100644 apps/mobile/modules/t3-agent-live-update/android/src/main/AndroidManifest.xml create mode 100644 apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/AgentLiveUpdateDismissReceiver.kt create mode 100644 apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/AgentLiveUpdateManager.kt create mode 100644 apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/LiveUpdateSnapshot.kt create mode 100644 apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/T3AgentLiveUpdateModule.kt create mode 100644 apps/mobile/modules/t3-agent-live-update/android/src/main/res/drawable/t3_agent_live_update.xml create mode 100644 apps/mobile/modules/t3-agent-live-update/expo-module.config.json create mode 100644 apps/mobile/modules/t3-agent-live-update/package.json create mode 100644 apps/mobile/plugins/withAndroidUnifiedNdk.cjs create mode 100644 apps/mobile/src/features/agent-awareness/androidLiveUpdate.ts create mode 100644 apps/mobile/src/features/settings/AndroidLiveUpdatePreviewSection.tsx diff --git a/apps/mobile/README.md b/apps/mobile/README.md index 0eb865cb79..1a1c25d6ab 100644 --- a/apps/mobile/README.md +++ b/apps/mobile/README.md @@ -28,6 +28,46 @@ Start Metro for the dev client: vp run dev:client ``` +### Android + +Local Android builds require Android Studio, JDK 17, and an Android SDK. On an Apple Silicon Mac, +the following setup installs the API 36.1 emulator used to exercise promoted ongoing notifications +(Android Live Updates): + +```bash +brew install --cask android-studio android-commandlinetools +brew install openjdk@17 + +export JAVA_HOME="/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home" +export ANDROID_HOME="$HOME/Library/Android/sdk" +export ANDROID_SDK_ROOT="$ANDROID_HOME" +export PATH="$JAVA_HOME/bin:$ANDROID_HOME/emulator:$ANDROID_HOME/platform-tools:$PATH" + +yes | sdkmanager --sdk_root="$ANDROID_HOME" --licenses +sdkmanager --sdk_root="$ANDROID_HOME" \ + "platform-tools" \ + "emulator" \ + "platforms;android-36" \ + "build-tools;36.0.0" \ + "system-images;android-36.1;google_apis;arm64-v8a" + +echo no | avdmanager create avd \ + --name T3Code_API_36_1 \ + --package "system-images;android-36.1;google_apis;arm64-v8a" \ + --device pixel_9 +``` + +Add the four exports to your shell profile, start `T3Code_API_36_1` from Android Studio's Device +Manager, then build and run the development client: + +```bash +vp run android:dev +``` + +The first native build may need roughly 20 GB of free space for SDK, NDK, Gradle, and emulator +caches. In a development build on Android, Settings includes an **Android Live Update · Mock** +section for exercising the active-agents and needs-attention states without the relay. + Build and run the local iOS dev client: ```bash diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 4a0c761f2c..b395dfd3d6 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -315,6 +315,7 @@ const config: ExpoConfig = { "./plugins/withIosSceneLifecycle.cjs", "./plugins/withAndroidCleartextTraffic.cjs", "./plugins/withAndroidGradleHeap.cjs", + "./plugins/withAndroidUnifiedNdk.cjs", "./plugins/withAndroidModernPopupMenu.cjs", "./plugins/withAndroidModernAlertDialog.cjs", "./plugins/withAndroidPredictiveBackCompat.cjs", diff --git a/apps/mobile/modules/t3-agent-live-update/android/build.gradle b/apps/mobile/modules/t3-agent-live-update/android/build.gradle new file mode 100644 index 0000000000..26fafd7e73 --- /dev/null +++ b/apps/mobile/modules/t3-agent-live-update/android/build.gradle @@ -0,0 +1,20 @@ +apply plugin: 'com.android.library' +apply plugin: 'org.jetbrains.kotlin.android' + +group = 'com.t3tools.agentliveupdate' +version = '0.0.0' + +android { + namespace 'expo.modules.t3agentliveupdate' + compileSdk rootProject.ext.compileSdkVersion + + defaultConfig { + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + } +} + +dependencies { + implementation project(':expo-modules-core') + implementation 'androidx.core:core:1.17.0' +} diff --git a/apps/mobile/modules/t3-agent-live-update/android/src/main/AndroidManifest.xml b/apps/mobile/modules/t3-agent-live-update/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..3d068091a1 --- /dev/null +++ b/apps/mobile/modules/t3-agent-live-update/android/src/main/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/AgentLiveUpdateDismissReceiver.kt b/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/AgentLiveUpdateDismissReceiver.kt new file mode 100644 index 0000000000..43fdc8250f --- /dev/null +++ b/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/AgentLiveUpdateDismissReceiver.kt @@ -0,0 +1,11 @@ +package expo.modules.t3agentliveupdate + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +internal class AgentLiveUpdateDismissReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent?) { + AgentLiveUpdateManager(context.applicationContext).cancel() + } +} diff --git a/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/AgentLiveUpdateManager.kt b/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/AgentLiveUpdateManager.kt new file mode 100644 index 0000000000..66518456fc --- /dev/null +++ b/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/AgentLiveUpdateManager.kt @@ -0,0 +1,194 @@ +package expo.modules.t3agentliveupdate + +import android.Manifest +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import android.provider.Settings +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat + +internal class AgentLiveUpdateManager(private val context: Context) { + private val notificationManager = context.getSystemService(NotificationManager::class.java) + private val notificationManagerCompat = NotificationManagerCompat.from(context) + + fun ensureChannel() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + + val channel = NotificationChannel( + CHANNEL_ID, + "Agent live updates", + NotificationManager.IMPORTANCE_LOW, + ).apply { + description = "Ongoing status for active T3 Code agents" + enableVibration(false) + lockscreenVisibility = Notification.VISIBILITY_PRIVATE + setShowBadge(false) + setSound(null, null) + } + notificationManager.createNotificationChannel(channel) + } + + fun show(snapshot: LiveUpdateSnapshot): Map { + ensureChannel() + checkNotificationPermission() + + val title = snapshot.title.trim().ifEmpty { "T3 Code agents" }.take(MAX_TITLE_LENGTH) + val summary = snapshot.summary.trim().ifEmpty { "Agent activity is in progress" } + val expandedText = snapshot.lines + .asSequence() + .map(String::trim) + .filter(String::isNotEmpty) + .take(MAX_VISIBLE_LINES) + .joinToString("\n") + .ifEmpty { summary } + + val builder = NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.t3_agent_live_update) + .setContentTitle(title) + .setContentText(summary) + .setStyle(NotificationCompat.BigTextStyle().bigText(expandedText)) + .setCategory(NotificationCompat.CATEGORY_PROGRESS) + .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setOngoing(true) + .setAutoCancel(false) + .setOnlyAlertOnce(true) + .setColorized(false) + .setRequestPromotedOngoing(true) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setDeleteIntent(dismissPendingIntent()) + .addAction( + NotificationCompat.Action.Builder( + 0, + "Stop", + dismissPendingIntent(), + ).build(), + ) + + contentPendingIntent()?.let(builder::setContentIntent) + snapshot.shortCriticalText + .trim() + .take(MAX_SHORT_CRITICAL_TEXT_LENGTH) + .takeIf(String::isNotEmpty) + ?.let(builder::setShortCriticalText) + + val notification = builder.build() + notificationManagerCompat.notify(NOTIFICATION_TAG, NOTIFICATION_ID, notification) + return status(notification) + } + + fun cancel(): Map { + notificationManagerCompat.cancel(NOTIFICATION_TAG, NOTIFICATION_ID) + return status(null) + } + + fun status(): Map = status(activeNotification()) + + fun openPromotionSettings(): Map { + val promotionIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) { + Intent(Settings.ACTION_APP_NOTIFICATION_PROMOTION_SETTINGS) + } else { + appNotificationSettingsIntent() + } + promotionIntent + .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + + try { + context.startActivity(promotionIntent) + } catch (_: ActivityNotFoundException) { + context.startActivity(appNotificationSettingsIntent()) + } + return status() + } + + private fun status(notification: Notification?): Map { + val supportsPromotion = Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA + val promotable = supportsPromotion && notification?.hasPromotableCharacteristics() == true + val promoted = supportsPromotion && + notification != null && + notification.flags.and(Notification.FLAG_PROMOTED_ONGOING) != 0 + val channelImportance = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + notificationManager.getNotificationChannel(CHANNEL_ID)?.importance + ?: NotificationManager.IMPORTANCE_UNSPECIFIED + } else { + NotificationManager.IMPORTANCE_UNSPECIFIED + } + + return mapOf( + "apiLevel" to Build.VERSION.SDK_INT, + "supportsPromotion" to supportsPromotion, + "notificationsEnabled" to notificationManagerCompat.areNotificationsEnabled(), + "canPostPromotedNotifications" to ( + supportsPromotion && notificationManagerCompat.canPostPromotedNotifications() + ), + "channelImportance" to channelImportance, + "active" to (notification != null), + "promotable" to promotable, + "promoted" to promoted, + ) + } + + private fun activeNotification(): Notification? = notificationManagerCompat.activeNotifications + .firstOrNull { it.tag == NOTIFICATION_TAG && it.id == NOTIFICATION_ID } + ?.notification + + private fun checkNotificationPermission() { + if ( + Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != + PackageManager.PERMISSION_GRANTED + ) { + throw SecurityException("Notification permission is required to show an agent Live Update.") + } + } + + private fun dismissPendingIntent(): PendingIntent { + val intent = Intent(context, AgentLiveUpdateDismissReceiver::class.java).apply { + action = ACTION_DISMISS + } + return PendingIntent.getBroadcast( + context, + DISMISS_REQUEST_CODE, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + private fun contentPendingIntent(): PendingIntent? { + val intent = + context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) + return PendingIntent.getActivity( + context, + CONTENT_REQUEST_CODE, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + private fun appNotificationSettingsIntent(): Intent = + Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) + .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + + private companion object { + const val CHANNEL_ID = "t3_agent_live_updates" + const val NOTIFICATION_TAG = "t3-agent-live-update" + const val NOTIFICATION_ID = 44_001 + const val ACTION_DISMISS = "com.t3tools.agentliveupdate.action.DISMISS" + const val DISMISS_REQUEST_CODE = 44_002 + const val CONTENT_REQUEST_CODE = 44_003 + const val MAX_VISIBLE_LINES = 3 + const val MAX_TITLE_LENGTH = 80 + const val MAX_SHORT_CRITICAL_TEXT_LENGTH = 7 + } +} diff --git a/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/LiveUpdateSnapshot.kt b/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/LiveUpdateSnapshot.kt new file mode 100644 index 0000000000..ebf0f3081d --- /dev/null +++ b/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/LiveUpdateSnapshot.kt @@ -0,0 +1,18 @@ +package expo.modules.t3agentliveupdate + +import expo.modules.kotlin.records.Field +import expo.modules.kotlin.records.Record + +internal class LiveUpdateSnapshot : Record { + @Field + val title: String = "" + + @Field + val summary: String = "" + + @Field + val lines: List = emptyList() + + @Field + val shortCriticalText: String = "" +} diff --git a/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/T3AgentLiveUpdateModule.kt b/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/T3AgentLiveUpdateModule.kt new file mode 100644 index 0000000000..06dc3c08c3 --- /dev/null +++ b/apps/mobile/modules/t3-agent-live-update/android/src/main/java/expo/modules/t3agentliveupdate/T3AgentLiveUpdateModule.kt @@ -0,0 +1,38 @@ +package expo.modules.t3agentliveupdate + +import android.content.Context +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition + +class T3AgentLiveUpdateModule : Module() { + private val context: Context + get() = requireNotNull(appContext.reactContext) { + "T3AgentLiveUpdate requires an active React context." + } + + override fun definition() = ModuleDefinition { + Name("T3AgentLiveUpdate") + + AsyncFunction("ensureChannel") { + manager().apply { ensureChannel() }.status() + } + + AsyncFunction("getStatus") { + manager().status() + } + + AsyncFunction("show") { snapshot: LiveUpdateSnapshot -> + manager().show(snapshot) + } + + AsyncFunction("cancel") { + manager().cancel() + } + + AsyncFunction("openPromotionSettings") { + manager().openPromotionSettings() + } + } + + private fun manager() = AgentLiveUpdateManager(context.applicationContext) +} diff --git a/apps/mobile/modules/t3-agent-live-update/android/src/main/res/drawable/t3_agent_live_update.xml b/apps/mobile/modules/t3-agent-live-update/android/src/main/res/drawable/t3_agent_live_update.xml new file mode 100644 index 0000000000..8f1d8ac1c1 --- /dev/null +++ b/apps/mobile/modules/t3-agent-live-update/android/src/main/res/drawable/t3_agent_live_update.xml @@ -0,0 +1,10 @@ + + + + diff --git a/apps/mobile/modules/t3-agent-live-update/expo-module.config.json b/apps/mobile/modules/t3-agent-live-update/expo-module.config.json new file mode 100644 index 0000000000..aacb3a2a62 --- /dev/null +++ b/apps/mobile/modules/t3-agent-live-update/expo-module.config.json @@ -0,0 +1,6 @@ +{ + "platforms": ["android"], + "android": { + "modules": ["expo.modules.t3agentliveupdate.T3AgentLiveUpdateModule"] + } +} diff --git a/apps/mobile/modules/t3-agent-live-update/package.json b/apps/mobile/modules/t3-agent-live-update/package.json new file mode 100644 index 0000000000..d158fdf93a --- /dev/null +++ b/apps/mobile/modules/t3-agent-live-update/package.json @@ -0,0 +1,12 @@ +{ + "name": "@t3tools/mobile-agent-live-update-native", + "version": "0.0.0", + "private": true, + "expo-module": { + "android": { + "modules": [ + "expo.modules.t3agentliveupdate.T3AgentLiveUpdateModule" + ] + } + } +} diff --git a/apps/mobile/plugins/withAndroidUnifiedNdk.cjs b/apps/mobile/plugins/withAndroidUnifiedNdk.cjs new file mode 100644 index 0000000000..9eab6d7751 --- /dev/null +++ b/apps/mobile/plugins/withAndroidUnifiedNdk.cjs @@ -0,0 +1,36 @@ +const { withProjectBuildGradle } = require("expo/config-plugins"); + +const BLOCK_START = "// @generated by withAndroidUnifiedNdk"; +const BLOCK_END = "// @end withAndroidUnifiedNdk"; +const BLOCK = `${BLOCK_START} +// Expo libraries that do not declare an NDK version otherwise fall back to +// Android Gradle Plugin's default. React Native declares a newer revision, +// which makes clean local builds download and retain both multi-gigabyte NDKs. +subprojects { subproject -> + subproject.plugins.withId("com.android.application") { + subproject.android.ndkVersion = rootProject.ext.ndkVersion + } + subproject.plugins.withId("com.android.library") { + subproject.android.ndkVersion = rootProject.ext.ndkVersion + } +} +${BLOCK_END}`; + +module.exports = function withAndroidUnifiedNdk(config) { + return withProjectBuildGradle(config, (nextConfig) => { + if (nextConfig.modResults.language !== "groovy") { + throw new Error("withAndroidUnifiedNdk requires a Groovy Android project build file."); + } + + const generatedBlock = new RegExp( + `${BLOCK_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${BLOCK_END.replace( + /[.*+?^${}()|[\]\\]/g, + "\\$&", + )}\\n?`, + "g", + ); + const contents = nextConfig.modResults.contents.replace(generatedBlock, "").trimEnd(); + nextConfig.modResults.contents = `${contents}\n\n${BLOCK}\n`; + return nextConfig; + }); +}; diff --git a/apps/mobile/src/features/agent-awareness/androidLiveUpdate.ts b/apps/mobile/src/features/agent-awareness/androidLiveUpdate.ts new file mode 100644 index 0000000000..5042c334e0 --- /dev/null +++ b/apps/mobile/src/features/agent-awareness/androidLiveUpdate.ts @@ -0,0 +1,96 @@ +import { requireOptionalNativeModule } from "expo"; +import { Platform } from "react-native"; + +const MODULE_NAME = "T3AgentLiveUpdate"; + +export interface AndroidLiveUpdateStatus { + readonly apiLevel: number; + readonly supportsPromotion: boolean; + readonly notificationsEnabled: boolean; + readonly canPostPromotedNotifications: boolean; + readonly channelImportance: number; + readonly active: boolean; + readonly promotable: boolean; + readonly promoted: boolean; +} + +interface AndroidLiveUpdateSnapshot { + readonly title: string; + readonly summary: string; + readonly lines: ReadonlyArray; + readonly shortCriticalText: string; +} + +interface AndroidLiveUpdateNativeModule { + readonly ensureChannel: () => Promise; + readonly getStatus: () => Promise; + readonly show: (snapshot: AndroidLiveUpdateSnapshot) => Promise; + readonly cancel: () => Promise; + readonly openPromotionSettings: () => Promise; +} + +export type AndroidLiveUpdateMockKind = "working" | "attention"; + +const MOCK_SNAPSHOTS: Record = { + working: { + title: "3 agents working", + summary: "T3 Code is making progress", + lines: [ + "● Implementing Android Live Updates", + "● Running the mobile typecheck", + "◌ Reviewing changes from #3579", + ], + shortCriticalText: "3", + }, + attention: { + title: "1 agent needs attention", + summary: "Approval is required to continue", + lines: [ + "! Waiting for your approval", + "● Android validation is still running", + "● Two agents continue in the background", + ], + shortCriticalText: "Action", + }, +}; + +function resolveNativeModule(): AndroidLiveUpdateNativeModule | null { + if (Platform.OS !== "android") return null; + try { + return requireOptionalNativeModule(MODULE_NAME); + } catch { + return null; + } +} + +function requireNativeLiveUpdateModule(): AndroidLiveUpdateNativeModule { + const module = resolveNativeModule(); + if (module) return module; + throw new Error("Rebuild the Android development client to install the Live Update module."); +} + +export function hasAndroidLiveUpdateModule(): boolean { + return resolveNativeModule() !== null; +} + +export async function ensureAndroidLiveUpdateChannel(): Promise { + return requireNativeLiveUpdateModule().ensureChannel(); +} + +export async function getAndroidLiveUpdateStatus(): Promise { + return resolveNativeModule()?.getStatus() ?? null; +} + +export async function showAndroidLiveUpdateMock( + kind: AndroidLiveUpdateMockKind, +): Promise { + return requireNativeLiveUpdateModule().show(MOCK_SNAPSHOTS[kind]); +} + +export async function cancelAndroidLiveUpdateMock(): Promise { + return requireNativeLiveUpdateModule().cancel(); +} + +export async function openAndroidLiveUpdatePromotionSettings(): Promise { + return requireNativeLiveUpdateModule().openPromotionSettings(); +} diff --git a/apps/mobile/src/features/settings/AndroidLiveUpdatePreviewSection.tsx b/apps/mobile/src/features/settings/AndroidLiveUpdatePreviewSection.tsx new file mode 100644 index 0000000000..9ae6925d72 --- /dev/null +++ b/apps/mobile/src/features/settings/AndroidLiveUpdatePreviewSection.tsx @@ -0,0 +1,130 @@ +import * as Notifications from "expo-notifications"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { Alert, AppState, View } from "react-native"; + +import { AppText as Text } from "../../components/AppText"; +import { + cancelAndroidLiveUpdateMock, + ensureAndroidLiveUpdateChannel, + getAndroidLiveUpdateStatus, + hasAndroidLiveUpdateModule, + openAndroidLiveUpdatePromotionSettings, + showAndroidLiveUpdateMock, + type AndroidLiveUpdateMockKind, + type AndroidLiveUpdateStatus, +} from "../agent-awareness/androidLiveUpdate"; +import { SettingsRow } from "./components/SettingsRow"; +import { SettingsSection } from "./components/SettingsSection"; + +export function AndroidLiveUpdatePreviewSection() { + const [status, setStatus] = useState(null); + const [busy, setBusy] = useState(false); + const busyRef = useRef(false); + const moduleAvailable = hasAndroidLiveUpdateModule(); + + const refreshStatus = useCallback(async () => { + const nextStatus = await getAndroidLiveUpdateStatus(); + setStatus(nextStatus); + }, []); + + useEffect(() => { + void refreshStatus(); + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") void refreshStatus(); + }); + return () => subscription.remove(); + }, [refreshStatus]); + + const run = useCallback(async (operation: () => Promise) => { + if (busyRef.current) return; + busyRef.current = true; + setBusy(true); + try { + setStatus(await operation()); + } catch (cause) { + Alert.alert( + "Live Update preview unavailable", + cause instanceof Error ? cause.message : "Could not update the mock notification.", + ); + } finally { + busyRef.current = false; + setBusy(false); + } + }, []); + + const showMock = useCallback( + (kind: AndroidLiveUpdateMockKind) => { + void run(async () => { + await ensureAndroidLiveUpdateChannel(); + const currentPermission = await Notifications.getPermissionsAsync(); + const permission = currentPermission.granted + ? currentPermission + : await Notifications.requestPermissionsAsync(); + if (!permission.granted) { + throw new Error("Allow notifications to display the Android Live Update preview."); + } + return showAndroidLiveUpdateMock(kind); + }); + }, + [run], + ); + + const statusLabel = useMemo( + () => formatStatus(status, moduleAvailable), + [moduleAvailable, status], + ); + const settingsValue = status?.canPostPromotedNotifications ? "Allowed" : "Review"; + + return ( + + + showMock("working")} + /> + showMock("attention")} + /> + void run(cancelAndroidLiveUpdateMock)} + /> + void run(openAndroidLiveUpdatePromotionSettings)} + /> + + + {statusLabel} Mock data only; relay and FCM delivery are intentionally deferred. + + + ); +} + +function formatStatus(status: AndroidLiveUpdateStatus | null, moduleAvailable: boolean): string { + if (!moduleAvailable) return "Rebuild the Android development client to enable this preview."; + if (!status) return "Checking Android notification capabilities."; + if (!status.notificationsEnabled) return "Notification access is currently disabled."; + if (status.active && status.promoted) return "A promoted Live Update is active."; + if (status.active && status.promotable) { + return status.canPostPromotedNotifications + ? "A promotable ongoing notification is active." + : "The ongoing notification is active, but promotion access is disabled."; + } + if (!status.supportsPromotion) { + return "This device will use the standard ongoing-notification fallback."; + } + return status.canPostPromotedNotifications + ? "This device allows promoted Live Updates." + : "Open Promotion Settings to allow promoted Live Updates."; +} diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx index 6c67a4d89e..2a99601774 100644 --- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx @@ -38,6 +38,7 @@ import { runtime } from "../../lib/runtime"; import { useThemeColor } from "../../lib/useThemeColor"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; +import { AndroidLiveUpdatePreviewSection } from "./AndroidLiveUpdatePreviewSection"; import { SettingsRow } from "./components/SettingsRow"; import { SettingsSection } from "./components/SettingsSection"; import { SettingsSwitchRow } from "./components/SettingsSwitchRow"; @@ -125,6 +126,8 @@ function LocalSettingsRouteScreen() { + {Platform.OS === "android" && __DEV__ ? : null} + @@ -508,6 +511,8 @@ function ConfiguredSettingsRouteScreen() { + {Platform.OS === "android" && __DEV__ ? : null} +