Skip to content
TypeScript

feat(mobile): add pooled subscription usage widgets (#11506)

Matthew Feroz17f8e2a8acba
diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts
index f34f9c4b39d..5daaa64a798 100644
--- a/apps/mobile/app.config.ts
+++ b/apps/mobile/app.config.ts
@@ -130,6 +130,45 @@ const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
// frequent-updates entitlement iOS throttles the update budget sooner.
frequentUpdates: 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" },
+ ],
+ },
+ },
+ },
+ supportedFamilies: [
+ "systemSmall",
+ "systemMedium",
+ "systemLarge",
+ "systemExtraLarge",
+ "accessoryRectangular",
+ ],
+ },
{
name: "AgentActivity",
displayName: "Agent Activity",
diff --git a/apps/mobile/modules/t3-subscription-widget/android/build.gradle b/apps/mobile/modules/t3-subscription-widget/android/build.gradle
new file mode 100644
index 00000000000..7de5052417c
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/build.gradle
@@ -0,0 +1,18 @@
+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')
+}
diff --git a/apps/mobile/modules/t3-subscription-widget/android/src/main/AndroidManifest.xml b/apps/mobile/modules/t3-subscription-widget/android/src/main/AndroidManifest.xml
new file mode 100644
index 00000000000..e66f03cffae
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/src/main/AndroidManifest.xml
@@ -0,0 +1,8 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <application>
+ <receiver android:name="expo.modules.t3subscriptionwidget.SubscriptionUsageWidget" 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>
diff --git a/apps/mobile/modules/t3-subscription-widget/android/src/main/java/expo/modules/t3subscriptionwidget/SubscriptionUsageWidget.kt b/apps/mobile/modules/t3-subscription-widget/android/src/main/java/expo/modules/t3subscriptionwidget/SubscriptionUsageWidget.kt
new file mode 100644
index 00000000000..ef33a5d7c25
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/src/main/java/expo/modules/t3subscriptionwidget/SubscriptionUsageWidget.kt
@@ -0,0 +1,163 @@
+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.Bundle
+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))
+ }
+
+ override fun onAppWidgetOptionsChanged(
+ context: Context,
+ manager: AppWidgetManager,
+ id: Int,
+ options: Bundle
+ ) {
+ update(context, manager, id)
+ }
+
+ 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) {
+ val saved = context.getSharedPreferences(PREFERENCES, 0).getString("snapshot", null)
+ val snapshot = runCatching { JSONObject(saved.orEmpty()) }.getOrNull()
+ val views = RemoteViews(context.packageName, R.layout.t3_subscription_widget)
+ openAppIntent(context, id, snapshot)?.let {
+ views.setOnClickPendingIntent(R.id.t3_widget_root, it)
+ }
+ val providers = snapshot?.optJSONArray("providers")
+ val now = System.currentTimeMillis()
+ var nextExpiry = Long.MAX_VALUE
+ var totalRows = 0
+ 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)
+ totalRows += provider.optInt("totalWindows", windows.length())
+ (0 until windows.length()).map { provider to windows.optJSONObject(it) }
+ } else {
+ totalRows++
+ listOf(provider to null)
+ }
+ }
+ // Show each provider before filling spare space with its other windows.
+ val rows = (0 until (groups.maxOfOrNull { it.size } ?: 0)).flatMap { index ->
+ groups.mapNotNull { it.getOrNull(index) }
+ }
+ if (rows.isNotEmpty()) {
+ views.removeAllViews(R.id.t3_widget_rows)
+ val options = manager.getAppWidgetOptions(id)
+ val height = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, 180)
+ val count = ((height - 64) / 66).coerceIn(1, 12).coerceAtMost(rows.size)
+ for ((provider, window) in rows.take(count)) {
+ views.addView(R.id.t3_widget_rows, rowView(context, provider, window))
+ }
+ val remaining = totalRows - count
+ val checkedAt = snapshot?.optLong("checkedAt") ?: 0
+ val formatted = DateFormat.getDateTimeInstance(
+ DateFormat.SHORT,
+ DateFormat.SHORT
+ ).format(Date(checkedAt))
+ val more = if (remaining > 0) {
+ context.getString(R.string.t3_subscription_widget_more, remaining)
+ } else {
+ ""
+ }
+ val checked = if (checkedAt > 0) {
+ context.getString(R.string.t3_subscription_widget_as_of, formatted)
+ } else {
+ context.getString(R.string.t3_subscription_widget_unknown_check)
+ }
+ views.setTextViewText(R.id.t3_widget_footer, checked + more)
+ }
+ 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?): 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,
+ intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or 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.setContentDescription(
+ R.id.t3_widget_row,
+ "$label. $windowLabel. $percent. $reset. $detail"
+ )
+ return child
+ }
+ }
+}
diff --git a/apps/mobile/modules/t3-subscription-widget/android/src/main/java/expo/modules/t3subscriptionwidget/T3SubscriptionWidgetModule.kt b/apps/mobile/modules/t3-subscription-widget/android/src/main/java/expo/modules/t3subscriptionwidget/T3SubscriptionWidgetModule.kt
new file mode 100644
index 00000000000..6557b70958d
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/src/main/java/expo/modules/t3subscriptionwidget/T3SubscriptionWidgetModule.kt
@@ -0,0 +1,18 @@
+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)
+ }
+ }
+}
diff --git a/apps/mobile/modules/t3-subscription-widget/android/src/main/res/drawable/t3_subscription_widget_background.xml b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/drawable/t3_subscription_widget_background.xml
new file mode 100644
index 00000000000..69ec028ee8a
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/drawable/t3_subscription_widget_background.xml
@@ -0,0 +1,4 @@
+<shape xmlns:android="http://schemas.android.com/apk/res/android">
+ <solid android:color="@color/t3_widget_background" />
+ <corners android:radius="20dp" />
+</shape>
diff --git a/apps/mobile/modules/t3-subscription-widget/android/src/main/res/layout/t3_subscription_widget.xml b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/layout/t3_subscription_widget.xml
new file mode 100644
index 00000000000..58e55bc2c81
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/layout/t3_subscription_widget.xml
@@ -0,0 +1,9 @@
+<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: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" />
+ <LinearLayout android:id="@+id/t3_widget_rows" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="vertical">
+ <TextView 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" />
+ </LinearLayout>
+ <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>
diff --git a/apps/mobile/modules/t3-subscription-widget/android/src/main/res/layout/t3_subscription_widget_row.xml b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/layout/t3_subscription_widget_row.xml
new file mode 100644
index 00000000000..941f27ef856
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/layout/t3_subscription_widget_row.xml
@@ -0,0 +1,10 @@
+<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>
diff --git a/apps/mobile/modules/t3-subscription-widget/android/src/main/res/values-night/colors.xml b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/values-night/colors.xml
new file mode 100644
index 00000000000..0647eb1a8ea
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/values-night/colors.xml
@@ -0,0 +1,5 @@
+<resources>
+ <color name="t3_widget_background">#18181B</color>
+ <color name="t3_widget_foreground">#FAFAFA</color>
+ <color name="t3_widget_secondary">#A1A1AA</color>
+</resources>
diff --git a/apps/mobile/modules/t3-subscription-widget/android/src/main/res/values/colors.xml b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/values/colors.xml
new file mode 100644
index 00000000000..bf4ca10ecfc
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/values/colors.xml
@@ -0,0 +1,5 @@
+<resources>
+ <color name="t3_widget_background">#FAFAFA</color>
+ <color name="t3_widget_foreground">#18181B</color>
+ <color name="t3_widget_secondary">#52525B</color>
+</resources>
diff --git a/apps/mobile/modules/t3-subscription-widget/android/src/main/res/values/strings.xml b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/values/strings.xml
new file mode 100644
index 00000000000..7ef70aa44a4
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/values/strings.xml
@@ -0,0 +1,11 @@
+<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_description">Saved subscription quotas from your T3 Code environments. Tap to refresh in the app.</string>
+ <string name="t3_subscription_widget_empty">Open T3 Code and connect an environment to see limits.</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_as_of">As of %1$s</string>
+ <string name="t3_subscription_widget_more"> · +%1$d more</string>
+</resources>
diff --git a/apps/mobile/modules/t3-subscription-widget/android/src/main/res/xml/t3_subscription_widget_info.xml b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/xml/t3_subscription_widget_info.xml
new file mode 100644
index 00000000000..4dfdad5b0fe
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/android/src/main/res/xml/t3_subscription_widget_info.xml
@@ -0,0 +1,9 @@
+<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" />
diff --git a/apps/mobile/modules/t3-subscription-widget/expo-module.config.json b/apps/mobile/modules/t3-subscription-widget/expo-module.config.json
new file mode 100644
index 00000000000..7ddc9c09e22
--- /dev/null
+++ b/apps/mobile/modules/t3-subscription-widget/expo-module.config.json
@@ -0,0 +1,4 @@
+{
+ "platforms": ["android"],
+ "android": { "modules": ["expo.modules.t3subscriptionwidget.T3SubscriptionWidgetModule"] }
+}
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx
index b7f1db54e8c..852b6c0560e 100644
--- a/apps/mobile/src/App.tsx
+++ b/apps/mobile/src/App.tsx
@@ -24,6 +24,8 @@ import { OverlayPortalHost } from "./components/OverlayPortal";
import { appBlurTargetRef } from "./lib/appBlurTarget";
import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
+import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";
+
import "../global.css";
if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
@@ -77,6 +79,7 @@ function AppContent() {
return (
<>
<SplashScreenCoordinator />
+ <SubscriptionUsageCoordinator />
<GestureHandlerRootView className="flex-1">
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
index b3232acc681..04d9a4bee6c 100644
--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx
+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
@@ -1,5 +1,5 @@
import { EnvironmentId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
-import { useNavigation } from "@react-navigation/native";
+import { type RouteProp, useNavigation, useRoute } from "@react-navigation/native";
import {
isCompatibleUsageContractVersion,
isModelCostUnknown,
@@ -65,11 +65,22 @@ const CHART_HEIGHT = 180;
* pull to refresh, each refreshing its own data.
*/
export function UsageRouteScreen() {
+ const route = useRoute<RouteProp<{ Usage: { tab?: string } | undefined }, "Usage">>();
const navigation = useNavigation();
const insets = useSafeAreaInsets();
- // Limits first: remaining quota and reset time are what most people open
- // the screen for.
- const [tab, setTab] = useState<UsageTab>("limits");
+ // Preserve the Limits default while honoring explicit widget/navigation links.
+ const [selection, setSelection] = useState(() => ({
+ params: route.params,
+ tab: (route.params?.tab === "usage" ? "usage" : "limits") as UsageTab,
+ }));
+ if (selection.params !== route.params) {
+ setSelection({
+ params: route.params,
+ tab: route.params?.tab === "usage" ? "usage" : "limits",
+ });
+ }
+ const { tab } = selection;
+ const setTab = (tab: UsageTab) => setSelection({ params: route.params, tab });
const [windowSelection, setWindowSelection] = useState(() => ({
days: 30,
window: makeWindow(30),
diff --git a/apps/mobile/src/widgets/SubscriptionUsage.tsx b/apps/mobile/src/widgets/SubscriptionUsage.tsx
new file mode 100644
index 00000000000..600383765d5
--- /dev/null
+++ b/apps/mobile/src/widgets/SubscriptionUsage.tsx
@@ -0,0 +1,262 @@
+import { HStack, ProgressView, Spacer, Text, VStack } from "@expo/ui/swift-ui";
+import {
+ accessibilityElement,
+ accessibilityLabel,
+ font,
+ foregroundStyle,
+ frame,
+ layoutPriority,
+ lineLimit,
+ minimumScaleFactor,
+ progressViewStyle,
+ tint,
+ widgetURL,
+} from "@expo/ui/swift-ui/modifiers";
+import { createWidget, type WidgetEnvironment } from "expo-widgets";
+
+import type { SubscriptionUsageSnapshot as SubscriptionUsageProps } from "./subscriptionUsageSnapshot";
+
+type UsageConfiguration = {
+ codexPeriod?: "auto" | "session" | "weekly";
+ claudePeriod?: "auto" | "session" | "weekly";
+};
+
+function SubscriptionUsage(
+ props: SubscriptionUsageProps,
+ environment: WidgetEnvironment<UsageConfiguration>,
+) {
+ "widget";
+ // The extension evaluates this function without the app's module scope.
+ const family = environment.widgetFamily;
+ // Gallery snapshots can render an old timeline entry after it has expired.
+ const now = Math.max(environment.date.getTime(), Date.now());
+ const accessory = family === "accessoryRectangular";
+ const compact =
+ family === "systemSmall" || accessory || environment.levelOfDetail === "simplified";
+ const limit = family === "systemExtraLarge" ? 6 : family === "systemLarge" ? 4 : 2;
+ const monochrome =
+ environment.widgetRenderingMode !== "fullColor" || environment.isLuminanceReduced;
+ const providers = props.providers ?? [
+ { name: "Codex", detail: "Open T3 to connect", windows: [], expiresAt: 0 },
+ { name: "Claude", detail: "Open T3 to connect", windows: [], expiresAt: 0 },
+ ];
+ const columns = providers.map((provider) => {
+ const stale = provider.windows.length > 0 && now >= provider.expiresAt;
+ const period =
+ environment.configuration?.[provider.name === "Claude" ? "claudePeriod" : "codexPeriod"] ??
+ "auto";
+ const windows = stale
+ ? []
+ : provider.windows.filter((window) => period === "auto" || window.kind === period);
+ // Lock Screen widgets surface the tightest selected limit.
+ const tightest = windows.reduce<(typeof windows)[number] | undefined>(
+ (result, window) => (!result || window.remaining < result.remaining ? window : result),
+ undefined,
+ );
+ const compactWindows = [
+ windows.find((window) => window.kind === "session"),
+ windows.find((window) => window.kind === "weekly"),
+ ].filter((window) => window !== undefined);
+ const shown =
+ accessory || environment.levelOfDetail === "simplified"
+ ? tightest
+ ? [tightest]
+ : []
+ : family === "systemSmall" && compactWindows.length > 0
+ ? compactWindows
+ : period === "auto" && compactWindows.length > 0
+ ? [
+ ...compactWindows,
+ ...windows.filter((window) => !compactWindows.includes(window)),
+ ].slice(0, limit)
+ : windows.slice(0, limit);
+ const detail = stale
+ ? "Open T3 to refresh"
+ : period !== "auto" && windows.length === 0 && provider.windows.length > 0
+ ? `No ${period} limit reported`
+ : provider.detail;
+ const barModifiers = [
+ progressViewStyle("linear"),
+ ...(monochrome ? [] : [tint(provider.name === "Claude" ? "#d97757" : "#8e8e93")]),
+ ];
+ if (accessory) {
+ return (
+ <VStack
+ key={provider.name}
+ alignment="leading"
+ spacing={2}
+ modifiers={[
+ accessibilityElement("ignore"),
+ accessibilityLabel(
+ tightest
+ ? `${provider.name}, ${tightest.label}, ${tightest.remaining} percent remaining. ${tightest.reset}. ${provider.detail}.`
+ : `${provider.name}. ${detail}.`,
+ ),
+ ]}
+ >
+ <HStack spacing={4}>
+ <Text
+ modifiers={[
+ font({ textStyle: "caption", weight: "semibold" }),
+ lineLimit(1),
+ minimumScaleFactor(0.75),
+ foregroundStyle("primary"),
+ ]}
+ >
+ {provider.name}
+ {tightest ? ` · ${tightest.label}` : ""}
+ </Text>
+ <Spacer />
+ <Text
+ modifiers={[
+ font({ textStyle: "caption", weight: "semibold" }),
+ lineLimit(1),
+ layoutPriority(1),
+ foregroundStyle("primary"),
+ ]}
+ >
+ {tightest
+ ? `${tightest.remaining}% left`
+ : period !== "auto" && !stale && provider.windows.length > 0
+ ? "N/A"
+ : "Open T3"}
+ </Text>
+ </HStack>
+ {tightest ? (
+ <ProgressView value={tightest.remaining / 100} modifiers={barModifiers} />
+ ) : null}
+ </VStack>
+ );
+ }
+ return (
+ <VStack
+ key={provider.name}
+ alignment="leading"
+ spacing={compact ? 2 : 4}
+ modifiers={[frame({ maxWidth: Infinity, alignment: "leading" })]}
+ >
+ <Text
+ modifiers={[
+ font({ textStyle: compact ? "caption" : "headline", weight: "bold" }),
+ lineLimit(1),
+ minimumScaleFactor(0.75),
+ foregroundStyle("primary"),
+ ]}
+ >
+ {provider.name}
+ </Text>
+ {(!compact || shown.length === 0) && detail !== "Subscription remaining" ? (
+ <Text
+ modifiers={[
+ font({ textStyle: "caption2" }),
+ foregroundStyle("secondary"),
+ lineLimit(compact ? 1 : 2),
+ ]}
+ >
+ {detail}
+ </Text>
+ ) : null}
+ {shown.map((window) => (
+ <VStack
+ key={window.label}
+ alignment="leading"
+ spacing={2}
+ modifiers={[
+ accessibilityElement("ignore"),
+ accessibilityLabel(
+ `${provider.name}, ${window.label}, ${window.remaining} percent remaining. ${window.reset}. ${provider.detail}.`,
+ ),
+ ]}
+ >
+ <HStack spacing={4}>
+ <Text
+ modifiers={[
+ font({ textStyle: compact ? "caption2" : "caption" }),
+ foregroundStyle("secondary"),
+ lineLimit(1),
+ minimumScaleFactor(0.75),
+ ]}
+ >
+ {window.label}
+ </Text>
+ <Spacer />
+ <Text
+ modifiers={[
+ font({ textStyle: compact ? "caption2" : "caption", weight: "semibold" }),
+ lineLimit(1),
+ minimumScaleFactor(0.75),
+ layoutPriority(1),
+ foregroundStyle(
+ window.remaining <= 10 && !monochrome
+ ? environment.colorScheme === "light"
+ ? "#dc2626"
+ : "#fca5a5"
+ : "primary",
+ ),
+ ]}
+ >
+ {window.remaining}% left
+ </Text>
+ </HStack>
+ <ProgressView value={window.remaining / 100} modifiers={barModifiers} />
+ {!compact ? (
+ <Text
+ modifiers={[
+ font({ textStyle: "caption2" }),
+ foregroundStyle("secondary"),
+ lineLimit(1),
+ minimumScaleFactor(0.75),
+ ]}
+ >
+ {window.reset}
+ </Text>
+ ) : null}
+ </VStack>
+ ))}
+ {!compact &&
+ !stale &&
+ (period === "auto" ? (provider.totalWindows ?? windows.length) : windows.length) > limit ? (
+ <Text modifiers={[font({ textStyle: "caption2" }), foregroundStyle("secondary")]}>
+ {(period === "auto" ? (provider.totalWindows ?? windows.length) : windows.length) -
+ limit}{" "}
+ more in T3
+ </Text>
+ ) : null}
+ </VStack>
+ );
+ });
+ return (
+ <VStack
+ alignment="leading"
+ spacing={accessory ? 2 : 6}
+ modifiers={props.url ? [widgetURL(props.url)] : []}
+ >
+ {compact ? (
+ <VStack alignment="leading" spacing={accessory ? 4 : 8}>
+ {columns}
+ </VStack>
+ ) : (
+ <HStack alignment="top" spacing={16}>
+ {columns}
+ </HStack>
+ )}
+ {!accessory ? <Spacer /> : null}
+ {!accessory ? (
+ <Text
+ modifiers={[
+ font({ textStyle: "caption2" }),
+ foregroundStyle("secondary"),
+ lineLimit(1),
+ minimumScaleFactor(0.75),
+ ]}
+ >
+ {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>
+ ) : null}
+ </VStack>
+ );
+}
+
+export default createWidget("SubscriptionUsage", SubscriptionUsage);
diff --git a/apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx b/apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx
new file mode 100644
index 00000000000..84dce5d515e
--- /dev/null
+++ b/apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx
@@ -0,0 +1,32 @@
+import { useAtomValue } from "@effect/atom-react";
+import { Atom } from "effect/unstable/reactivity";
+import * as Linking from "expo-linking";
+import { useEffect } from "react";
+import { environmentCatalog } from "../connection/catalog";
+import { environmentPresentations } from "../state/presentation";
+import { publishSubscriptionUsage } from "./publishSubscriptionUsage";
+import { useSubscriptionUsage } from "./useSubscriptionUsage";
+import { buildSubscriptionUsageSnapshot } from "./subscriptionUsageSnapshot";
+
+// Isolate quota changes from the much busier thread/config presentation stream.
+const snapshotAtom = Atom.make((get) =>
+ buildSubscriptionUsageSnapshot(
+ get(environmentPresentations.presentationsAtom),
+ Linking.createURL("settings/usage", { queryParams: { tab: "limits" } }),
+ ),
+).pipe(Atom.withEquality((a, b) => JSON.stringify(a) === JSON.stringify(b)));
+
+export function SubscriptionUsageCoordinator() {
+ const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
+ const snapshot = useAtomValue(snapshotAtom);
+ useSubscriptionUsage(catalog.isReady);
+ useEffect(() => {
+ if (!catalog.isReady) return;
+ void Promise.resolve()
+ .then(() => publishSubscriptionUsage(snapshot))
+ .catch((error: unknown) => {
+ console.warn("Could not update subscription usage widget", error);
+ });
+ }, [catalog.isReady, snapshot]);
+ return null;
+}
diff --git a/apps/mobile/src/widgets/publishSubscriptionUsage.android.ts b/apps/mobile/src/widgets/publishSubscriptionUsage.android.ts
new file mode 100644
index 00000000000..a37b4f61eca
--- /dev/null
+++ b/apps/mobile/src/widgets/publishSubscriptionUsage.android.ts
@@ -0,0 +1,8 @@
+import { requireOptionalNativeModule } from "expo";
+import type { SubscriptionUsageSnapshot } from "./subscriptionUsageSnapshot";
+
+export function publishSubscriptionUsage(snapshot: SubscriptionUsageSnapshot) {
+ requireOptionalNativeModule<{ updateSnapshot: (snapshot: string) => void }>(
+ "T3SubscriptionWidget",
+ )?.updateSnapshot(JSON.stringify(snapshot));
+}
diff --git a/apps/mobile/src/widgets/publishSubscriptionUsage.ios.ts b/apps/mobile/src/widgets/publishSubscriptionUsage.ios.ts
new file mode 100644
index 00000000000..c386f927f94
--- /dev/null
+++ b/apps/mobile/src/widgets/publishSubscriptionUsage.ios.ts
@@ -0,0 +1,11 @@
+import { requireOptionalNativeModule } from "expo";
+import {
+ subscriptionUsageTimeline,
+ type SubscriptionUsageSnapshot,
+} from "./subscriptionUsageSnapshot";
+
+export async function publishSubscriptionUsage(snapshot: SubscriptionUsageSnapshot) {
+ if (!requireOptionalNativeModule("ExpoWidgets")) return;
+ const { default: widget } = await import("./SubscriptionUsage");
+ widget.updateTimeline(subscriptionUsageTimeline(snapshot, Date.now()));
+}
diff --git a/apps/mobile/src/widgets/publishSubscriptionUsage.ts b/apps/mobile/src/widgets/publishSubscriptionUsage.ts
new file mode 100644
index 00000000000..3a50eb20d82
--- /dev/null
+++ b/apps/mobile/src/widgets/publishSubscriptionUsage.ts
@@ -0,0 +1,3 @@
+import type { SubscriptionUsageSnapshot } from "./subscriptionUsageSnapshot";
+
+export function publishSubscriptionUsage(_snapshot: SubscriptionUsageSnapshot) {}
diff --git a/apps/mobile/src/widgets/subscriptionUsageSnapshot.test.ts b/apps/mobile/src/widgets/subscriptionUsageSnapshot.test.ts
new file mode 100644
index 00000000000..65d4c9924f6
--- /dev/null
+++ b/apps/mobile/src/widgets/subscriptionUsageSnapshot.test.ts
@@ -0,0 +1,257 @@
+import {
+ EnvironmentId,
+ ProviderDriverKind,
+ ProviderInstanceId,
+ UsageLimitSourceId,
+ type ServerProvider,
+} from "@t3tools/contracts";
+import { describe, expect, it, vi } from "vite-plus/test";
+import {
+ buildSubscriptionUsageSnapshot,
+ createWidgetRefresher,
+ WIDGET_REFRESH_INTERVAL,
+ subscriptionUsageTimeline,
+} from "./subscriptionUsageSnapshot";
+
+const checkedAt = "2026-09-05T12:00:00.000Z";
+const now = Date.parse(checkedAt);
+const window = {
+ id: "session",
+ kind: "session",
+ label: "5 hours",
+ usedPercent: 40,
+ resetsAt: "2026-09-05T12:10:00.000Z",
+} as const;
+const limits = { checkedAt, windows: [window] };
+const deepLink = "t3code-dev://settings/usage?tab=limits";
+function provider(overrides: Partial<ServerProvider> = {}): ServerProvider {
+ return {
+ instanceId: ProviderInstanceId.make("codex"),
+ driver: ProviderDriverKind.make("codex"),
+ enabled: true,
+ installed: true,
+ version: null,
+ status: "ready",
+ auth: { status: "authenticated", email: "[email protected]" },
+ checkedAt,
+ models: [],
+ slashCommands: [],
+ skills: [],
+ usageLimits: limits,
+ ...overrides,
+ };
+}
+function presentations(providers: readonly ServerProvider[] = [provider()]) {
+ return new Map([
+ [
+ EnvironmentId.make("env"),
+ { entry: { target: { label: "Remote" } }, serverConfig: { providers } },
+ ],
+ ]);
+}
+
+describe("subscription widget snapshots", () => {
+ it("uses provider data and its observation time without exposing account emails", () => {
+ const snapshot = buildSubscriptionUsageSnapshot(
+ presentations([provider({ displayName: "[email protected]" })]),
+ deepLink,
+ );
+ expect(snapshot.checkedAt).toBe(now);
+ expect(snapshot.providers[0]).toMatchObject({
+ name: "Codex",
+ windows: [{ remaining: 60 }],
+ expiresAt: now + 10 * 60_000,
+ });
+ expect(snapshot.url).toBe(deepLink);
+ expect(JSON.stringify(snapshot)).not.toContain("[email protected]");
+ });
+ it("clears data after removing environments and hides disabled providers", () => {
+ expect(
+ buildSubscriptionUsageSnapshot(new Map(), deepLink).providers.every(
+ (p) => p.windows.length === 0,
+ ),
+ ).toBe(true);
+ expect(
+ buildSubscriptionUsageSnapshot(
+ presentations([provider({ enabled: false })]),
+ deepLink,
+ ).providers.every((p) => p.windows.length === 0),
+ ).toBe(true);
+ });
+ it("uses upstream deduplication for a native account also present in a proxy hub", () => {
+ const input = new Map([
+ [
+ EnvironmentId.make("env"),
+ {
+ entry: { target: { label: "Remote" } },
+ serverConfig: {
+ providers: [provider()],
+ usageLimitSources: [
+ {
+ id: UsageLimitSourceId.make("hub"),
+ kind: "cliproxy" as const,
+ label: "Hub",
+ checkedAt,
+ accounts: [
+ {
+ id: "account",
+ driver: ProviderDriverKind.make("codex"),
+ email: " [email protected] ",
+ usageLimits: limits,
+ },
+ ],
+ },
+ ],
+ },
+ },
+ ],
+ ]);
+ expect(buildSubscriptionUsageSnapshot(input, deepLink).providers[0]?.detail).toBe(
+ "Subscription remaining",
+ );
+ input.get(EnvironmentId.make("env"))!.serverConfig.providers = [];
+ const snapshot = buildSubscriptionUsageSnapshot(input, deepLink);
+ expect(snapshot.providers[0]?.name).toBe("Codex");
+ expect(JSON.stringify(snapshot)).not.toContain("example.com");
+ });
+ it("keeps unavailable quotas distinct from zero usage and omits provider error messages", () => {
+ const snapshot = buildSubscriptionUsageSnapshot(
+ presentations([
+ provider({
+ usageLimits: {
+ ...limits,
+ unavailable: { reason: "probeFailed", message: "token secret" },
+ },
+ }),
+ ]),
+ deepLink,
+ );
+ expect(snapshot.providers[0]?.windows).toEqual([]);
+ expect(JSON.stringify(snapshot)).not.toContain("token secret");
+ expect(
+ buildSubscriptionUsageSnapshot(
+ presentations([
+ provider({ usageLimits: { checkedAt, windows: [{ ...window, usedPercent: 0 }] } }),
+ ]),
+ deepLink,
+ ).providers[0]?.windows[0]?.remaining,
+ ).toBe(100);
+ });
+ it("bounds OS storage and puts the most constrained windows first", () => {
+ const windows = Array.from({ length: 20 }, (_, index) => ({
+ ...window,
+ id: `${index}`,
+ usedPercent: index * 5,
+ }));
+ const snapshot = buildSubscriptionUsageSnapshot(
+ presentations([provider({ usageLimits: { checkedAt, windows } })]),
+ deepLink,
+ );
+ expect(snapshot.providers[0]?.windows).toHaveLength(6);
+ expect(snapshot.providers[0]?.totalWindows).toBe(20);
+ expect(snapshot.providers[0]?.windows[0]?.remaining).toBe(5);
+ });
+ it("marks unknown or distant reset times stale after fifteen minutes", () => {
+ const snapshot = buildSubscriptionUsageSnapshot(
+ presentations([
+ provider({ usageLimits: { checkedAt, windows: [{ ...window, resetsAt: undefined }] } }),
+ ]),
+ deepLink,
+ );
+ expect(snapshot.providers[0]?.expiresAt).toBe(now + 15 * 60_000);
+ expect(snapshot.providers[0]?.windows[0]?.reset).toBe("Reset time unavailable");
+ });
+ it("schedules a reset boundary without inventing a zero quota", () => {
+ const snapshot = buildSubscriptionUsageSnapshot(presentations(), deepLink);
+ const timeline = subscriptionUsageTimeline(snapshot, now);
+ expect(timeline.map((entry) => entry.date.getTime())).toEqual([now, now + 10 * 60_000]);
+ expect(timeline[1]?.props.providers[0]?.windows).toEqual([]);
+ expect(subscriptionUsageTimeline(snapshot, now + 60 * 60_000)).toHaveLength(1);
+ });
+ it("expires providers independently without inventing a refill", () => {
+ const snapshot = buildSubscriptionUsageSnapshot(
+ presentations([
+ provider(),
+ provider({
+ instanceId: ProviderInstanceId.make("claude"),
+ driver: ProviderDriverKind.make("claudeAgent"),
+ usageLimits: { checkedAt, windows: [{ ...window, resetsAt: undefined }] },
+ }),
+ ]),
+ deepLink,
+ );
+ const timeline = subscriptionUsageTimeline(snapshot, now);
+ expect(timeline.map((entry) => entry.date.getTime())).toEqual([
+ now,
+ now + 10 * 60_000,
+ now + 15 * 60_000,
+ ]);
+ expect(timeline[1]?.props.providers[0]?.windows).toEqual([]);
+ expect(timeline[1]?.props.providers[1]?.windows[0]?.remaining).toBe(60);
+ expect(timeline[2]?.props.providers.every((provider) => provider.windows.length === 0)).toBe(
+ true,
+ );
+ });
+ it("marks a malformed check time immediately stale without storing null", () => {
+ const snapshot = buildSubscriptionUsageSnapshot(
+ presentations([provider({ usageLimits: { ...limits, checkedAt: "invalid" } })]),
+ deepLink,
+ );
+ expect(snapshot.checkedAt).toBe(0);
+ expect(snapshot.providers[0]).toMatchObject({ expiresAt: 0, windows: [] });
+ expect(subscriptionUsageTimeline(snapshot, now)).toHaveLength(1);
+ expect(JSON.stringify(snapshot)).not.toContain("null");
+ });
+ it("uses the freshest copy of an account across environments before pooling", () => {
+ const input = presentations();
+ input.set(EnvironmentId.make("other"), {
+ entry: { target: { label: "Other" } },
+ serverConfig: {
+ providers: [
+ provider({
+ usageLimits: {
+ checkedAt: new Date(now + 60_000).toISOString(),
+ windows: [{ ...window, usedPercent: 80 }],
+ },
+ }),
+ ],
+ },
+ });
+ const snapshot = buildSubscriptionUsageSnapshot(input, deepLink);
+ expect(snapshot.providers[0]?.detail).toBe("Subscription remaining");
+ expect(snapshot.providers[0]?.windows[0]?.remaining).toBe(20);
+ });
+});
+
+describe("widget refresh probes", () => {
+ it("throttles each connected environment independently and retries failures", async () => {
+ const probe = vi
+ .fn<(id: string) => Promise<void>>()
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockResolvedValue(undefined);
+ const refresh = createWidgetRefresher(probe);
+ await refresh([], now);
+ expect(probe).not.toHaveBeenCalled();
+ await refresh(["first"], now);
+ await refresh(["first", "second"], now + 1);
+ expect(probe.mock.calls).toEqual([["first"], ["second"]]);
+ await refresh(["first"], now + WIDGET_REFRESH_INTERVAL);
+ expect(probe.mock.calls).toEqual([["first"], ["second"], ["first"]]);
+ });
+
+ it("does not overlap a slow probe even after the refresh interval", async () => {
+ let finish!: () => void;
+ const probe = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const refresh = createWidgetRefresher(probe);
+ const first = refresh(["one", "one"], now);
+ await refresh(["one"], now + WIDGET_REFRESH_INTERVAL);
+ expect(probe).toHaveBeenCalledTimes(1);
+ finish();
+ await first;
+ });
+});
diff --git a/apps/mobile/src/widgets/subscriptionUsageSnapshot.ts b/apps/mobile/src/widgets/subscriptionUsageSnapshot.ts
new file mode 100644
index 00000000000..826124e1053
--- /dev/null
+++ b/apps/mobile/src/widgets/subscriptionUsageSnapshot.ts
@@ -0,0 +1,134 @@
+import {
+ collectLimitAccounts,
+ collectLimitPools,
+ type LimitAccount,
+ type LimitPresentations,
+} from "@t3tools/shared/usageLimits";
+
+export interface SubscriptionUsageSnapshot {
+ url?: string;
+ checkedAt: number;
+ providers: Array<{
+ name: string;
+ detail: string;
+ windows: Array<{ kind?: string; label: string; remaining: number; reset: string }>;
+ expiresAt: number;
+ totalWindows: number;
+ }>;
+}
+
+// Snapshots expire after 15 minutes; background refresh needs a
+// separate authenticated transport while the mobile app is suspended.
+const SNAPSHOT_MAX_AGE = 15 * 60_000;
+export const WIDGET_REFRESH_INTERVAL = 5 * 60_000;
+
+/** Bound probes across config updates, reconnects, and foreground transitions. */
+export function createWidgetRefresher<Id>(refresh: (id: Id) => Promise<unknown>) {
+ const attempted = new Map<Id, number>();
+ const pending = new Set<Id>();
+ return async (connected: readonly Id[], now: number) => {
+ await Promise.allSettled(
+ connected.map(async (id) => {
+ if (pending.has(id) || now - (attempted.get(id) ?? -Infinity) < WIDGET_REFRESH_INTERVAL)
+ return;
+ attempted.set(id, now);
+ pending.add(id);
+ try {
+ await refresh(id);
+ } finally {
+ pending.delete(id);
+ }
+ }),
+ );
+ };
+}
+
+function subscriptionUsageProps(
+ accounts: readonly LimitAccount[],
+ now: number,
+): SubscriptionUsageSnapshot {
+ const pools = collectLimitPools(accounts, now);
+ const checked = accounts
+ .filter((account) => account.driver === "codex" || account.driver === "claudeAgent")
+ .map((account) => Date.parse(account.limits.checkedAt));
+ return {
+ checkedAt: checked.length > 0 && checked.every(Number.isFinite) ? Math.min(...checked) : 0,
+ providers: (["codex", "claudeAgent"] as const).map((driver) => {
+ const pool = pools.find((candidate) => candidate.driver === driver);
+ const name = driver === "codex" ? "Codex" : "Claude";
+ if (!pool)
+ return { name, detail: "No limits available", windows: [], expiresAt: 0, totalWindows: 0 };
+ const checkedAt = Math.min(...pool.accounts.map((a) => Date.parse(a.limits.checkedAt)));
+ const expiresAt = Math.min(
+ checkedAt + SNAPSHOT_MAX_AGE,
+ ...pool.windows.flatMap((window) => window.resets.map((reset) => reset.at)),
+ );
+ const fresh = Number.isFinite(expiresAt) && expiresAt > now;
+ const sortedWindows = [...pool.windows].sort(
+ (a, b) => a.remainingPercent - b.remainingPercent,
+ );
+ // Keep a session and weekly limit when scoped limits fill the storage budget.
+ const selectedWindows = [
+ ...new Set([
+ sortedWindows.find((window) => window.kind === "session"),
+ sortedWindows.find((window) => window.kind === "weekly"),
+ ...sortedWindows,
+ ]),
+ ]
+ .filter((window) => window !== undefined)
+ .slice(0, 6)
+ .sort((a, b) => a.remainingPercent - b.remainingPercent);
+ return {
+ name,
+ detail: !fresh
+ ? "Open T3 to refresh"
+ : pool.accounts.length > 1
+ ? `${pool.accounts.length} accounts · pooled`
+ : "Subscription remaining",
+ expiresAt: fresh ? expiresAt : 0,
+ totalWindows: fresh ? pool.windows.length : 0,
+ windows: fresh
+ ? selectedWindows.map((window) => ({
+ kind: window.kind,
+ label: window.label,
+ remaining: Math.round(window.remainingPercent),
+ reset: window.resets[0]
+ ? `Next reset ${new Date(window.resets[0].at).toLocaleString(undefined, {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ })}`
+ : "Reset time unavailable",
+ }))
+ : [],
+ };
+ }),
+ };
+}
+
+/** Deduplicate accounts before pooling, and only publish display data to the OS. */
+export function buildSubscriptionUsageSnapshot(
+ presentations: LimitPresentations,
+ url: string,
+): SubscriptionUsageSnapshot {
+ // Freshness is evaluated at publication/render time, not on unrelated config emissions.
+ return { ...subscriptionUsageProps(collectLimitAccounts(presentations), 0), url };
+}
+
+export function subscriptionUsageTimeline(snapshot: SubscriptionUsageSnapshot, now: number) {
+ const deadlines = [...new Set(snapshot.providers.map((p) => p.expiresAt))]
+ .filter((deadline) => deadline > now)
+ .sort((a, b) => a - b);
+ return [now, ...deadlines].map((date) => ({
+ date: new Date(date),
+ props: {
+ ...snapshot,
+ providers: snapshot.providers.map((provider) =>
+ provider.windows.length > 0 && provider.expiresAt <= date
+ ? { ...provider, detail: "Open T3 to refresh", windows: [], totalWindows: 0 }
+ : provider,
+ ),
+ },
+ }));
+}
diff --git a/apps/mobile/src/widgets/useSubscriptionUsage.ts b/apps/mobile/src/widgets/useSubscriptionUsage.ts
new file mode 100644
index 00000000000..1f90a5ebbe7
--- /dev/null
+++ b/apps/mobile/src/widgets/useSubscriptionUsage.ts
@@ -0,0 +1,40 @@
+import { useAtomValue } from "@effect/atom-react";
+import { useEffect, useMemo } from "react";
+import { AppState } from "react-native";
+
+import { environmentPresentations } from "../state/presentation";
+import { serverEnvironment } from "../state/server";
+import { useAtomCommand } from "../state/use-atom-command";
+import { createWidgetRefresher, WIDGET_REFRESH_INTERVAL } from "./subscriptionUsageSnapshot";
+
+export function useSubscriptionUsage(enabled = true) {
+ const presentations = useAtomValue(environmentPresentations.presentationsAtom);
+ const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
+ reportFailure: false,
+ });
+ const refresh = useMemo(
+ () =>
+ createWidgetRefresher(
+ (environmentId: Parameters<typeof refreshProviders>[0]["environmentId"]) =>
+ refreshProviders({ environmentId, input: {} }),
+ ),
+ [refreshProviders],
+ );
+
+ useEffect(() => {
+ const update = () => {
+ if (!enabled || AppState.currentState !== "active") return;
+ const connected = [...presentations]
+ .filter(([, presentation]) => presentation.connection.phase === "connected")
+ .map(([id]) => id);
+ void refresh(connected, Date.now());
+ };
+ update();
+ const subscription = AppState.addEventListener("change", update);
+ const timer = setInterval(update, WIDGET_REFRESH_INTERVAL);
+ return () => {
+ subscription.remove();
+ clearInterval(timer);
+ };
+ }, [enabled, presentations, refresh]);
+}
diff --git a/docs/user/usage.md b/docs/user/usage.md
index f4fdb5cca00..9b0f449ee75 100644
--- a/docs/user/usage.md
+++ b/docs/user/usage.md
@@ -81,3 +81,9 @@ account and choose **Use reset** to redeem one. No hub plugin is required.
This connection supplies usage information; configure
the provider separately to send agent requests through the hub. Remove the hub from the same
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.
diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts
index b814e66da45..0ef53b1e7f5 100644
--- a/packages/shared/src/usageLimits.test.ts
+++ b/packages/shared/src/usageLimits.test.ts
@@ -3,7 +3,6 @@ import {
ProviderDriverKind,
ProviderInstanceId,
type ServerProvider,
- type UsageLimitSourceAccount,
UsageLimitSourceId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
@@ -17,8 +16,6 @@ import {
collectLimitAccounts,
collectLimitNotices,
collectLimitPools,
- collectLimitSources,
- collectLimitsGroups,
elapsedShare,
formatResetsIn,
limitsNotice,
@@ -129,191 +126,6 @@ describe("providersWithLimits", () => {
});
});
-describe("collectLimitsGroups", () => {
- it("labels environments only when more than one reports limits", () => {
- const limits = { checkedAt: "2026-09-03T11:00:00.000Z", windows: [window] };
- const codex = provider({ usageLimits: limits });
- const one = new Map([
- ["env-a", { entry: { target: { label: "Laptop" } }, serverConfig: { providers: [codex] } }],
- [
- "env-b",
- { entry: { target: { label: "Desktop" } }, serverConfig: { providers: [provider({})] } },
- ],
- ] as const);
- expect(collectLimitsGroups(one as never).map((group) => group.environmentLabel)).toEqual([
- null,
- ]);
-
- const two = new Map([
- ["env-a", { entry: { target: { label: "Laptop" } }, serverConfig: { providers: [codex] } }],
- ["env-b", { entry: { target: { label: "Desktop" } }, serverConfig: { providers: [codex] } }],
- ] as const);
- expect(collectLimitsGroups(two as never).map((group) => group.environmentLabel)).toEqual([
- "Laptop",
- "Desktop",
- ]);
- });
-});
-
-describe("collectLimitSources", () => {
- const source = {
- id: UsageLimitSourceId.make("cliproxy-hub"),
- kind: "cliproxy" as const,
- label: "hub",
- checkedAt: "2026-09-03T11:00:00.000Z",
- accounts: [],
- };
- const limits = { checkedAt: source.checkedAt, windows: [window] };
- const account: UsageLimitSourceAccount = {
- id: "codex-personal",
- driver: ProviderDriverKind.make("codex"),
- email: "[email protected]",
- plan: "ChatGPT Pro Subscription",
- usageLimits: limits,
- };
- const native = provider({
- displayName: "Personal",
- auth: { status: "authenticated", email: account.email },
- usageLimits: { ...limits, resetCredits: { availableCount: 2 } },
- });
-
- function presentations(
- providers: readonly ServerProvider[],
- accounts: readonly UsageLimitSourceAccount[] = [account],
- ) {
- return new Map([
- [
- EnvironmentId.make("env-a"),
- {
- entry: { target: { label: "Laptop" } },
- serverConfig: { providers, usageLimitSources: [{ ...source, accounts }] },
- },
- ],
- ]);
- }
-
- it.each(["codex", "claudeAgent"])(
- "prefers native %s limits by email without changing provider rows or source snapshots",
- (kind) => {
- const driver = ProviderDriverKind.make(kind);
- const first = { ...native, driver };
- const second = { ...first, instanceId: ProviderInstanceId.make("work") };
- const accounts = [{ ...account, driver, email: " [email protected] " }];
- const input = presentations([first, second], accounts);
-
- expect(collectLimitSources(input)).toMatchObject([{ accounts: [], hiddenAccountCount: 1 }]);
- expect(collectLimitsGroups(input)[0]?.providers).toEqual([first, second]);
- expect(accounts).toHaveLength(1);
- expect(first.usageLimits?.resetCredits?.availableCount).toBe(2);
- },
- );
-
- it("matches across environments even when the hub is visited before the native provider", () => {
- const input = presentations([]);
- input.set(EnvironmentId.make("env-b"), {
- entry: { target: { label: "Desktop" } },
- serverConfig: { providers: [native], usageLimitSources: [] },
- });
-
- expect(collectLimitSources(input)).toMatchObject([
- { accounts: [], hiddenAccountCount: 1, environmentId: "env-a" },
- ]);
- });
-
- it("keeps other providers, other emails, and unidentified accounts with the same plan", () => {
- const accounts = [
- account,
- { ...account, id: "other-provider", driver: ProviderDriverKind.make("claudeAgent") },
- { ...account, id: "other-email", email: "[email protected]" },
- { ...account, id: "unknown-email", email: undefined },
- ];
-
- expect(collectLimitSources(presentations([native], accounts))).toMatchObject([
- { accounts: accounts.slice(1), hiddenAccountCount: 1 },
- ]);
- expect(
- collectLimitSources(
- presentations([{ ...native, auth: { status: "authenticated" } }], accounts),
- )[0]?.accounts,
- ).toEqual(accounts);
- });
-
- it.each([
- { enabled: false },
- { installed: false },
- { availability: "unavailable" },
- { usageLimits: undefined },
- { usageLimits: { ...limits, windows: [] } },
- { usageLimits: { ...limits, unavailable: { reason: "probeFailed" } } },
- { usageLimits: { ...limits, unavailable: { reason: "unsupported" } } },
- ] satisfies Partial<ServerProvider>[])(
- "retains hub limits when the native provider cannot show them: %j",
- (overrides) => {
- expect(collectLimitSources(presentations([{ ...native, ...overrides }]))).toMatchObject([
- { accounts: [account], hiddenAccountCount: 0 },
- ]);
- },
- );
-
- it("restores the hub account when the matching provider disappears", () => {
- const input = presentations([native]);
- expect(collectLimitSources(input)[0]?.accounts).toEqual([]);
- input.delete(EnvironmentId.make("env-a"));
- for (const [id, entry] of presentations([])) input.set(id, entry);
-
- expect(collectLimitSources(input)[0]?.accounts).toEqual([account]);
- });
-
- it("keeps source errors and genuinely empty sources distinguishable from hidden accounts", () => {
- const input = new Map([
- [
- EnvironmentId.make("env-a"),
- {
- entry: { target: { label: "Laptop" } },
- serverConfig: {
- providers: [native],
- usageLimitSources: [{ ...source, error: "Hub unavailable" }],
- },
- },
- ],
- ]);
- expect(collectLimitSources(input)).toMatchObject([
- { accounts: [], hiddenAccountCount: 0, error: "Hub unavailable" },
- ]);
- });
-
- it("keys sources per environment and names the environment only when several have some", () => {
- const one = new Map([
- [
- "env-a",
- { entry: { target: { label: "Laptop" } }, serverConfig: { usageLimitSources: [source] } },
- ],
- [
- "env-b",
- { entry: { target: { label: "Desktop" } }, serverConfig: { usageLimitSources: [] } },
- ],
- ] as const);
- expect(collectLimitSources(one as never).map((entry) => [entry.key, entry.label])).toEqual([
- ["env-a:cliproxy-hub", "hub"],
- ]);
-
- const two = new Map([
- [
- "env-a",
- { entry: { target: { label: "Laptop" } }, serverConfig: { usageLimitSources: [source] } },
- ],
- [
- "env-b",
- { entry: { target: { label: "Desktop" } }, serverConfig: { usageLimitSources: [source] } },
- ],
- ] as const);
- expect(collectLimitSources(two as never).map((entry) => entry.label)).toEqual([
- "Laptop · hub",
- "Desktop · hub",
- ]);
- });
-});
-
describe("pools", () => {
const checkedAt = "2026-09-03T11:00:00.000Z";
const weekly = {
diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts
index 5c32cc0343b..17ba1feab5d 100644
--- a/packages/shared/src/usageLimits.ts
+++ b/packages/shared/src/usageLimits.ts
@@ -15,7 +15,6 @@ import {
type ServerProvider,
type ServerProviderUsageLimits,
type ServerProviderUsageWindow,
- type UsageLimitSourceSnapshot,
type UsageLimitSourceSnapshots,
} from "@t3tools/contracts";
@@ -42,108 +41,16 @@ export function providersWithLimits(
);
}
-export interface LimitsGroup {
- readonly environmentId: EnvironmentId;
- /** Null while only one environment is connected; there is nothing to tell apart. */
- readonly environmentLabel: string | null;
- readonly providers: readonly ServerProvider[];
-}
-
-/**
- * One group per connected environment with a provider reporting limits.
- * Provider snapshots come from the config stream every client already holds,
- * so opening the view costs no extra request.
- */
-export function collectLimitsGroups(
- presentations: ReadonlyMap<
- EnvironmentId,
- {
- readonly entry: { readonly target: { readonly label: string } };
- readonly serverConfig: {
- readonly providers?: readonly ServerProvider[] | undefined;
- } | null;
- }
- >,
-): readonly LimitsGroup[] {
- const groups: LimitsGroup[] = [];
- for (const [environmentId, presentation] of presentations) {
- const providers = providersWithLimits(presentation.serverConfig?.providers ?? []);
- if (providers.length === 0) continue;
- groups.push({ environmentId, environmentLabel: presentation.entry.target.label, providers });
- }
- return groups.length > 1 ? groups : groups.map((group) => ({ ...group, environmentLabel: null }));
-}
-
-/**
- * Every usage-limit source across connected environments, keyed so two
- * environments pointing at the same hub still get their own rows. The label
- * carries the environment only when more than one environment has sources.
- * A native provider with usable limits takes precedence over the same account
- * in a source, even when it belongs to another connected environment.
- */
-export function collectLimitSources(
- presentations: ReadonlyMap<
- EnvironmentId,
- {
- readonly entry: { readonly target: { readonly label: string } };
- readonly serverConfig: {
- readonly providers?: readonly ServerProvider[] | undefined;
- readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined;
- } | null;
- }
- >,
-): ReadonlyArray<
- UsageLimitSourceSnapshot & {
- readonly key: string;
- readonly environmentId: EnvironmentId;
- readonly hiddenAccountCount: number;
+export type LimitPresentations = ReadonlyMap<
+ EnvironmentId,
+ {
+ readonly entry: { readonly target: { readonly label: string } };
+ readonly serverConfig: {
+ readonly providers?: readonly ServerProvider[] | undefined;
+ readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined;
+ } | null;
}
-> {
- const nativeAccounts = new Set<string>();
- for (const presentation of presentations.values()) {
- for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
- const key = accountKey(provider.driver, provider.auth.email);
- if (
- key !== null &&
- provider.usageLimits?.windows.length &&
- !provider.usageLimits.unavailable
- ) {
- nativeAccounts.add(key);
- }
- }
- }
- const perEnvironment: Array<{
- readonly environmentId: EnvironmentId;
- readonly environmentLabel: string;
- readonly sources: UsageLimitSourceSnapshots;
- }> = [];
- for (const [environmentId, presentation] of presentations) {
- const sources = presentation.serverConfig?.usageLimitSources ?? [];
- if (sources.length === 0) continue;
- perEnvironment.push({
- environmentId,
- environmentLabel: presentation.entry.target.label,
- sources,
- });
- }
- const labelEnvironment = perEnvironment.length > 1;
- return perEnvironment.flatMap(({ environmentId, environmentLabel, sources }) =>
- sources.map((source) => {
- const accounts = source.accounts.filter((account) => {
- const key = accountKey(account.driver, account.email);
- return key === null || !nativeAccounts.has(key);
- });
- return {
- ...source,
- accounts,
- hiddenAccountCount: source.accounts.length - accounts.length,
- environmentId,
- key: `${environmentId}:${source.id}`,
- label: labelEnvironment ? `${environmentLabel} · ${source.label}` : source.label,
- };
- }),
- );
-}
+>;
function accountKey(driver: ServerProvider["driver"], email: string | undefined): string | null {
const normalizedEmail = email?.trim().toLowerCase();
@@ -184,9 +91,7 @@ export interface LimitAccount {
* entry per distinct account. The freshest reads supply windows and credits;
* native instances supply names and environment labels.
*/
-export function collectLimitAccounts(
- presentations: Parameters<typeof collectLimitSources>[0],
-): readonly LimitAccount[] {
+export function collectLimitAccounts(presentations: LimitPresentations): readonly LimitAccount[] {
const accounts = new Map<string, LimitAccount>();
const creditSources = new Map<string, LimitAccount>();
const hubRedeems = new Map<string, LimitAccount>();
@@ -315,9 +220,7 @@ export function collectLimitAccounts(
* are left out; there is nothing for the user to act on. The environment
* is named only when more than one is connected.
*/
-export function collectLimitNotices(
- presentations: Parameters<typeof collectLimitSources>[0],
-): readonly string[] {
+export function collectLimitNotices(presentations: LimitPresentations): readonly string[] {
const label = (environmentLabel: string, subject: string) =>
presentations.size > 1 ? `${environmentLabel} · ${subject}` : subject;
const notices: string[] = [];