feat(mobile): render the Android subscription widget with expo-widgets (#12046)
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
8dc07f199c
commit
e41755cf8a
23 files changed
+483
-319
No files matched your search
+47
-32
@@ -129,51 +129,66 @@ const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
// Agent activity can update many times an hour; without the
|
||||
// frequent-updates entitlement iOS throttles the update budget sooner.
|
||||
frequentUpdates: true,
|
||||
enableAndroid: true,
|
||||
widgets: [
|
||||
{
|
||||
name: "SubscriptionUsage",
|
||||
displayName: "Subscription usage",
|
||||
description: "Subscription quotas from your connected T3 Code environments.",
|
||||
configuration: {
|
||||
title: "Subscription usage",
|
||||
description:
|
||||
"Both shows Session and Weekly when available. The Lock Screen shows the tightest selected limit.",
|
||||
parameters: {
|
||||
codexPeriod: {
|
||||
title: "Codex limits",
|
||||
type: "enum",
|
||||
default: "auto",
|
||||
values: [
|
||||
{ name: "Both", value: "auto" },
|
||||
{ name: "Session", value: "session" },
|
||||
{ name: "Weekly", value: "weekly" },
|
||||
],
|
||||
},
|
||||
claudePeriod: {
|
||||
title: "Claude limits",
|
||||
type: "enum",
|
||||
default: "auto",
|
||||
values: [
|
||||
{ name: "Both", value: "auto" },
|
||||
{ name: "Session", value: "session" },
|
||||
{ name: "Weekly", value: "weekly" },
|
||||
],
|
||||
ios: {
|
||||
configuration: {
|
||||
title: "Subscription usage",
|
||||
description:
|
||||
"Both shows Session and Weekly when available. The Lock Screen shows the tightest selected limit.",
|
||||
parameters: {
|
||||
codexPeriod: {
|
||||
title: "Codex limits",
|
||||
type: "enum",
|
||||
default: "auto",
|
||||
values: [
|
||||
{ name: "Both", value: "auto" },
|
||||
{ name: "Session", value: "session" },
|
||||
{ name: "Weekly", value: "weekly" },
|
||||
],
|
||||
},
|
||||
claudePeriod: {
|
||||
title: "Claude limits",
|
||||
type: "enum",
|
||||
default: "auto",
|
||||
values: [
|
||||
{ name: "Both", value: "auto" },
|
||||
{ name: "Session", value: "session" },
|
||||
{ name: "Weekly", value: "weekly" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
supportedFamilies: [
|
||||
"systemSmall",
|
||||
"systemMedium",
|
||||
"systemLarge",
|
||||
"systemExtraLarge",
|
||||
"accessoryRectangular",
|
||||
],
|
||||
},
|
||||
android: {
|
||||
minWidth: 250,
|
||||
minHeight: 180,
|
||||
targetCellWidth: 4,
|
||||
targetCellHeight: 3,
|
||||
resizeMode: "both",
|
||||
// Embeds the layout in the APK so the widget renders before the app
|
||||
// has run once; the app replaces it with stored props on publish.
|
||||
initialLayout: "./src/widgets/SubscriptionUsage.android.tsx",
|
||||
},
|
||||
supportedFamilies: [
|
||||
"systemSmall",
|
||||
"systemMedium",
|
||||
"systemLarge",
|
||||
"systemExtraLarge",
|
||||
"accessoryRectangular",
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "AgentActivity",
|
||||
displayName: "Agent Activity",
|
||||
description: "Shows the current state of active T3 Code agents.",
|
||||
supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
|
||||
// Live Activity companion; there is no Android presentation for it.
|
||||
android: null,
|
||||
ios: { supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"] },
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'org.jetbrains.kotlin.android'
|
||||
|
||||
group = 'com.t3tools.subscriptionwidget'
|
||||
version = '0.0.0'
|
||||
|
||||
android {
|
||||
namespace 'expo.modules.t3subscriptionwidget'
|
||||
compileSdk rootProject.ext.compileSdkVersion
|
||||
defaultConfig {
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':expo-modules-core')
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application>
|
||||
<receiver android:name="expo.modules.t3subscriptionwidget.SubscriptionUsageWidget" android:enabled="@bool/t3_subscription_widget_enabled" android:exported="false" android:label="@string/t3_subscription_widget_name">
|
||||
<intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider" android:resource="@xml/t3_subscription_widget_info" />
|
||||
</receiver>
|
||||
</application>
|
||||
</manifest>
|
||||
-174
@@ -1,174 +0,0 @@
|
||||
package expo.modules.t3subscriptionwidget
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.view.View
|
||||
import android.widget.RemoteViews
|
||||
import org.json.JSONObject
|
||||
import java.text.DateFormat
|
||||
import java.util.Date
|
||||
|
||||
class SubscriptionUsageWidget : AppWidgetProvider() {
|
||||
override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
|
||||
ids.forEach { update(context, manager, it) }
|
||||
}
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
super.onReceive(context, intent)
|
||||
if (intent.action == EXPIRE) updateAll(context)
|
||||
}
|
||||
|
||||
override fun onDisabled(context: Context) {
|
||||
context.getSystemService(AlarmManager::class.java).cancel(expiryIntent(context))
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val PREFERENCES = "t3_subscription_widget"
|
||||
private const val EXPIRE = "expo.modules.t3subscriptionwidget.EXPIRE"
|
||||
|
||||
private fun expiryIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
0,
|
||||
Intent(context, SubscriptionUsageWidget::class.java).setAction(EXPIRE),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
fun updateAll(context: Context) {
|
||||
val manager = AppWidgetManager.getInstance(context)
|
||||
manager.getAppWidgetIds(ComponentName(context, SubscriptionUsageWidget::class.java))
|
||||
.forEach { update(context, manager, it) }
|
||||
}
|
||||
|
||||
private fun update(context: Context, manager: AppWidgetManager, id: Int) {
|
||||
// The receiver is disabled below 12L (values-v32/bools.xml), but the module still calls in.
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S_V2) return
|
||||
val saved = context.getSharedPreferences(PREFERENCES, 0).getString("snapshot", null)
|
||||
val snapshot = runCatching { JSONObject(saved.orEmpty()) }.getOrNull()
|
||||
val openApp = openAppIntent(context, id, snapshot)
|
||||
val providers = snapshot?.optJSONArray("providers")
|
||||
val now = System.currentTimeMillis()
|
||||
var nextExpiry = Long.MAX_VALUE
|
||||
val groups = (0 until (providers?.length() ?: 0)).mapNotNull { index ->
|
||||
val provider = providers?.optJSONObject(index) ?: return@mapNotNull null
|
||||
val windows = provider.optJSONArray("windows")
|
||||
val expiresAt = provider.optLong("expiresAt")
|
||||
if (expiresAt > now && windows != null && windows.length() > 0) {
|
||||
nextExpiry = minOf(nextExpiry, expiresAt)
|
||||
(0 until windows.length()).map { provider to windows.optJSONObject(it) }
|
||||
} else {
|
||||
listOf(provider to null)
|
||||
}
|
||||
}
|
||||
// Keep the first quota from each provider near the top of the list.
|
||||
val rows = (0 until (groups.maxOfOrNull { it.size } ?: 0)).flatMap { index ->
|
||||
groups.mapNotNull { it.getOrNull(index) }
|
||||
}
|
||||
val views = RemoteViews(context.packageName, R.layout.t3_subscription_widget)
|
||||
// Count limits only; "Open app to refresh" placeholders are not entries.
|
||||
val limits = rows.count { (_, window) -> window != null }
|
||||
// Without limits the layout's plain title stays.
|
||||
if (limits > 0) {
|
||||
views.setTextViewText(
|
||||
R.id.t3_widget_title,
|
||||
context.getString(R.string.t3_subscription_widget_title_count, limits)
|
||||
)
|
||||
views.setContentDescription(
|
||||
R.id.t3_widget_title,
|
||||
context.resources.getQuantityString(
|
||||
R.plurals.t3_subscription_widget_title_description,
|
||||
limits,
|
||||
limits
|
||||
)
|
||||
)
|
||||
}
|
||||
openApp?.let { views.setOnClickPendingIntent(R.id.t3_widget_root, it) }
|
||||
openAppIntent(context, id, snapshot, forCollection = true)?.let {
|
||||
views.setPendingIntentTemplate(R.id.t3_widget_rows, it)
|
||||
}
|
||||
val items = RemoteViews.RemoteCollectionItems.Builder()
|
||||
rows.forEachIndexed { index, (provider, window) ->
|
||||
items.addItem(index.toLong(), rowView(context, provider, window))
|
||||
}
|
||||
views.setRemoteAdapter(R.id.t3_widget_rows, items.build())
|
||||
views.setEmptyView(R.id.t3_widget_rows, R.id.t3_widget_empty)
|
||||
val checkedAt = snapshot?.optLong("checkedAt") ?: 0
|
||||
val checked = if (checkedAt > 0) {
|
||||
val formatted = DateFormat.getDateTimeInstance(
|
||||
DateFormat.SHORT,
|
||||
DateFormat.SHORT
|
||||
).format(Date(checkedAt))
|
||||
context.getString(R.string.t3_subscription_widget_last_checked, formatted)
|
||||
} else {
|
||||
context.getString(R.string.t3_subscription_widget_unknown_check)
|
||||
}
|
||||
views.setTextViewText(R.id.t3_widget_footer, checked)
|
||||
val alarms = context.getSystemService(AlarmManager::class.java)
|
||||
alarms.cancel(expiryIntent(context))
|
||||
// Inexact and non-wakeup: the timestamp remains visible if Android delays expiry.
|
||||
if (nextExpiry != Long.MAX_VALUE) {
|
||||
alarms.set(AlarmManager.RTC, nextExpiry, expiryIntent(context))
|
||||
}
|
||||
manager.updateAppWidget(id, views)
|
||||
}
|
||||
|
||||
private fun openAppIntent(
|
||||
context: Context,
|
||||
id: Int,
|
||||
snapshot: JSONObject?,
|
||||
forCollection: Boolean = false
|
||||
): PendingIntent? {
|
||||
// Target this variant's launcher so co-installed builds cannot steal the tap.
|
||||
val intent =
|
||||
context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null
|
||||
intent.action = Intent.ACTION_VIEW
|
||||
val deepLink = snapshot?.optString("url")?.takeIf { it.isNotBlank() }
|
||||
?: "t3code://settings/usage?tab=limits"
|
||||
intent.data = Uri.parse(deepLink)
|
||||
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
return PendingIntent.getActivity(
|
||||
context,
|
||||
id * 2 + if (forCollection) 1 else 0,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or if (forCollection) {
|
||||
// Collection rows use fill-in intents with an explicit app target.
|
||||
PendingIntent.FLAG_MUTABLE
|
||||
} else {
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private fun rowView(context: Context, provider: JSONObject, window: JSONObject?): RemoteViews {
|
||||
val child = RemoteViews(context.packageName, R.layout.t3_subscription_widget_row)
|
||||
val remaining = window?.optInt("remaining")?.coerceIn(0, 100)
|
||||
val detail = provider.optString("detail")
|
||||
val label = provider.optString("name")
|
||||
val windowLabel = window?.optString("label") ?: detail
|
||||
child.setTextViewText(R.id.t3_widget_label, label)
|
||||
child.setTextViewText(R.id.t3_widget_window, windowLabel)
|
||||
val percent = remaining?.let {
|
||||
context.getString(R.string.t3_subscription_widget_remaining, it)
|
||||
} ?: "—"
|
||||
child.setTextViewText(R.id.t3_widget_percent, percent)
|
||||
val visibility = if (remaining == null) View.GONE else View.VISIBLE
|
||||
child.setViewVisibility(R.id.t3_widget_progress, visibility)
|
||||
if (remaining != null) child.setProgressBar(R.id.t3_widget_progress, 100, remaining, false)
|
||||
val reset = window?.optString("reset")
|
||||
?: context.getString(R.string.t3_subscription_widget_refresh)
|
||||
child.setTextViewText(R.id.t3_widget_reset, reset)
|
||||
child.setOnClickFillInIntent(R.id.t3_widget_row, Intent())
|
||||
child.setContentDescription(
|
||||
R.id.t3_widget_row,
|
||||
"$label. $windowLabel. $percent. $reset. $detail"
|
||||
)
|
||||
return child
|
||||
}
|
||||
}
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package expo.modules.t3subscriptionwidget
|
||||
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
import org.json.JSONObject
|
||||
|
||||
class T3SubscriptionWidgetModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("T3SubscriptionWidget")
|
||||
Function("updateSnapshot") { snapshot: String ->
|
||||
val context = appContext.reactContext ?: return@Function
|
||||
JSONObject(snapshot) // Reject malformed writes before replacing the saved snapshot.
|
||||
context.getSharedPreferences(SubscriptionUsageWidget.PREFERENCES, 0)
|
||||
.edit().putString("snapshot", snapshot).apply()
|
||||
SubscriptionUsageWidget.updateAll(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<solid android:color="@color/t3_widget_background" />
|
||||
<corners android:radius="20dp" />
|
||||
</shape>
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:id="@+id/t3_widget_root" android:layout_width="match_parent" android:layout_height="match_parent"
|
||||
android:orientation="vertical" android:padding="16dp" android:background="@drawable/t3_subscription_widget_background">
|
||||
<TextView android:id="@+id/t3_widget_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/t3_subscription_widget_name" android:textStyle="bold" android:textSize="16sp" android:textColor="@color/t3_widget_foreground" android:maxLines="1" android:ellipsize="end" />
|
||||
<FrameLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1">
|
||||
<ListView android:id="@+id/t3_widget_rows" android:layout_width="match_parent" android:layout_height="match_parent" android:divider="@null" android:scrollbars="vertical" />
|
||||
<TextView android:id="@+id/t3_widget_empty" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:text="@string/t3_subscription_widget_empty" android:textSize="13sp" android:textColor="@color/t3_widget_secondary" />
|
||||
</FrameLayout>
|
||||
<TextView android:id="@+id/t3_widget_footer" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/t3_subscription_widget_open" android:textSize="10sp" android:textColor="@color/t3_widget_secondary" android:maxLines="1" android:ellipsize="end" />
|
||||
</LinearLayout>
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:id="@+id/t3_widget_row" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingTop="8dp">
|
||||
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
|
||||
<TextView android:id="@+id/t3_widget_label" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:textSize="12sp" android:textStyle="bold" android:textColor="@color/t3_widget_foreground" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/t3_widget_percent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingStart="8dp" android:textSize="12sp" android:textColor="@color/t3_widget_foreground" />
|
||||
</LinearLayout>
|
||||
<TextView android:id="@+id/t3_widget_window" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="10sp" android:textColor="@color/t3_widget_secondary" android:maxLines="1" android:ellipsize="end" />
|
||||
<ProgressBar android:id="@+id/t3_widget_progress" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="6dp" android:max="100" android:progressTint="#0284c7" />
|
||||
<TextView android:id="@+id/t3_widget_reset" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="10sp" android:textColor="@color/t3_widget_secondary" android:maxLines="1" android:ellipsize="end" />
|
||||
</LinearLayout>
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
<resources>
|
||||
<color name="t3_widget_background">#18181B</color>
|
||||
<color name="t3_widget_foreground">#FAFAFA</color>
|
||||
<color name="t3_widget_secondary">#A1A1AA</color>
|
||||
</resources>
|
||||
@@ -1,5 +0,0 @@
|
||||
<resources>
|
||||
<color name="t3_widget_background">#FAFAFA</color>
|
||||
<color name="t3_widget_foreground">#18181B</color>
|
||||
<color name="t3_widget_secondary">#52525B</color>
|
||||
</resources>
|
||||
@@ -1,15 +0,0 @@
|
||||
<resources>
|
||||
<string name="t3_subscription_widget_unknown_check">Last checked unavailable</string>
|
||||
<string name="t3_subscription_widget_name">Subscription usage</string>
|
||||
<string name="t3_subscription_widget_title_count">Subscription usage (%1$d)</string>
|
||||
<plurals name="t3_subscription_widget_title_description">
|
||||
<item quantity="one">Subscription usage, %1$d entry</item>
|
||||
<item quantity="other">Subscription usage, %1$d entries</item>
|
||||
</plurals>
|
||||
<string name="t3_subscription_widget_description">Saved subscription quotas from your T3 Code environments. Tap to refresh in the app.</string>
|
||||
<string name="t3_subscription_widget_empty">No subscription limits available. Open T3 Code to connect.</string>
|
||||
<string name="t3_subscription_widget_open">Tap to open Usage</string>
|
||||
<string name="t3_subscription_widget_refresh">Open app to refresh</string>
|
||||
<string name="t3_subscription_widget_remaining">%1$d%% remaining</string>
|
||||
<string name="t3_subscription_widget_last_checked">Last checked %1$s</string>
|
||||
</resources>
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:minWidth="250dp" android:minHeight="180dp"
|
||||
android:minResizeWidth="180dp" android:minResizeHeight="130dp"
|
||||
android:targetCellWidth="4" android:targetCellHeight="3"
|
||||
android:resizeMode="horizontal|vertical" android:widgetCategory="home_screen"
|
||||
android:updatePeriodMillis="1800000"
|
||||
android:description="@string/t3_subscription_widget_description"
|
||||
android:initialLayout="@layout/t3_subscription_widget"
|
||||
android:previewLayout="@layout/t3_subscription_widget" />
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"platforms": ["android"],
|
||||
"android": { "modules": ["expo.modules.t3subscriptionwidget.T3SubscriptionWidgetModule"] }
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'org.jetbrains.kotlin.android'
|
||||
|
||||
group = 'com.t3tools.widgetexpiry'
|
||||
version = '0.0.0'
|
||||
|
||||
android {
|
||||
namespace 'expo.modules.t3widgetexpiry'
|
||||
compileSdk rootProject.ext.compileSdkVersion
|
||||
defaultConfig {
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
}
|
||||
testOptions {
|
||||
unitTests.includeAndroidResources = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':expo-modules-core')
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
testImplementation 'org.robolectric:robolectric:4.16.1'
|
||||
}
|
||||
|
||||
tasks.withType(Test).configureEach {
|
||||
javaLauncher = javaToolchains.launcherFor {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<application>
|
||||
<receiver android:name="expo.modules.t3widgetexpiry.WidgetExpiryReceiver" android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
</application>
|
||||
</manifest>
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package expo.modules.t3widgetexpiry
|
||||
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
|
||||
class T3WidgetExpiryModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("T3WidgetExpiry")
|
||||
Function("schedule") { name: String, deadlines: List<Double> ->
|
||||
val context = appContext.reactContext ?: return@Function
|
||||
WidgetExpiryReceiver.schedule(context, name, deadlines.map { it.toLong() }.toLongArray())
|
||||
}
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package expo.modules.t3widgetexpiry
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
|
||||
/**
|
||||
* Re-renders an expo-widgets widget when a snapshot deadline passes while the app is closed.
|
||||
* The generated `<package>.<name>Provider` receiver re-runs the JS layout with the stored
|
||||
* snapshot on ACTION_APPWIDGET_UPDATE, so a deadline only needs to deliver that broadcast.
|
||||
*/
|
||||
class WidgetExpiryReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
|
||||
val stored = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE)
|
||||
for ((name, value) in stored.all) {
|
||||
val deadlines = (value as? String)?.split(',')?.mapNotNull { it.toLongOrNull() }
|
||||
?.toLongArray() ?: continue
|
||||
refresh(context, name)
|
||||
schedule(context, name, deadlines)
|
||||
}
|
||||
return
|
||||
}
|
||||
val name = intent.getStringExtra(EXTRA_NAME) ?: return
|
||||
val remaining = intent.getLongArrayExtra(EXTRA_DEADLINES) ?: LongArray(0)
|
||||
refresh(context, name)
|
||||
schedule(context, name, remaining)
|
||||
}
|
||||
|
||||
private fun refresh(context: Context, name: String) {
|
||||
val provider = providerComponent(context, name)
|
||||
val ids = AppWidgetManager.getInstance(context).getAppWidgetIds(provider)
|
||||
if (ids.isNotEmpty()) {
|
||||
context.sendBroadcast(
|
||||
Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
|
||||
.setComponent(provider)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val EXTRA_NAME = "expo.modules.t3widgetexpiry.NAME"
|
||||
private const val EXTRA_DEADLINES = "expo.modules.t3widgetexpiry.DEADLINES"
|
||||
private const val PREFERENCES = "expo.modules.t3widgetexpiry.DEADLINES"
|
||||
|
||||
/** Arms one inexact, non-wakeup alarm for the next future deadline and carries the rest. */
|
||||
fun schedule(context: Context, name: String, deadlines: LongArray) {
|
||||
val alarms = context.getSystemService(AlarmManager::class.java)
|
||||
val now = System.currentTimeMillis()
|
||||
val pending = deadlines.filter { it > now }.sorted()
|
||||
val stored = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE).edit()
|
||||
if (pending.isEmpty()) {
|
||||
stored.remove(name)
|
||||
} else {
|
||||
stored.putString(name, pending.joinToString(","))
|
||||
}
|
||||
stored.apply()
|
||||
val intent = Intent(context, WidgetExpiryReceiver::class.java)
|
||||
.setAction("expo.modules.t3widgetexpiry.EXPIRE.$name")
|
||||
.putExtra(EXTRA_NAME, name)
|
||||
.putExtra(EXTRA_DEADLINES, pending.drop(1).toLongArray())
|
||||
val operation = PendingIntent.getBroadcast(
|
||||
context,
|
||||
0,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
alarms.cancel(operation)
|
||||
val next = pending.firstOrNull() ?: return
|
||||
alarms.set(AlarmManager.RTC, next, operation)
|
||||
}
|
||||
|
||||
// Mirrors expo-widgets' widgetProviderComponentName for the generated provider class.
|
||||
private fun providerComponent(context: Context, name: String) =
|
||||
ComponentName(context.packageName, "${context.packageName}.${name}Provider")
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package expo.modules.t3widgetexpiry
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [24, 36], manifest = Config.NONE)
|
||||
class WidgetExpiryReceiverTest {
|
||||
@Test
|
||||
fun bootRestoresTheNextAlarmFromPersistedDeadlines() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val alarms = context.getSystemService(AlarmManager::class.java)
|
||||
val deadlines = longArrayOf(
|
||||
System.currentTimeMillis() + 60000,
|
||||
System.currentTimeMillis() + 120000
|
||||
)
|
||||
WidgetExpiryReceiver.schedule(context, "SubscriptionUsage", deadlines)
|
||||
val scheduled = shadowOf(alarms).scheduledAlarms.single()
|
||||
alarms.cancel(requireNotNull(scheduled.operation))
|
||||
assertTrue(shadowOf(alarms).scheduledAlarms.isEmpty())
|
||||
|
||||
WidgetExpiryReceiver().onReceive(context, Intent(Intent.ACTION_BOOT_COMPLETED))
|
||||
|
||||
assertEquals(deadlines[0], shadowOf(alarms).scheduledAlarms.single().triggerAtTime)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bootDoesNotRestoreCancelledDeadlines() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
WidgetExpiryReceiver.schedule(
|
||||
context,
|
||||
"SubscriptionUsage",
|
||||
longArrayOf(System.currentTimeMillis() + 60000)
|
||||
)
|
||||
WidgetExpiryReceiver.schedule(context, "SubscriptionUsage", longArrayOf())
|
||||
|
||||
WidgetExpiryReceiver().onReceive(context, Intent(Intent.ACTION_BOOT_COMPLETED))
|
||||
|
||||
assertTrue(
|
||||
shadowOf(context.getSystemService(AlarmManager::class.java)).scheduledAlarms.isEmpty()
|
||||
)
|
||||
assertTrue(
|
||||
context.getSharedPreferences(
|
||||
"expo.modules.t3widgetexpiry.DEADLINES",
|
||||
Context.MODE_PRIVATE
|
||||
).all.isEmpty()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"platforms": ["android"],
|
||||
"android": { "modules": ["expo.modules.t3widgetexpiry.T3WidgetExpiryModule"] }
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
vi.mock("@expo/ui/jetpack-compose", () => ({
|
||||
Button: "Button",
|
||||
Column: "Column",
|
||||
LinearProgressIndicator: "LinearProgressIndicator",
|
||||
Text: "Text",
|
||||
getMaterialColors: ({ scheme }: { scheme: string }) => ({
|
||||
surface: `${scheme}-surface`,
|
||||
onSurface: `${scheme}-onSurface`,
|
||||
onSurfaceVariant: `${scheme}-onSurfaceVariant`,
|
||||
surfaceVariant: `${scheme}-surfaceVariant`,
|
||||
primary: `${scheme}-primary`,
|
||||
error: `${scheme}-error`,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@expo/ui/jetpack-compose/modifiers", () => ({
|
||||
fillMaxSize: () => "fillMaxSize",
|
||||
fillMaxWidth: () => "fillMaxWidth",
|
||||
height: (value: number) => ({ height: value }),
|
||||
padding: (...values: number[]) => ({ padding: values }),
|
||||
paddingAll: (value: number) => ({ paddingAll: value }),
|
||||
}));
|
||||
|
||||
vi.mock("expo-widgets", () => ({
|
||||
createWidget: vi.fn((name: string, layout: unknown) => ({ layout, name })),
|
||||
}));
|
||||
|
||||
import { SubscriptionUsage } from "./SubscriptionUsage.android";
|
||||
import type { SubscriptionUsageSnapshot } from "./subscriptionUsageSnapshot";
|
||||
|
||||
const now = Date.parse("2026-09-05T12:00:00.000Z");
|
||||
const provider = {
|
||||
name: "Codex",
|
||||
detail: "Subscription remaining",
|
||||
windows: [
|
||||
{ kind: "session", label: "5 hours", remaining: 60, reset: "Next reset Sep 5, 5:00 PM" },
|
||||
{ kind: "weekly", label: "Weekly", remaining: 8, reset: "Next reset Sep 9, 9:00 AM" },
|
||||
],
|
||||
expiresAt: now + 60_000,
|
||||
totalWindows: 2,
|
||||
} satisfies SubscriptionUsageSnapshot["providers"][number];
|
||||
const snapshot = {
|
||||
checkedAt: now,
|
||||
url: "t3code-dev://settings/usage?tab=limits",
|
||||
providers: [provider, { ...provider, name: "Claude" }],
|
||||
} satisfies SubscriptionUsageSnapshot;
|
||||
|
||||
function render(props: SubscriptionUsageSnapshot, colorScheme: "light" | "dark" = "dark") {
|
||||
vi.setSystemTime(now);
|
||||
return JSON.stringify(SubscriptionUsage(props, { colorScheme, configuration: undefined }));
|
||||
}
|
||||
|
||||
describe("SubscriptionUsage Android layout", () => {
|
||||
it("renders each window with its remaining share, bar, and reset", () => {
|
||||
const tree = render(snapshot);
|
||||
expect(tree).toContain("5 hours · 60% left");
|
||||
expect(tree).toContain('"progress":0.6');
|
||||
expect(tree).toContain("Next reset Sep 5, 5:00 PM");
|
||||
expect(tree).toContain('"progress":0.08');
|
||||
expect(tree).toContain('"color":"dark-error"');
|
||||
expect(tree).toContain("As of ");
|
||||
});
|
||||
|
||||
it("drops the bars and asks for a refresh once the snapshot expires", () => {
|
||||
const tree = render({
|
||||
...snapshot,
|
||||
providers: [{ ...provider, expiresAt: now - 1 }],
|
||||
});
|
||||
expect(tree).toContain("Open T3 to refresh");
|
||||
expect(tree).not.toContain("LinearProgressIndicator");
|
||||
expect(tree).not.toContain("more in T3");
|
||||
});
|
||||
|
||||
it("counts the quotas that did not fit", () => {
|
||||
const tree = render({ ...snapshot, providers: [{ ...provider, totalWindows: 5 }] });
|
||||
expect(tree).toContain("3 more in T3");
|
||||
});
|
||||
|
||||
it("keeps quotas without an expiry deadline visible", () => {
|
||||
const tree = render({ ...snapshot, providers: [{ ...provider, expiresAt: 0 }] });
|
||||
expect(tree).toContain("5 hours · 60% left");
|
||||
expect(tree).not.toContain("Open T3 to refresh");
|
||||
});
|
||||
|
||||
it("invites connecting when nothing has been checked", () => {
|
||||
const tree = render({ checkedAt: 0, providers: [] }, "light");
|
||||
expect(tree).toContain("Tap to connect in T3");
|
||||
expect(tree).not.toContain("As of ");
|
||||
expect(tree).toContain('"containerColor":"light-surface"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import {
|
||||
Button,
|
||||
Column,
|
||||
getMaterialColors,
|
||||
LinearProgressIndicator,
|
||||
Text,
|
||||
} from "@expo/ui/jetpack-compose";
|
||||
import {
|
||||
fillMaxSize,
|
||||
fillMaxWidth,
|
||||
height,
|
||||
padding,
|
||||
paddingAll,
|
||||
} from "@expo/ui/jetpack-compose/modifiers";
|
||||
import { createWidget, type WidgetEnvironment } from "expo-widgets";
|
||||
|
||||
import type { SubscriptionUsageSnapshot as SubscriptionUsageProps } from "./subscriptionUsageSnapshot";
|
||||
|
||||
export function SubscriptionUsage(props: SubscriptionUsageProps, environment: WidgetEnvironment) {
|
||||
"widget";
|
||||
// The widget runtime evaluates this function without the app's module scope.
|
||||
// Android has no timeline, so freshness is decided on every render; the
|
||||
// expiry alarm and each tap trigger one while the app is closed.
|
||||
const now = Date.now();
|
||||
// The 4x3 default cell fits two quotas per provider with their reset text.
|
||||
const limit = 2;
|
||||
const colors = getMaterialColors({
|
||||
scheme: environment.colorScheme === "dark" ? "dark" : "light",
|
||||
});
|
||||
const muted = colors.onSurfaceVariant;
|
||||
const providers = props.providers ?? [
|
||||
{ name: "Codex", detail: "Open T3 to connect", windows: [], expiresAt: 0, totalWindows: 0 },
|
||||
{ name: "Claude", detail: "Open T3 to connect", windows: [], expiresAt: 0, totalWindows: 0 },
|
||||
];
|
||||
return (
|
||||
// The card is one Button so a tap reaches the app's interaction listener,
|
||||
// which opens props.url. expo-widgets has no Android counterpart to widgetURL.
|
||||
<Button
|
||||
colors={{ containerColor: colors.surface }}
|
||||
modifiers={[fillMaxSize()]}
|
||||
onClick={() => {}}
|
||||
>
|
||||
<Column modifiers={[fillMaxSize(), paddingAll(16)]}>
|
||||
{providers.map((provider, index) => {
|
||||
const stale =
|
||||
provider.windows.length > 0 && provider.expiresAt > 0 && now >= provider.expiresAt;
|
||||
const shown = stale ? [] : provider.windows.slice(0, limit);
|
||||
const hidden = stale ? 0 : (provider.totalWindows ?? provider.windows.length) - limit;
|
||||
return (
|
||||
<Column
|
||||
key={provider.name}
|
||||
modifiers={[fillMaxWidth(), padding(0, index === 0 ? 0 : 10, 0, 0)]}
|
||||
>
|
||||
<Text
|
||||
color={colors.onSurface}
|
||||
maxLines={1}
|
||||
style={{ fontSize: 13, fontWeight: "bold" }}
|
||||
>
|
||||
{provider.name}
|
||||
</Text>
|
||||
{shown.length === 0 ? (
|
||||
<Text color={muted} maxLines={1} style={{ fontSize: 11 }}>
|
||||
{stale ? "Open T3 to refresh" : provider.detail}
|
||||
</Text>
|
||||
) : null}
|
||||
{shown.map((window) => {
|
||||
const low = window.remaining <= 10;
|
||||
return (
|
||||
<Column key={window.label} modifiers={[fillMaxWidth(), padding(0, 4, 0, 0)]}>
|
||||
<Text
|
||||
color={low ? colors.error : colors.onSurface}
|
||||
maxLines={1}
|
||||
style={{ fontSize: 11 }}
|
||||
>
|
||||
{`${window.label} · ${window.remaining}% left`}
|
||||
</Text>
|
||||
<Column modifiers={[fillMaxWidth(), padding(0, 3, 0, 3)]}>
|
||||
<LinearProgressIndicator
|
||||
progress={window.remaining / 100}
|
||||
color={low ? colors.error : colors.primary}
|
||||
trackColor={colors.surfaceVariant}
|
||||
modifiers={[fillMaxWidth(), height(6)]}
|
||||
/>
|
||||
</Column>
|
||||
<Text color={muted} maxLines={1} style={{ fontSize: 10 }}>
|
||||
{window.reset}
|
||||
</Text>
|
||||
</Column>
|
||||
);
|
||||
})}
|
||||
{hidden > 0 ? (
|
||||
<Text color={muted} maxLines={1} style={{ fontSize: 10 }}>
|
||||
{`${hidden} more in T3`}
|
||||
</Text>
|
||||
) : null}
|
||||
</Column>
|
||||
);
|
||||
})}
|
||||
<Text
|
||||
color={muted}
|
||||
maxLines={1}
|
||||
style={{ fontSize: 10 }}
|
||||
modifiers={[padding(0, 10, 0, 0)]}
|
||||
>
|
||||
{props.checkedAt
|
||||
? `As of ${new Date(props.checkedAt).toLocaleString(undefined, { hour: "numeric", minute: "2-digit", month: "short", day: "numeric" })}`
|
||||
: "Tap to connect in T3"}
|
||||
</Text>
|
||||
</Column>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export default createWidget("SubscriptionUsage", SubscriptionUsage);
|
||||
@@ -1,8 +1,33 @@
|
||||
import { requireOptionalNativeModule } from "expo";
|
||||
import * as Linking from "expo-linking";
|
||||
import type { SubscriptionUsageSnapshot } from "./subscriptionUsageSnapshot";
|
||||
|
||||
export function publishSubscriptionUsage(snapshot: SubscriptionUsageSnapshot) {
|
||||
requireOptionalNativeModule<{ updateSnapshot: (snapshot: string) => void }>(
|
||||
"T3SubscriptionWidget",
|
||||
)?.updateSnapshot(JSON.stringify(snapshot));
|
||||
let tapUrl: string | undefined;
|
||||
let listening = false;
|
||||
|
||||
export async function publishSubscriptionUsage(snapshot: SubscriptionUsageSnapshot) {
|
||||
if (!requireOptionalNativeModule("ExpoWidgets")) return;
|
||||
const [{ default: widget }, { addUserInteractionListener }] = await Promise.all([
|
||||
import("./SubscriptionUsage"),
|
||||
import("expo-widgets"),
|
||||
]);
|
||||
tapUrl = snapshot.url;
|
||||
if (!listening) {
|
||||
// expo-widgets has no Android counterpart to widgetURL: the card is a
|
||||
// button whose tap is delivered to this process, so opening the app needs
|
||||
// a live JS runtime.
|
||||
listening = true;
|
||||
addUserInteractionListener((event) => {
|
||||
if (event.source === "SubscriptionUsage" && tapUrl) void Linking.openURL(tapUrl);
|
||||
});
|
||||
}
|
||||
widget.updateSnapshot(snapshot);
|
||||
// Android has no timeline; an alarm re-renders the stored snapshot at each
|
||||
// deadline so stale readings flip to "Open T3 to refresh" unattended.
|
||||
requireOptionalNativeModule<{ schedule: (name: string, deadlines: number[]) => void }>(
|
||||
"T3WidgetExpiry",
|
||||
)?.schedule(
|
||||
"SubscriptionUsage",
|
||||
snapshot.providers.map((provider) => provider.expiresAt).filter((at) => at > 0),
|
||||
);
|
||||
}
|
||||
+3
-3
@@ -120,9 +120,9 @@ settings section when you no longer need it.
|
||||
## Subscription usage widget
|
||||
|
||||
Add **Subscription usage** from your iOS or Android widget gallery to see remaining Codex and
|
||||
Claude quotas. Tap it to open **Usage → Limits**. On iOS, use **Edit Widget** to choose Session,
|
||||
Weekly, or both for each provider. Reopen T3 to refresh expired readings. The Android widget
|
||||
requires Android 12L or later.
|
||||
Claude quotas. Tap it to open **Usage → Limits**; on Android this works while T3 is running in
|
||||
the background, otherwise open the app from the launcher. On iOS, use **Edit Widget** to choose
|
||||
Session, Weekly, or both for each provider. Reopen T3 to refresh expired readings.
|
||||
|
||||
## Keyboard shortcuts
|
||||
|
||||
|
||||
Reference in new issue
Block a user