Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/mobile/knip.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"$schema": "https://unpkg.com/knip@5/schema.json",
"entry": ["src/app/**/*.{ts,tsx}"],
"entry": ["src/app/**/*.{ts,tsx}", "src/glanceable-android/register.ts"],
"project": ["src/**/*.{ts,tsx}"],
"ignoreDependencies": [
"expo-updates",
Expand Down
22 changes: 22 additions & 0 deletions apps/mobile/modules/active-agents-live-update/android/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
apply plugin: 'com.android.library'

group = 'com.kilocode.activeagentsliveupdate'
version = '0.1.0'

def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
apply from: expoModulesCorePlugin
applyKotlinExpoModulesCorePlugin()
useCoreDependencies()
useExpoPublishing()
useDefaultAndroidSdkVersions()

android {
namespace "com.kilocode.activeagentsliveupdate"
defaultConfig {
versionCode 1
versionName "0.1.0"
}
lintOptions {
abortOnError false
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application>
<receiver
android:name="com.kilocode.activeagentsliveupdate.ActiveAgentsDeadlineReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
</application>
</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package com.kilocode.activeagentsliveupdate

import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import java.util.UUID

/** One OS-owned widget deadline; an old delivery never changes a newer snapshot. */
class ActiveAgentsDeadlineReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED -> restoreWidgetDeadline(context)
else -> expire(context, intent)
}
}

companion object {
private const val STORE = "active-agents-deadlines"
private const val SNAPSHOT = "widget-snapshot"
private const val WIDGET = "widget-expiry"
private const val NOTIFICATION = "notification-expiry"
private const val GENERATION = "generation"
private const val DEADLINE = "deadline"
internal const val NOTIFICATION_ID = 1001

@Synchronized
fun setWidgetSnapshot(context: Context, snapshot: String, expiresAt: Long) {
replace(context, WIDGET, expiresAt, snapshot)
}

fun getWidgetSnapshot(context: Context): String? =
context.getSharedPreferences(STORE, Context.MODE_PRIVATE).getString(SNAPSHOT, null)

/** Notification.Builder.setTimeoutAfter is unavailable on supported API 24–25. */
@Synchronized
fun setLegacyNotificationTimeout(context: Context, timeoutMs: Long) {
val deadline = if (timeoutMs > 0) System.currentTimeMillis() + timeoutMs else 0
replace(context, NOTIFICATION, deadline)
}

private fun replace(context: Context, action: String, deadline: Long, snapshot: String? = null) {
val generation = UUID.randomUUID().toString()
val preferences = context.getSharedPreferences(STORE, Context.MODE_PRIVATE)
val editor = preferences.edit()
.putLong(action, deadline)
.putString("$action-$GENERATION", generation)
if (snapshot != null) editor.putString(SNAPSHOT, snapshot)
// Commit before returning across the bridge so process exit cannot lose a blank.
check(editor.commit()) { "Cannot persist the active agents deadline" }

val intent = Intent(context, ActiveAgentsDeadlineReceiver::class.java)
.setAction(action)
.putExtra(DEADLINE, deadline)
.putExtra(GENERATION, generation)
val operation = PendingIntent.getBroadcast(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val alarms = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarms.cancel(operation)
if (deadline <= System.currentTimeMillis()) {
operation.cancel()
return
}
if (Build.VERSION.SDK_INT >= 31) {
// No exact-alarm permission: Android can defer delivery while idle.
alarms.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, deadline, operation)
} else {
alarms.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, deadline, operation)
}
}

@Synchronized
private fun restoreWidgetDeadline(context: Context) {
val preferences = context.getSharedPreferences(STORE, Context.MODE_PRIVATE)
val deadline = preferences.getLong(WIDGET, 0)
// Privacy and signed-out snapshots persist a zero deadline in the same commit.
if (deadline <= 0) return
// Keep the original expiry and snapshot; replace only the alarm generation.
replace(context, WIDGET, deadline)
// Also handle an expiry that passed while down or during alarm restoration.
expire(context, Intent(WIDGET)
.putExtra(DEADLINE, deadline)
.putExtra(GENERATION, preferences.getString("$WIDGET-$GENERATION", null)))
}

@Synchronized
private fun expire(context: Context, intent: Intent) {
val action = intent.action ?: return
if (action != WIDGET && action != NOTIFICATION) return
val preferences = context.getSharedPreferences(STORE, Context.MODE_PRIVATE)
val deadline = preferences.getLong(action, 0)
if (deadline <= 0 || deadline > System.currentTimeMillis() ||
deadline != intent.getLongExtra(DEADLINE, 0) ||
preferences.getString("$action-$GENERATION", null) != intent.getStringExtra(GENERATION)
) return

check(preferences.edit().remove(action).remove("$action-$GENERATION").commit()) {
"Cannot consume the active agents deadline"
}
if (action == NOTIFICATION) {
val notifications = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notifications.cancel(NOTIFICATION_ID)
return
}

// The installed widget provider starts its durable headless worker for each instance.
// That handler re-reads the stored snapshot, including any intervening privacy blank.
val provider = ComponentName(context.packageName, "${context.packageName}.widget.ActiveAgentsWidget")
val ids = AppWidgetManager.getInstance(context).getAppWidgetIds(provider)
if (ids.isEmpty()) return
context.sendBroadcast(
Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
.setComponent(provider)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package com.kilocode.activeagentsliveupdate

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition

/**
* Local Expo module for the Android aggregate ongoing notification.
*
* The JS side owns the translated copy and the revision guard; this module owns
* the fixed notification id, the dedicated `active-agents` channel (default
* importance, silent, no heads-up), and the API 36.1+ promotion gate.
*/
class ActiveAgentsLiveUpdateModule : Module() {
override fun definition() = ModuleDefinition {
Name("ActiveAgentsLiveUpdate")

Function("isPromotionCapable") {
isPromotionCapable()
}

Function("start") { title: String, text: String, compactText: String?, promotion: Boolean ->
post(title, text, compactText, promotion, 0)
}

Function("update") { title: String, text: String, compactText: String?, promotion: Boolean, timeoutMs: Double ->
post(title, text, compactText, promotion, timeoutMs.toLong())
}

Function("end") {
dismiss()
}

Function("setWidgetSnapshot") { snapshot: String, expiresAt: Double ->
ActiveAgentsDeadlineReceiver.setWidgetSnapshot(context, snapshot, expiresAt.toLong())
}

Function("getWidgetSnapshot") {
ActiveAgentsDeadlineReceiver.getWidgetSnapshot(context)
}
}

private val context: Context
get() = appContext.reactContext ?: appContext.applicationContext

private val notificationManager: NotificationManager
get() = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

private val notificationState
get() = context.getSharedPreferences("active_agents_notification", Context.MODE_PRIVATE)

private fun smallIconId(): Int =
context.resources.getIdentifier("notification_icon", "drawable", context.packageName)

private fun isPromotionCapable(): Boolean =
Build.VERSION.SDK_INT >= 36 &&
Build.VERSION.SDK_INT_FULL >= 36_001_000 &&
notificationManager.canPostPromotedNotifications()

private fun ensureChannel(title: String) {
if (Build.VERSION.SDK_INT < 26) {
return
}
if (notificationManager.getNotificationChannel(CHANNEL_ID) != null) {
return
}
val channel = NotificationChannel(CHANNEL_ID, title, NotificationManager.IMPORTANCE_DEFAULT)
channel.setSound(null, null)
channel.enableVibration(false)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
notificationManager.createNotificationChannel(channel)
}

private fun newBuilder(title: String): Notification.Builder {
if (Build.VERSION.SDK_INT >= 26) {
ensureChannel(title)
return Notification.Builder(context, CHANNEL_ID)
}
return legacyBuilder()
}

@Suppress("DEPRECATION")
private fun legacyBuilder(): Notification.Builder = Notification.Builder(context)

/** A PendingIntent that deep-links the app to the Open agents route. */
private fun openAgentsPendingIntent(): PendingIntent {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(OPEN_AGENTS_DEEP_LINK)).apply {
setPackage(context.packageName)
}
return PendingIntent.getActivity(
context,
OPEN_AGENTS_REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}

private fun post(title: String, text: String, compactText: String?, promotion: Boolean, timeoutMs: Long) {
val builder = newBuilder(title)
.setSmallIcon(smallIconId())
.setContentTitle(title)
.setContentText(text)
.setContentIntent(openAgentsPendingIntent())
.setOngoing(true)
.setOnlyAlertOnce(true)
.setSound(null)
.setCategory(Notification.CATEGORY_STATUS)

// API 36.1+ Live Update: promote only when the device reports the capability.
// setRequestPromotedOngoing does not exist; use the documented flag setter.
if (promotion && isPromotionCapable()) {
builder.setFlag(Notification.FLAG_PROMOTED_ONGOING, true)
Comment thread
iscekic marked this conversation as resolved.
builder.setShortCriticalText(compactText)
builder.setStyle(Notification.ProgressStyle())
}

// Commit before arming a timeout so process exit cannot lose cancellation state.
if (timeoutMs > 0) {
check(notificationState.edit().putBoolean(HAS_TIMEOUT, true).commit()) {
"Cannot persist the active agents notification timeout"
}
}

if (Build.VERSION.SDK_INT >= 26) {
// Ordinary updates must retain the notification so onlyAlertOnce suppresses repeat alerts.
if (timeoutMs <= 0 && notificationState.getBoolean(HAS_TIMEOUT, false)) {
notificationManager.cancel(ActiveAgentsDeadlineReceiver.NOTIFICATION_ID)
}
builder.setTimeoutAfter(timeoutMs.coerceAtLeast(0))
} else {
ActiveAgentsDeadlineReceiver.setLegacyNotificationTimeout(context, timeoutMs)
}
notificationManager.notify(ActiveAgentsDeadlineReceiver.NOTIFICATION_ID, builder.build())
if (timeoutMs <= 0) {
notificationState.edit().putBoolean(HAS_TIMEOUT, false).apply()
}
}

private fun dismiss() {
if (Build.VERSION.SDK_INT < 26) {
ActiveAgentsDeadlineReceiver.setLegacyNotificationTimeout(context, 0)
}
notificationManager.cancel(ActiveAgentsDeadlineReceiver.NOTIFICATION_ID)
notificationState.edit().remove(HAS_TIMEOUT).apply()
}

private companion object {
const val HAS_TIMEOUT = "has_timeout"
const val CHANNEL_ID = "active-agents"
const val OPEN_AGENTS_DEEP_LINK = "kiloapp:///cloud/sessions"
const val OPEN_AGENTS_REQUEST_CODE = 1002
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
"modules": []
},
"android": {
"modules": []
"modules": ["com.kilocode.activeagentsliveupdate.ActiveAgentsLiveUpdateModule"]
}
}
Loading