Compare commits

...
15 changed files with 631 additions and 0 deletions

No files matched your search

+44
View File
@@ -28,6 +28,50 @@ 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.
The mock preview is entirely local. It does not require T3 Connect, a hosted relay, Clerk
configuration, Firebase/FCM credentials, or a connected T3 Code server. Remote delivery and
background reconciliation require the separate T3 Connect infrastructure.
Build and run the local iOS dev client:
```bash
+1
View File
@@ -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",
@@ -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'
}
@@ -0,0 +1,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />
<application>
<receiver
android:name="expo.modules.t3agentliveupdate.AgentLiveUpdateDismissReceiver"
android:exported="false" />
</application>
</manifest>
@@ -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()
}
}
@@ -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<String, Any> {
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()
}
fun cancel(): Map<String, Any> {
notificationManagerCompat.cancel(NOTIFICATION_TAG, NOTIFICATION_ID)
return status(null)
}
fun status(): Map<String, Any> = status(activeNotification())
fun openPromotionSettings(): Map<String, Any> {
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<String, Any> {
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
}
}
@@ -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<String> = emptyList()
@Field
val shortCriticalText: String = ""
}
@@ -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)
}
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M8,5.5L1.5,12 8,18.5 9.4,17.1 4.3,12 9.4,6.9zM16,5.5L14.6,6.9 19.7,12 14.6,17.1 16,18.5 22.5,12z" />
</vector>
@@ -0,0 +1,6 @@
{
"platforms": ["android"],
"android": {
"modules": ["expo.modules.t3agentliveupdate.T3AgentLiveUpdateModule"]
}
}
@@ -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"
]
}
}
}
@@ -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;
});
};
@@ -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<string>;
readonly shortCriticalText: string;
}
interface AndroidLiveUpdateNativeModule {
readonly ensureChannel: () => Promise<AndroidLiveUpdateStatus>;
readonly getStatus: () => Promise<AndroidLiveUpdateStatus>;
readonly show: (snapshot: AndroidLiveUpdateSnapshot) => Promise<AndroidLiveUpdateStatus>;
readonly cancel: () => Promise<AndroidLiveUpdateStatus>;
readonly openPromotionSettings: () => Promise<AndroidLiveUpdateStatus>;
}
export type AndroidLiveUpdateMockKind = "working" | "attention";
const MOCK_SNAPSHOTS: Record<AndroidLiveUpdateMockKind, AndroidLiveUpdateSnapshot> = {
working: {
title: "3 agents working",
summary: "T3 Code is making progress",
lines: [
"● Implementing Android Live Updates",
"● Running the mobile typecheck",
"◌ Reviewing recent agent changes",
],
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<AndroidLiveUpdateNativeModule>(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<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().ensureChannel();
}
export async function getAndroidLiveUpdateStatus(): Promise<AndroidLiveUpdateStatus | null> {
return resolveNativeModule()?.getStatus() ?? null;
}
export async function showAndroidLiveUpdateMock(
kind: AndroidLiveUpdateMockKind,
): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().show(MOCK_SNAPSHOTS[kind]);
}
export async function cancelAndroidLiveUpdateMock(): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().cancel();
}
export async function openAndroidLiveUpdatePromotionSettings(): Promise<AndroidLiveUpdateStatus> {
return requireNativeLiveUpdateModule().openPromotionSettings();
}
@@ -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<AndroidLiveUpdateStatus | null>(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<AndroidLiveUpdateStatus>) => {
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 (
<View className="gap-3">
<SettingsSection title="Android Live Update · Mock">
<SettingsRow
disabled={busy || !moduleAvailable}
icon="bolt.circle"
label="Show Active Agents"
onPress={() => showMock("working")}
/>
<SettingsRow
disabled={busy || !moduleAvailable}
icon="exclamationmark.triangle"
label="Show Needs Attention"
onPress={() => showMock("attention")}
/>
<SettingsRow
disabled={busy || !moduleAvailable || !status?.active}
icon="stop.fill"
label="End Mock Update"
onPress={() => void run(cancelAndroidLiveUpdateMock)}
/>
<SettingsRow
disabled={busy || !moduleAvailable}
icon="gearshape"
label="Promotion Settings"
value={settingsValue}
onPress={() => void run(openAndroidLiveUpdatePromotionSettings)}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
{statusLabel} Mock data only; relay and FCM delivery are intentionally deferred.
</Text>
</View>
);
}
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.";
}
@@ -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() {
<ArchivedThreadsSettingsSection />
{Platform.OS === "android" && __DEV__ ? <AndroidLiveUpdatePreviewSection /> : null}
<AppSettingsSection />
</ScrollView>
</View>
@@ -508,6 +511,8 @@ function ConfiguredSettingsRouteScreen() {
<ArchivedThreadsSettingsSection />
{Platform.OS === "android" && __DEV__ ? <AndroidLiveUpdatePreviewSection /> : null}
<AppSettingsSection />
</ScrollView>
</View>