Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(mobile): usage, stats and agents-needing-input, and seal four RPC types

tony68cbf1774d85
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index 7ea7196f7..572b9103e 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -20,6 +20,7 @@ const Set<String> encryptedDownTypes = {
'session_get',
'models_list',
'agent_create',
+ 'agent_create_status',
'agent_delete',
'agent_restart',
'agent_recent',
@@ -27,8 +28,15 @@ const Set<String> encryptedDownTypes = {
'agent_files',
'agent_read_file',
'fs_list_dir',
+ 'project_preview',
'codex_profiles_list',
'codex_profile_link',
+ // Asks the machine to read its OWN agent accounts' usage (cli/src/lib/accountUsage.ts). Missing
+ // here it went out in the clear and the machine's CLI refused it outright with E2EE_REQUIRED —
+ // which surfaced as an empty Usage page on a phone that was linked and connected.
+ 'usage_read',
+ // The pane colours this client paints with, for the machine's tmux sessions (cli/src/lib/hostTheme.ts).
+ 'theme_set',
'device_e2ee_pair',
'e2ee_pairings_list',
'e2ee_pairing_unpair',
diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dart
index 7ea7196f7..572b9103e 100644
--- a/mobile/lib/e2ee/envelope.dart
+++ b/mobile/lib/e2ee/envelope.dart
@@ -20,6 +20,7 @@ const Set<String> encryptedDownTypes = {
'session_get',
'models_list',
'agent_create',
+ 'agent_create_status',
'agent_delete',
'agent_restart',
'agent_recent',
@@ -27,8 +28,15 @@ const Set<String> encryptedDownTypes = {
'agent_files',
'agent_read_file',
'fs_list_dir',
+ 'project_preview',
'codex_profiles_list',
'codex_profile_link',
+ // Asks the machine to read its OWN agent accounts' usage (cli/src/lib/accountUsage.ts). Missing
+ // here it went out in the clear and the machine's CLI refused it outright with E2EE_REQUIRED —
+ // which surfaced as an empty Usage page on a phone that was linked and connected.
+ 'usage_read',
+ // The pane colours this client paints with, for the machine's tmux sessions (cli/src/lib/hostTheme.ts).
+ 'theme_set',
'device_e2ee_pair',
'e2ee_pairings_list',
'e2ee_pairing_unpair',
diff --git a/mobile/lib/phone/agents_tab.dart b/mobile/lib/phone/agents_tab.dart
index 184010b4d..8d5708999 100644
--- a/mobile/lib/phone/agents_tab.dart
+++ b/mobile/lib/phone/agents_tab.dart
@@ -8,6 +8,7 @@ import 'package:harness_mobile/state/app_state.dart';
import 'agent_index.dart';
import 'agent_row.dart';
import 'agents_page.dart';
+import 'attention_entry.dart';
import 'machine_filter_bar.dart';
import 'phone_card.dart';
import 'phone_fab.dart';
@@ -94,6 +95,11 @@ class _AgentsTabState extends State<AgentsTab> {
large: true,
title: 'Agents',
trailing: [
+ // Only while something is actually waiting — the button draws
+ // itself away otherwise, which is why there is no condition
+ // here. It sits before search because it is the one control
+ // that appears in response to something happening.
+ buildAttentionButton(context, widget.notifier),
if (machines.isNotEmpty)
PhoneSearchButton(notifier: widget.notifier),
],
diff --git a/mobile/lib/phone/attention_entry.dart b/mobile/lib/phone/attention_entry.dart
new file mode 100644
index 000000000..62b8854a1
--- /dev/null
+++ b/mobile/lib/phone/attention_entry.dart
@@ -0,0 +1,111 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/widgets/app_icon_button.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'agent_index.dart';
+import 'attention_page.dart';
+import 'phone_navigation.dart';
+
+/// Pushes [AttentionPage].
+///
+/// Separate from the button so anything else that should land there — a notification tap, a
+/// future shortcut — opens the same route rather than pushing its own.
+void openAttentionPage(BuildContext context, AppNotifier notifier) =>
+ Navigator.of(context).push(
+ phoneRoute((_) => AttentionPage(notifier: notifier)),
+ );
+
+/// The way into [AttentionPage], drawn in the Agents tab header's `trailing`.
+///
+/// ⚠️ **Absent when nothing is waiting**, rather than drawn disabled or drawn with a zero badge.
+/// The page's own answer for that case is an empty state, and a glyph whose only outcome is being
+/// told "nothing here" is worse than no glyph — the same rule the search button in that header
+/// keeps. It is also why the count lives on the button rather than beside it: the button only
+/// exists while the count is worth reading.
+Widget buildAttentionButton(BuildContext context, AppNotifier notifier) {
+ final waiting = waitingAgents(agentIndex(notifier)).length;
+ if (waiting == 0) return const SizedBox.shrink();
+ return _AttentionButton(notifier: notifier, count: waiting);
+}
+
+class _AttentionButton extends StatelessWidget {
+ const _AttentionButton({required this.notifier, required this.count});
+
+ final AppNotifier notifier;
+ final int count;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Padding(
+ padding: const EdgeInsets.only(right: 2),
+ child: Stack(
+ // The badge overhangs the glyph's box on both axes, the way the tab bar's does.
+ clipBehavior: Clip.none,
+ children: [
+ AppIconButton(
+ icon: LucideIcons.bell300,
+ size: 22,
+ tooltip: count == 1 ? '1 agent waiting' : '$count agents waiting',
+ // The glyph itself carries the attention colour: it is only on screen because
+ // something IS waiting, so drawing it in the quiet ink every other header control
+ // uses would hide the one control worth noticing.
+ color: AppPalette.warn,
+ onPressed: () => openAttentionPage(context, notifier),
+ ),
+ Positioned(
+ top: -3,
+ right: -5,
+ // Ignores pointers so the badge cannot eat a tap meant for the button under it —
+ // it overhangs the glyph's box, so it sits over the row's padding as well.
+ child: IgnorePointer(child: _Badge(count: count)),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// The count, drawn the same way the Agents tab's own badge is.
+///
+/// Deliberately a second, private copy of `phone_tab_bar.dart`'s `_Badge` rather than a shared
+/// one: that badge rims itself in the tab bar's `panelBg` so it reads as separate from the icon it
+/// overlaps, and this one sits on the page background instead. One widget carrying both would
+/// need a colour argument at every call site to say which surface it is on, which is more moving
+/// parts than the eleven lines it would save.
+class _Badge extends StatelessWidget {
+ const _Badge({required this.count});
+
+ final int count;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Container(
+ constraints: const BoxConstraints(minWidth: 16),
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
+ decoration: BoxDecoration(
+ color: AppPalette.warn,
+ borderRadius: BorderRadius.circular(999),
+ border: Border.all(color: AppPalette.windowBg, width: 1.5),
+ ),
+ alignment: Alignment.center,
+ child: Text(
+ // Past 99 the exact figure stops meaning anything and the pill would widen off the glyph.
+ count > 99 ? '99+' : '$count',
+ style: TextStyle(
+ // Follows the theme because the fill does — see the tab bar's badge for the contrast
+ // measurements behind this pair.
+ color: AppTheme.pick(Colors.white, const Color(0xFF181818)),
+ fontSize: 10,
+ height: 1.2,
+ fontWeight: FontWeight.w700,
+ fontFeatures: AppFont.tabularFigures,
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/attention_page.dart b/mobile/lib/phone/attention_page.dart
new file mode 100644
index 000000000..b523ac124
--- /dev/null
+++ b/mobile/lib/phone/attention_page.dart
@@ -0,0 +1,276 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/widgets/empty_state.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/attention.dart';
+import 'package:harness_mobile/widgets/engine_identity.dart';
+
+import 'phone_card.dart';
+import 'phone_header.dart';
+import 'phone_navigation.dart';
+import 'phone_status.dart';
+
+/// Every agent, on every machine, that has stopped to ask the person something.
+///
+/// The desktop reaches the same list with ⇧⌘I and draws it as a searchable picker
+/// (`widgets/swarm_attention.dart`); a phone gets a page instead, because there is no keyboard to
+/// open it with and nothing else to look at while it is open. The badge on the Agents tab already
+/// says HOW MANY are waiting — this is the screen that says which.
+///
+/// ⚠️ It is the one list that does not fall back to the whole roster. A page that showed idle
+/// agents once everything had been answered would be a second, worse Agents tab; when there is
+/// nothing waiting, the right answer is to say so and send the person back.
+class AttentionPage extends StatelessWidget {
+ const AttentionPage({super.key, required this.notifier});
+
+ final AppNotifier notifier;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: notifier,
+ builder: (context, _) {
+ AppTheme.watch(context);
+ final entries = attentionEntries(notifier);
+ final groups = attentionGroups(entries);
+ return Scaffold(
+ backgroundColor: AppPalette.windowBg,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ children: [
+ PhoneHeader(
+ title: 'Needs input',
+ subtitle: entries.isEmpty
+ ? null
+ : Text(
+ entries.length == 1
+ ? '1 agent waiting'
+ : '${entries.length} agents waiting',
+ style: TextStyle(
+ color: AppPalette.textSecondary,
+ fontSize: 13,
+ ),
+ ),
+ ),
+ Expanded(
+ child: _Body(notifier: notifier, groups: groups),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+}
+
+class _Body extends StatelessWidget {
+ const _Body({required this.notifier, required this.groups});
+
+ final AppNotifier notifier;
+ final List<AttentionGroup> groups;
+
+ /// Whether anything is still on its way in — a machine connecting, or its agents not yet
+ /// answered. "Loading" and "nobody is waiting" must not render the same, which is the one thing
+ /// this page's empty state has to get right: the second is good news and the first is not news
+ /// at all.
+ bool get _stillArriving {
+ if (notifier.machines.isEmpty && notifier.machinesLoading) return true;
+ for (final machine in notifier.machines) {
+ final state = notifier.stateOf(machine.machineId);
+ if (state == null) return true;
+ if (phoneMachineStatusOf(state) == PhoneMachineStatus.connecting) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ if (groups.isEmpty) {
+ if (_stillArriving) return const PhoneListSkeleton();
+ return const EmptyState(
+ icon: LucideIcons.circleCheck300,
+ title: 'No agents waiting',
+ message: 'Nothing has stopped to ask you anything right now.',
+ );
+ }
+ // Every waiting agent across the whole page, in the order the rows are drawn — so a swipe on
+ // the terminal this opens walks THIS list rather than the Agents tab's. Built from the groups
+ // rather than recomputed, so the two cannot disagree about the order.
+ final ordered = [
+ for (final group in groups)
+ for (final entry in group.entries) entry.agent,
+ ];
+ return RefreshIndicator(
+ onRefresh: notifier.retryMachines,
+ child: ListView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: phoneListPadding(context),
+ children: [
+ for (final group in groups) ...[
+ _MachineLabel(group.machineName),
+ for (final entry in group.entries)
+ Padding(
+ padding: const EdgeInsets.only(bottom: kPhoneCardGap),
+ child: _AttentionRow(
+ entry: entry,
+ onTap: () => openAgentPager(
+ context,
+ notifier,
+ ordered,
+ entry.agent,
+ ),
+ ),
+ ),
+ const SizedBox(height: 6),
+ ],
+ ],
+ ),
+ );
+ }
+}
+
+/// One waiting agent: its engine, its name, and what it is asking.
+///
+/// Taller than the app's other rows on purpose — [PhoneCard]'s fixed 70pt fits a name and a status
+/// line, and the QUESTION is the whole reason to come here. A row that cropped it to a status pill
+/// would send the person into the terminal to find out what the tap was for.
+class _AttentionRow extends StatelessWidget {
+ const _AttentionRow({required this.entry, required this.onTap});
+
+ final AttentionEntry entry;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final agent = entry.agent.agent;
+ final prompt = entry.promptLine;
+ // Held to the same rule as every other row: an agent with no terminal to attach cannot be
+ // opened. It still draws — it IS waiting, and hiding it would make the tab's badge count
+ // rows this page does not have.
+ final open = agent.terminalAvailable;
+ return Material(
+ color: Colors.transparent,
+ child: InkWell(
+ onTap: open ? onTap : null,
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ child: Opacity(
+ opacity: open ? 1 : 0.55,
+ child: Container(
+ padding: const EdgeInsets.fromLTRB(13, 12, 13, 12),
+ decoration: BoxDecoration(
+ color: AppGlass.rowFill,
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ // The attention rim every waiting row wears, matching [AgentRow] — the same agent
+ // seen on two screens must not be marked two different ways.
+ border: Border.all(color: AppPalette.warn.withValues(alpha: 0.42)),
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ PhoneCardGlyph(
+ child: EngineMark(
+ engine: agent.engine,
+ displayName: agent.engineDisplayName,
+ size: 22,
+ ),
+ ),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ agent.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textPrimary,
+ fontSize: 16,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(height: 3),
+ Text(
+ entry.machineName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textFaint,
+ fontSize: 12.5,
+ ),
+ ),
+ const SizedBox(height: 7),
+ // ⚠️ Two lines, never more. The prompt is already collapsed to one line by
+ // [AttentionEntry.promptLine]; letting it run further would turn a list into
+ // a transcript and push the next waiting agent off the screen.
+ Text(
+ prompt ?? 'Waiting for you',
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: prompt == null
+ ? AppPalette.textFaint
+ : AppPalette.textSecondary,
+ fontSize: 13.5,
+ height: 1.35,
+ fontStyle: prompt == null
+ ? FontStyle.italic
+ : FontStyle.normal,
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 8),
+ if (open)
+ Padding(
+ padding: const EdgeInsets.only(top: 11),
+ child: Icon(
+ LucideIcons.chevronRight300,
+ size: 22,
+ color: AppPalette.textFaint,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// The machine a group of rows belongs to.
+///
+/// The rows name their machine as well, because one is read on its own the moment the page
+/// scrolls past this heading — the heading is what makes the grouping visible, not what carries
+/// the fact.
+class _MachineLabel extends StatelessWidget {
+ const _MachineLabel(this.text);
+
+ final String text;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(4, 8, 4, 8),
+ child: Text(
+ text.toUpperCase(),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textFaint,
+ fontSize: 11.5,
+ fontWeight: FontWeight.w600,
+ letterSpacing: 0.5,
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dart
index df13bafe9..acfe705ee 100644
--- a/mobile/lib/phone/settings_page.dart
+++ b/mobile/lib/phone/settings_page.dart
@@ -2,28 +2,52 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:package_info_plus/package_info_plus.dart';
import 'package:harness_mobile/core/app_version.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/appearance_prefs_store.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/terminal/terminal_font_store.dart';
+import 'package:harness_mobile/terminal/terminal_theme_store.dart';
+
import 'phone_header.dart';
import 'phone_sheet.dart';
import 'settings_row.dart';
+import 'stats_entry.dart';
+import 'usage_entry.dart';
/// The phone's Settings tab.
///
-/// DELIBERATELY not the desktop's eight sections. Four of them cannot work in a viewer build and
+/// DELIBERATELY not the desktop's eight sections. Three of them cannot work in a viewer build and
/// would each be a screen that opens on nothing:
///
-/// - **Usage** reads `~/.claude/projects`, `~/.codex` and OpenCode's SQLite file ON THIS DISK. A
-/// phone has none of them — every figure would be zero, for agents that really are running.
/// - **Autonomous devices** flashes an ESP32 over a serial port, through the CLI. A viewer has no
/// CLI and a phone has no serial port.
/// - **Keyboard shortcuts** is a list of ⌘ combinations for a keyboard that is not there.
/// - **Check for updates** belongs to the desktop updater; a phone build is updated by its store.
///
+/// **Usage** used to be on that list, for a reason that was true of the desktop reader and not of
+/// the setting: it counts by reading `~/.claude/projects`, `~/.codex` and OpenCode's SQLite file ON
+/// THIS DISK, and a phone has none of them. What a phone can do is ask the machine that does — so
+/// the section is kept, and its two rows come from elsewhere: `usage_entry.dart` reads each linked
+/// machine's rate limits over `usage_read`, and `stats_entry.dart` reads the counters this app keeps
+/// about itself.
+///
+/// What a phone shows that the desktop splits across panes:
+///
+/// - **Appearance** carries the six [HarnessPalette] choices the desktop keeps in its own
+/// Customize pane. They are not decoration here: the phone's tab bar, cards and terminal ground
+/// are all drawn from the chosen palette, and until now the phone shipped whichever one the
+/// desktop had last written to `~/.harness`.
+/// - **Terminal** carries the colour scheme beside the face and the size, because on a phone all
+/// three answer the same question — what the pane looks like at arm's length.
+///
+/// The desktop's **Debug** screen has no counterpart here on purpose. It reads an in-memory ring
+/// that only a debug build fills, so on a shipped phone the row would open on an empty page — and
+/// the log files it mirrors are written either way, which is what a fault report actually needs.
+///
/// What a phone adds instead is the account and the machine links, which the desktop keeps in its
/// rail footer — on a phone there is no rail, so this is the only way to reach either.
class SettingsPage extends StatelessWidget {
@@ -80,13 +104,26 @@ class _Body extends StatelessWidget {
),
],
),
+ // ⚠️ Usage sits SECOND, right under the account and above the appearance settings, and that
+ // is deliberate: it is the only run here anybody opens twice. Everything below it is set once
+ // and left alone, so burying a figure people check daily under four preferences would be
+ // ordering the list by how permanent each row is rather than by how often it is read.
+ const SettingsCaption('Usage'),
+ SettingsGroup(
+ children: [
+ buildUsageSettingsRow(context, notifier),
+ buildStatsSettingsRow(context, notifier),
+ ],
+ ),
const SettingsCaption('Terminal'),
- SettingsGroup(children: [_FontRow(), _SizeRow()]),
+ SettingsGroup(children: [_FontRow(), _SizeRow(), _TerminalThemeRow()]),
const SettingsCaption('Appearance'),
- SettingsGroup(children: [_TextSizeRow()]),
- const SettingsNote('Harness is dark-only, so there is no theme to pick.'),
+ SettingsGroup(children: [_PaletteRow(), _TextSizeRow()]),
+ const SettingsNote(
+ 'Harness is dark-only, so a palette picks the shade rather than the mode.',
+ ),
const SettingsCaption('About'),
- SettingsGroup(children: [const _VersionRow()]),
+ SettingsGroup(children: const [_VersionRow(), _BuildRow()]),
],
);
@@ -200,6 +237,74 @@ class _SizeRow extends StatelessWidget {
);
}
+/// The terminal's colour scheme. Beside the face and the size rather than under Appearance, because
+/// all three describe the pane a remote program draws into — and [TerminalThemeChoice.matchApp],
+/// the default, is precisely the choice to follow Appearance instead.
+class _TerminalThemeRow extends StatelessWidget {
+ @override
+ Widget build(BuildContext context) =>
+ ValueListenableBuilder<TerminalThemeChoice>(
+ valueListenable: terminalThemeStore,
+ builder: (context, choice, _) {
+ AppTheme.watch(context);
+ return SettingsRow(
+ title: 'Colors',
+ value: choice.label,
+ onTap: () => showPhoneSheet(
+ context,
+ title: 'Terminal colors',
+ actions: [
+ for (final option in TerminalThemeChoice.values)
+ PhoneSheetAction(
+ icon: option == choice
+ ? LucideIcons.check300
+ : LucideIcons.palette300,
+ label: option.label,
+ onTap: () => unawaited(terminalThemeStore.set(option)),
+ ),
+ ],
+ ),
+ );
+ },
+ );
+}
+
+/// The app's palette — the six [HarnessPalette] choices the desktop lays out as swatch cards.
+///
+/// A sheet of names rather than a grid of previews, and the difference is the screen: the desktop's
+/// cards each draw a miniature workspace, which needs the width of a settings pane to be legible at
+/// all. Shrunk to a phone's column they would be six indistinguishable dark rectangles. The app
+/// repaints on the tap anyway — [AppearancePrefsStore.setPalette] moves the notifier before it
+/// writes — so the preview IS the app behind the sheet, at full size, which no swatch can beat.
+class _PaletteRow extends StatelessWidget {
+ @override
+ Widget build(BuildContext context) => ValueListenableBuilder<AppearancePrefs>(
+ valueListenable: appearancePrefsStore,
+ builder: (context, prefs, _) {
+ AppTheme.watch(context);
+ return SettingsRow(
+ title: 'Palette',
+ value: prefs.palette.label,
+ onTap: () => showPhoneSheet(
+ context,
+ title: 'Color palette',
+ actions: [
+ for (final palette in HarnessPalette.values)
+ PhoneSheetAction(
+ icon: palette == prefs.palette
+ ? LucideIcons.check300
+ : LucideIcons.swatchBook300,
+ label: '${palette.label} · ${palette.description}',
+ onTap: () =>
+ unawaited(appearancePrefsStore.setPalette(palette)),
+ ),
+ ],
+ ),
+ );
+ },
+ );
+}
+
/// The app's own text size — everything that is not the terminal.
class _TextSizeRow extends StatelessWidget {
@override
@@ -237,3 +342,43 @@ class _VersionRow extends StatelessWidget {
},
);
}
+
+/// The build behind the version — `buildNumber` from the bundle, and the store's own identifier.
+///
+/// Version alone is not enough to name a phone build. Two TestFlight builds and two Play internal
+/// tracks share one marketing version by design, and a bug report that says "1.0.0" names four
+/// binaries. The build number is what the store shows beside a submission and what a crash report
+/// is filed against, so it is the one figure support actually asks for — which is why it earns a
+/// row rather than being folded into the version's text and lost to its own ellipsis.
+///
+/// ⚠️ Read through [PackageInfo] rather than [runningAppVersion]: that one deliberately answers only
+/// the marketing version, with a Linux `version.txt` branch this platform never takes.
+class _BuildRow extends StatelessWidget {
+ const _BuildRow();
+
+ /// Resolved ONCE per process, not per build of this row.
+ ///
+ /// [PackageInfo.fromPlatform] is a platform-channel round trip, and the settings list rebuilds on
+ /// every [AppNotifier] notification — a socket frame, an agent's state change. A future created
+ /// inline would fire one channel call per frame and flash the em dash back in each time while it
+ /// resolved. The answer cannot change while the process lives, so caching it is exact rather than
+ /// merely cheap.
+ static final Future<PackageInfo> _info = PackageInfo.fromPlatform();
+
+ @override
+ Widget build(BuildContext context) => FutureBuilder<PackageInfo>(
+ future: _info,
+ builder: (context, snapshot) {
+ AppTheme.watch(context);
+ final info = snapshot.data;
+ // Empty rather than missing on Linux/desktop dev builds, where nothing stamps it — the em
+ // dash covers both, so a blank string never renders as a row with no value.
+ final build = info?.buildNumber ?? '';
+ return SettingsRow(
+ title: 'Build',
+ value: build.isEmpty ? '—' : build,
+ detail: info?.packageName,
+ );
+ },
+ );
+}
diff --git a/mobile/lib/phone/stats_entry.dart b/mobile/lib/phone/stats_entry.dart
new file mode 100644
index 000000000..758c78c82
--- /dev/null
+++ b/mobile/lib/phone/stats_entry.dart
@@ -0,0 +1,41 @@
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/stats/harness_stats.dart';
+
+import 'phone_navigation.dart';
+import 'settings_row.dart';
+import 'stats_page.dart';
+
+/// The Settings row that opens [StatsPage].
+///
+/// A function rather than a widget class, and it lives here rather than in the settings list, for
+/// one reason: that list builds every row inline, so a feature owning a page of its own would
+/// otherwise have its row wired up in a file that knows nothing else about it. This keeps the row,
+/// the page and the counters behind them together — the settings list only has to call it.
+///
+/// [notifier] is unused today and deliberately still taken: every other entry point on that list is
+/// handed one, and a row that later wants the app model — a count of live agents beside the figure,
+/// say — should not change the shape of the call to get it.
+Widget buildStatsSettingsRow(BuildContext context, AppNotifier notifier) =>
+ // Subscribed to the counters rather than reading them once: the settings list rebuilds on the
+ // app model, which does not move when an agent is spawned from another tab, so the figure below
+ // would otherwise sit at whatever it was when Settings was first drawn.
+ ListenableBuilder(
+ listenable: harnessStats,
+ builder: (context, _) {
+ final summary = harnessStats.summary;
+ return SettingsRow(
+ title: 'Stats',
+ // The headline figure on the row itself, so the list answers "has this counted
+ // anything?" without a push. Empty reads as an em dash rather than "0 agents", which
+ // looks like a figure that was measured and came out zero.
+ value: summary.isEmpty
+ ? '—'
+ : '${formatStatCount(summary.agentsSpawned)} '
+ '${summary.agentsSpawned == 1 ? 'agent' : 'agents'}',
+ onTap: () =>
+ Navigator.of(context).push(phoneRoute((_) => const StatsPage())),
+ );
+ },
+ );
diff --git a/mobile/lib/phone/stats_page.dart b/mobile/lib/phone/stats_page.dart
new file mode 100644
index 000000000..79fc175a8
--- /dev/null
+++ b/mobile/lib/phone/stats_page.dart
@@ -0,0 +1,278 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/stats/harness_stats.dart';
+
+import 'phone_header.dart';
+import 'settings_row.dart';
+
+/// What this app has done, on a phone: agents spawned, time agents worked, turns — and the date
+/// the counting started under them.
+///
+/// The figures come from [harnessStats], the app's own counters. They are not a vendor's and not a
+/// file on disk, so unlike the desktop's Settings ▸ Usage there is no ledger half here and no
+/// permission to ask: a phone has none of the `~/.claude` / `~/.codex` transcripts that half reads,
+/// and every token figure would be zero for agents that really are running.
+///
+/// ⚠️ **Deliberately NOT the desktop's `StatsSummaryCards` layout.** That draws three cards in a
+/// row — a shape that collapses to one column below 420pt anyway, which is every phone — with an
+/// 11.5pt label and a 20pt figure sized for a settings pane read at desk distance. This stacks
+/// three full-width rows instead, each with its glyph, its label and a figure large enough to read
+/// at arm's length, which is also what lets the number carry the unit ("3h 24m") without wrapping.
+class StatsPage extends StatelessWidget {
+ const StatsPage({super.key, this.stats});
+
+ /// The counters to draw. Defaults to the singleton; the parameter exists so a caller can pass
+ /// its own instance, exactly as the desktop's `UsageSection` takes one.
+ final HarnessStats? stats;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ // [HarnessStats] is a `ChangeNotifier` and every hook in `AppNotifier` notifies, so the figures
+ // move while this page is open — an agent started from another tab lands here without a
+ // refresh, and a turn's minutes land the moment it ends. Nothing to pull.
+ return ListenableBuilder(
+ listenable: stats ?? harnessStats,
+ builder: (context, _) {
+ AppTheme.watch(context);
+ return Scaffold(
+ backgroundColor: AppPalette.windowBg,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ children: [
+ const PhoneHeader(title: 'Stats'),
+ Expanded(
+ child: _Body(summary: (stats ?? harnessStats).summary),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+ }
+}
+
+class _Body extends StatelessWidget {
+ const _Body({required this.summary});
+
+ final StatsSummary summary;
+
+ @override
+ Widget build(BuildContext context) => ListView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: EdgeInsets.fromLTRB(
+ 16,
+ 4,
+ 16,
+ MediaQuery.paddingOf(context).bottom + 24,
+ ),
+ children: summary.isEmpty
+ // "Nothing tracked yet" and "0, 0, 0" read very differently: three zeroes look like a
+ // broken counter, and this says what would make them move.
+ ? const [
+ _EmptyState(),
+ SettingsNote(
+ 'These are this app’s own counters — what it watched happen, not what any '
+ 'agent account was billed. Nothing here is sent anywhere.',
+ ),
+ ]
+ : [
+ _StatCard(
+ icon: LucideIcons.bot300,
+ label: 'Agents spawned',
+ value: formatStatCount(summary.agentsSpawned),
+ ),
+ const SizedBox(height: kStatCardGap),
+ _StatCard(
+ icon: LucideIcons.clock300,
+ label: 'Time agents worked',
+ value: formatWorkedTime(summary.timeWorked),
+ ),
+ const SizedBox(height: kStatCardGap),
+ _StatCard(
+ icon: LucideIcons.messagesSquare300,
+ label: 'Turns',
+ value: formatStatCount(summary.turns),
+ ),
+ if (summary.firstEventAt case final since?)
+ SettingsNote('Tracking since ${formatTrackingDate(since)}.'),
+ ],
+ );
+}
+
+/// The gap between two stat cards — the same one two phone cards keep, so a column of these reads
+/// as the same kind of list as the machines and agents tabs.
+const double kStatCardGap = 10;
+
+/// One figure, full width: its glyph and label on one line, the number under them.
+///
+/// The number sits BELOW the label rather than opposite it, which is the other shape a row like
+/// this could take. A right-aligned figure has to share the row with a label that can be as long as
+/// "Time agents worked", and the longest value ("3d 21h") then lands in a different place on every
+/// row; stacked, all three numbers start on the same left margin and can be compared down the
+/// column at a glance.
+class _StatCard extends StatelessWidget {
+ const _StatCard({
+ required this.icon,
+ required this.label,
+ required this.value,
+ });
+
+ final IconData icon;
+ final String label;
+ final String value;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Container(
+ width: double.infinity,
+ padding: const EdgeInsets.fromLTRB(14, 13, 14, 15),
+ decoration: BoxDecoration(
+ color: AppGlass.rowFill,
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ border: Border.all(color: AppGlass.hair),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Row(
+ children: [
+ Icon(icon, size: 15, color: AppPalette.textFaint),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textSecondary,
+ fontSize: 12.5,
+ ),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 6),
+ Text(
+ value,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textPrimary,
+ fontSize: 28,
+ fontWeight: FontWeight.w600,
+ letterSpacing: -0.5,
+ // Tabular, so a counter ticking from 9 to 10 while the page is open does not reflow
+ // the figure beside it.
+ fontFeatures: AppFont.tabularFigures,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// Nothing has happened yet. A sentence rather than three zeroes.
+class _EmptyState extends StatelessWidget {
+ const _EmptyState();
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Container(
+ width: double.infinity,
+ padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 26),
+ decoration: BoxDecoration(
+ color: AppSurface.recess,
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ border: Border.all(color: AppGlass.hair),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(LucideIcons.bot300, size: 26, color: AppPalette.textFaint),
+ const SizedBox(height: 12),
+ Text(
+ 'Nothing tracked yet',
+ textAlign: TextAlign.center,
+ style: TextStyle(
+ color: AppPalette.textPrimary,
+ fontSize: 16,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(height: 6),
+ Text(
+ 'Start your first agent and this page begins counting.',
+ textAlign: TextAlign.center,
+ style: TextStyle(
+ color: AppPalette.textSecondary,
+ fontSize: 13,
+ height: 1.4,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// `1,284` — a count with its thousands grouped.
+///
+/// Grouped by hand rather than through `intl`: this package deliberately carries no localisation
+/// dependency, and the one separator a stat needs is not worth adding one for.
+String formatStatCount(int count) {
+ final digits = count.abs().toString();
+ final out = StringBuffer(count < 0 ? '-' : '');
+ for (var i = 0; i < digits.length; i++) {
+ // A separator before every digit whose distance from the end is a multiple of three, except at
+ // the very start — which is what keeps `1,000` from coming out as `,1,000`.
+ if (i > 0 && (digits.length - i) % 3 == 0) out.write(',');
+ out.write(digits[i]);
+ }
+ return out.toString();
+}
+
+/// `4h 12m`, `3d 5h`, `18m` — a worked duration at a glance.
+///
+/// The desktop's `formatWorkedTime` exactly, kept in step deliberately: the same counter is drawn
+/// in both apps, and a phone that rounded differently would look like it had counted differently.
+/// Days and hours past a day, hours and minutes past an hour, minutes below. Never seconds: the
+/// smallest thing being summed is a turn, and a figure that ticked every second would be the only
+/// moving thing on the screen.
+String formatWorkedTime(Duration worked) {
+ if (worked <= Duration.zero) return '0m';
+ if (worked.inDays > 0) return '${worked.inDays}d ${worked.inHours % 24}h';
+ if (worked.inHours > 0) return '${worked.inHours}h ${worked.inMinutes % 60}m';
+ return '${worked.inMinutes}m';
+}
+
+/// `Sep 16, 2026` — the date the counting started.
+///
+/// The month as a name rather than a number, because `9/16/2026` and `16/9/2026` are the same
+/// string read two ways and this line has no second figure to disambiguate it.
+String formatTrackingDate(DateTime at) {
+ const months = [
+ 'Jan',
+ 'Feb',
+ 'Mar',
+ 'Apr',
+ 'May',
+ 'Jun',
+ 'Jul',
+ 'Aug',
+ 'Sep',
+ 'Oct',
+ 'Nov',
+ 'Dec',
+ ];
+ final local = at.toLocal();
+ return '${months[local.month - 1]} ${local.day}, ${local.year}';
+}
diff --git a/mobile/lib/phone/usage_entry.dart b/mobile/lib/phone/usage_entry.dart
new file mode 100644
index 000000000..b4ca3abe6
--- /dev/null
+++ b/mobile/lib/phone/usage_entry.dart
@@ -0,0 +1,32 @@
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'phone_navigation.dart';
+import 'settings_row.dart';
+import 'usage_page.dart';
+
+/// The Settings ▸ Usage row, built here rather than in `settings_page.dart` so
+/// the page that owns the feature owns its entry point too.
+///
+/// What comes back is a [SettingsRow] — the same shape as every other row in a
+/// [SettingsGroup] — with a [ValueListenableBuilder] around it, so the figure
+/// refreshes when someone comes back from the page without Settings having to
+/// know that it can. Settings decides WHERE the row goes; this decides what it
+/// says.
+///
+/// The value is the tightest weekly figure across every account, which is the
+/// one worth a glance from a list of rows: the account closest to running out is
+/// the one that will stop the work. A dash when nothing has been read yet,
+/// never a zero — `0% used` is a measurement, and this has none.
+Widget buildUsageSettingsRow(BuildContext context, AppNotifier notifier) =>
+ ValueListenableBuilder<String?>(
+ valueListenable: lastUsageSummary,
+ builder: (context, summary, _) => SettingsRow(
+ title: 'Usage',
+ value: summary ?? '—',
+ onTap: () => Navigator.of(
+ context,
+ ).push(phoneRoute((_) => UsagePage(notifier: notifier))),
+ ),
+ );
diff --git a/mobile/lib/phone/usage_page.dart b/mobile/lib/phone/usage_page.dart
new file mode 100644
index 000000000..37f3b4b8a
--- /dev/null
+++ b/mobile/lib/phone/usage_page.dart
@@ -0,0 +1,594 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/widgets/empty_state.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
+import 'package:harness_mobile/usage/usage_accounts.dart';
+import 'package:harness_mobile/usage/usage_controller.dart';
+import 'package:harness_mobile/usage/usage_pressure.dart';
+import 'package:harness_mobile/usage/usage_window.dart';
+import 'package:harness_mobile/widgets/engine_identity.dart';
+
+import 'phone_card.dart';
+import 'phone_header.dart';
+
+/// The last figure this page resolved, so the Settings row that opens it can
+/// print something rather than a dash every single time.
+///
+/// ⚠️ **A cache, deliberately, and not a second poller.** That row is one line
+/// in a list; giving it a [UsageController] of its own would put a minute-ly
+/// relay round trip behind a screen whose whole job is to OFFER the screen that
+/// already does that — two pollers asking the same machines the same question,
+/// and a phone spending radio on a figure nobody asked to see. So the row shows
+/// what this page last measured, and this page is where a fresh reading is
+/// taken.
+///
+/// In memory only: a display convenience rather than a fact worth keeping
+/// across launches, and a figure restored from disk would be printed with no
+/// way to say how old it is.
+final ValueNotifier<String?> lastUsageSummary = ValueNotifier<String?>(null);
+
+/// What the agent accounts have spent, as a phone page.
+///
+/// ⚠️ **Deliberately NOT the desktop's layout.** There the same numbers live in
+/// a 26px strip along the window's bottom edge with a hover panel behind it:
+/// furniture you read on the way past, expanded by a pointer that a phone does
+/// not have. A phone has no rail to put it on and no hover to open it with, so
+/// this is a page — reached from Settings ▸ Usage — and the strip's one-figure
+/// rule becomes the card's headline while the panel's every-window detail
+/// becomes what the card expands to on a tap.
+///
+/// ⚠️ **Every figure here belongs to a REMOTE machine.** A phone holds no agent
+/// CLI and no `claude login`, so [UsageController] reads no local source at all
+/// — see its class comment. That is why each card names the machine it was read
+/// on rather than treating an unlabelled figure as "mine" the way the desktop
+/// does: on a phone there is no "mine".
+class UsagePage extends StatefulWidget {
+ const UsagePage({super.key, required this.notifier});
+
+ final AppNotifier notifier;
+
+ @override
+ State<UsagePage> createState() => _UsagePageState();
+}
+
+class _UsagePageState extends State<UsagePage> {
+ /// Owned by the page rather than by the app, which is the opposite of the
+ /// desktop's choice and right for the opposite reason. There the rail
+ /// unmounts whenever the sidebar folds, so a poller living in it would
+ /// restart on every unfold; here the page is a pushed route that exists only
+ /// while somebody is looking at it, and a minute-ly poll that outlived it
+ /// would be a phone spending radio on a screen nobody has open.
+ ///
+ /// The timer dies with [dispose], so nothing leaks when the page pops.
+ late final UsageController _usage = UsageController(
+ remote: widget.notifier.readRemoteUsage,
+ );
+
+ @override
+ void initState() {
+ super.initState();
+ _usage.addListener(_rememberSummary);
+ }
+
+ @override
+ void dispose() {
+ _usage.removeListener(_rememberSummary);
+ _usage.dispose();
+ super.dispose();
+ }
+
+ /// Hands the Settings row the figure this cycle came to.
+ ///
+ /// Only once a cycle has actually LANDED: a controller still on its first
+ /// round trip would otherwise clear a perfectly good figure from the row
+ /// behind this page the moment the page opened, and the reader would watch it
+ /// blank and come back.
+ void _rememberSummary() {
+ if (!_usage.hasAnswer) return;
+ lastUsageSummary.value = usageSummaryLabel(_usage.accounts);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Scaffold(
+ backgroundColor: AppPalette.windowBg,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ children: [
+ PhoneHeader(
+ title: 'Usage',
+ subtitle: Text(
+ 'What your agent accounts have spent',
+ style: TextStyle(color: AppPalette.textSecondary, fontSize: 13),
+ ),
+ ),
+ Expanded(
+ child: ListenableBuilder(
+ listenable: _usage,
+ builder: (context, _) => _Body(usage: _usage),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _Body extends StatelessWidget {
+ const _Body({required this.usage});
+
+ final UsageController usage;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ // Blank at the size of the answer, and only before the FIRST one: once
+ // figures exist they stay through every refresh rather than flicking back
+ // to skeletons once a minute.
+ if (usage.loading && !usage.hasAnswer) {
+ return const PhoneListSkeleton(rows: 2);
+ }
+ final accounts = [
+ for (final account in usage.accounts)
+ if (account.reading.hasFigures) account,
+ ];
+ if (accounts.isEmpty) {
+ // ⚠️ Three different silences, drawn three different ways — the whole
+ // point of keeping [UsageStatus.signedOut] apart from [UsageStatus.failed]
+ // upstream. Retrying fixes one, signing in on the machine fixes another,
+ // and linking a machine at all fixes the third; one shared "no data"
+ // screen would send every reader down the wrong path two times in three.
+ return RefreshIndicator(
+ onRefresh: usage.refresh,
+ child: ListView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: phoneListPadding(context),
+ children: [
+ SizedBox(height: MediaQuery.sizeOf(context).height * 0.18),
+ _EmptyUsage(usage: usage),
+ ],
+ ),
+ );
+ }
+ return PhoneCardList(
+ onRefresh: usage.refresh,
+ itemCount: accounts.length,
+ itemBuilder: (context, index) {
+ final account = accounts[index];
+ return _AccountCard(
+ // Keyed by the ACCOUNT rather than by its position, because
+ // `_AccountCard` carries the one piece of state on this page — whether
+ // it is expanded — and the order can change under it: a machine that
+ // finishes connecting adds an account mid-session, and an unkeyed
+ // stateful row would hand its open/closed state to whichever account
+ // slid into its index.
+ key: ValueKey(
+ '${account.provider.name}:${account.machines.join(',')}',
+ ),
+ account: account,
+ );
+ },
+ );
+ }
+}
+
+/// Why there are no figures, in the reader's own terms.
+///
+/// The order matters: a machine that ANSWERED with "sign in" has told us
+/// something specific about itself and outranks the generic failure beside it,
+/// because it names the one action that would actually help. A page with no
+/// machines at all never reaches either sentence.
+class _EmptyUsage extends StatelessWidget {
+ const _EmptyUsage({required this.usage});
+
+ final UsageController usage;
+
+ @override
+ Widget build(BuildContext context) {
+ final readings = [
+ for (final machine in usage.machines) ...machine.readings,
+ ];
+ if (readings.isEmpty) {
+ // Nothing answered at all. On a phone that is almost always the same
+ // thing as "no machine is linked and connected yet", which is the action
+ // worth naming — a Retry here would retry a question nobody was asked.
+ return EmptyState(
+ icon: LucideIcons.monitorSmartphone300,
+ title: 'No usage data',
+ message: usage.stale
+ ? 'The machines you linked did not answer this time. Pull down to try again.'
+ : 'Link a machine and connect to it — usage is read on the machine '
+ 'your agents run on, not on this phone.',
+ );
+ }
+ final signedOut = [
+ for (final reading in readings)
+ if (reading.status == UsageStatus.signedOut) reading,
+ ];
+ if (signedOut.isNotEmpty) {
+ return EmptyState(
+ icon: LucideIcons.logIn300,
+ title: 'Not signed in',
+ message:
+ '${_providers(signedOut)} on your linked machines have no session '
+ 'to read. Sign in there with the agent CLI — this phone cannot do '
+ 'it for them.',
+ );
+ }
+ final failed = [
+ for (final reading in readings)
+ if (reading.status == UsageStatus.failed) reading,
+ ];
+ if (failed.isNotEmpty) {
+ return EmptyState(
+ icon: LucideIcons.triangleAlert300,
+ title: 'Could not read usage',
+ // The machine's own sentence when there is exactly one, because it is
+ // the side that knows what went wrong; past that a list of them would
+ // be longer than the screen.
+ message: failed.length == 1
+ ? (failed.first.message ?? 'Pull down to try again.')
+ : '${_providers(failed)} did not answer. Pull down to try again.',
+ );
+ }
+ return const EmptyState(
+ icon: LucideIcons.chartNoAxesColumn300,
+ title: 'No usage to show',
+ message: 'The machines that answered reported no rate-limit windows.',
+ );
+ }
+
+ /// The providers named once each, in [UsageProvider] order — two machines
+ /// signed out of the same account are one sentence, not two.
+ static String _providers(List<ProviderUsage> readings) {
+ final seen = <UsageProvider>{for (final reading in readings) reading.provider};
+ final labels = [
+ for (final provider in UsageProvider.values)
+ if (seen.contains(provider)) provider.label,
+ ];
+ if (labels.isEmpty) return 'Your accounts';
+ if (labels.length == 1) return labels.single;
+ return '${labels.take(labels.length - 1).join(', ')} and ${labels.last}';
+ }
+}
+
+/// One account: its provider, where it was read, its weekly figure — and, once
+/// expanded, every window it reports.
+///
+/// Expanding in place rather than pushing a page of its own: an account has at
+/// most three windows, which is less than a page's worth of anything, and the
+/// comparison a reader came for is between the accounts rather than inside one.
+class _AccountCard extends StatefulWidget {
+ const _AccountCard({super.key, required this.account});
+
+ final UsageAccount account;
+
+ @override
+ State<_AccountCard> createState() => _AccountCardState();
+}
+
+class _AccountCardState extends State<_AccountCard> {
+ bool _expanded = false;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final reading = widget.account.reading;
+ // ⚠️ ONE window in the headline — the weekly one, never all of them. See
+ // [ProviderUsage.railWindow]: Claude reports three and Codex one, so a
+ // headline showing every window would make one account three figures tall
+ // and the other one, two cards that read as different KINDS of thing.
+ final headline = reading.railWindow;
+ final colour = engineIdentity(reading.provider.engineId).color;
+ // Every window BUT the headline is what expanding adds; a card whose
+ // provider reports only the one has nothing to expand and says so by not
+ // offering the chevron at all.
+ final expandable = reading.windows.length > 1;
+ return Container(
+ decoration: BoxDecoration(
+ color: AppGlass.rowFill,
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ border: Border.all(color: AppGlass.hair),
+ ),
+ child: Material(
+ color: Colors.transparent,
+ child: InkWell(
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ onTap: expandable ? () => setState(() => _expanded = !_expanded) : null,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(13, 12, 13, 13),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _CardHeader(
+ account: widget.account,
+ expandable: expandable,
+ expanded: _expanded,
+ ),
+ if (headline != null) ...[
+ const SizedBox(height: 12),
+ _WindowRow(window: headline, color: colour),
+ ],
+ if (_expanded)
+ for (final window in reading.windows)
+ if (!identical(window, headline)) ...[
+ const SizedBox(height: 14),
+ _WindowRow(window: window, color: colour),
+ ],
+ if (reading.fetchedAt != null) ...[
+ const SizedBox(height: 10),
+ Text(
+ _freshness(reading.fetchedAt!),
+ style: TextStyle(
+ color: AppPalette.textFaint,
+ fontSize: 11.5,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ /// How long ago the figures were read, at the granularity the poll actually
+ /// has. Anything finer would be a precision the once-a-minute refresh behind
+ /// it cannot back up.
+ static String _freshness(DateTime at) {
+ final since = DateTime.now().difference(at);
+ if (since.inMinutes < 1) return 'Updated just now';
+ if (since.inMinutes < 60) return 'Updated ${since.inMinutes}m ago';
+ return 'Updated ${since.inHours}h ago';
+ }
+}
+
+class _CardHeader extends StatelessWidget {
+ const _CardHeader({
+ required this.account,
+ required this.expandable,
+ required this.expanded,
+ });
+
+ final UsageAccount account;
+ final bool expandable;
+ final bool expanded;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final machines = account.machines;
+ return Row(
+ children: [
+ // The mark the agent list already draws beside every agent of this
+ // engine — the account's own logo, in its own colour. A second glyph
+ // here would make one account look like two things.
+ EngineMark(engine: account.provider.engineId, size: 16),
+ const SizedBox(width: 9),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ account.provider.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textPrimary,
+ fontSize: 15,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ // WHERE this was read. Unlike the desktop, which leaves its own
+ // computer's figure unlabelled because that is the one a person
+ // reads as "mine", every figure on a phone was read somewhere
+ // else — so every figure says where, and an account shared by
+ // several machines names them all rather than picking one.
+ if (machines.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(
+ machines.join(', '),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textSecondary,
+ fontSize: 12.5,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ if (expandable)
+ Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: AnimatedRotation(
+ turns: expanded ? 0.5 : 0,
+ duration: AppMotion.press,
+ curve: AppMotion.curve,
+ child: Icon(
+ LucideIcons.chevronDown300,
+ size: 20,
+ color: AppPalette.textFaint,
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+/// One window: what it is, how full it is, and when it empties.
+class _WindowRow extends StatelessWidget {
+ const _WindowRow({required this.window, required this.color});
+
+ final UsageWindow window;
+
+ /// The account's own colour, so the bar and the mark at the top of the card
+ /// are visibly the same account's.
+ final Color color;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final resetsIn = window.resetsInLabel();
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ window.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textSecondary,
+ fontSize: 12.5,
+ fontWeight: AppFont.medium,
+ ),
+ ),
+ ),
+ Text(
+ '${window.usedPercent.round()}% used',
+ style: TextStyle(
+ // Amber past 80, red past 90. The figure is exact either way,
+ // so the colour is not carrying the number — it is carrying the
+ // moment the number starts to matter.
+ color: usagePressureInk(window.pressure, AppPalette.textPrimary),
+ fontSize: 13.5,
+ fontWeight: FontWeight.w600,
+ fontFeatures: AppFont.tabularFigures,
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 7),
+ UsageBar(usedPercent: window.usedPercent, color: color),
+ // No reset time means no countdown — never "resets in 0m", which would
+ // read as a measurement rather than as the silence it is.
+ if (resetsIn != null) ...[
+ const SizedBox(height: 6),
+ Text(
+ 'Resets in $resetsIn',
+ style: TextStyle(color: AppPalette.textFaint, fontSize: 11.5),
+ ),
+ ],
+ ],
+ );
+ }
+}
+
+/// The colour a nearly-spent window is drawn in, over the [UsagePressure.calm]
+/// colour it wears the rest of the time.
+///
+/// One function for the figure and the bar under it, so a window cannot be
+/// amber in one and plain in the other.
+///
+/// ⚠️ [AppColors.danger] rather than `AppPalette.dangerFill`: this is ink on a
+/// surface, and the fill is tuned to carry white lettering ON it.
+Color usagePressureInk(UsagePressure pressure, Color calm) =>
+ switch (pressure) {
+ UsagePressure.calm => calm,
+ UsagePressure.warn => AppPalette.warn,
+ UsagePressure.critical => AppColors.danger,
+ };
+
+/// How full one window is.
+///
+/// Drawn 6px and fully rounded, in the **account's own colour** — the same
+/// colour as the mark at the head of the card. Turns amber past
+/// [kUsageWarnPercent] and red past [kUsageCriticalPercent], from the same
+/// [usagePressureOf] the figure above it uses: a bar that changed hue at a
+/// different number would make one window look like two readings.
+class UsageBar extends StatelessWidget {
+ const UsageBar({
+ super.key,
+ required this.usedPercent,
+ required this.color,
+ this.height = 6,
+ });
+
+ final double usedPercent;
+
+ /// The account's colour. Overridden once the window is nearly spent, because
+ /// "which account" matters less at that point than "how close".
+ final Color color;
+
+ final double height;
+
+ /// The narrowest the filled part may be drawn.
+ ///
+ /// Below this a band of colour reads as a rendering artefact rather than a
+ /// quantity, so a small percentage is over-represented on purpose. A window
+ /// at 2% is *not* a window at 0%, and the bar has to be able to say so — the
+ /// exact figure is printed right above it, so nothing is lost by rounding up.
+ static const double _minFill = 4;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final fill = usagePressureInk(usagePressureOf(usedPercent), color);
+ return ClipRRect(
+ borderRadius: BorderRadius.circular(height / 2),
+ child: SizedBox(
+ height: height,
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final full = constraints.maxWidth;
+ final measured = full * (usedPercent / 100).clamp(0.0, 1.0);
+ // Zero stays zero: an untouched window draws no colour at all, or
+ // the bar would claim usage nobody has spent.
+ final width = measured <= 0
+ ? 0.0
+ : measured.clamp(_minFill, full).toDouble();
+ // BOTH children are positioned, deliberately. A Stack takes its
+ // size from its non-positioned children, so an unpositioned fill
+ // would drag the track in to the fill's own width — the right
+ // length in the wrong colour.
+ return Stack(
+ children: [
+ Positioned.fill(child: ColoredBox(color: AppSurface.recess)),
+ Positioned(
+ left: 0,
+ top: 0,
+ bottom: 0,
+ width: width,
+ child: ColoredBox(color: fill),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ );
+ }
+}
+
+/// The summary a settings row prints for the whole page — the tightest weekly
+/// figure across every account, because the one worth a glance from a list of
+/// rows is the account closest to running out.
+///
+/// Null when there is nothing to summarise, which the row draws as `—` rather
+/// than as a zero it never measured.
+String? usageSummaryLabel(List<UsageAccount> accounts) {
+ double? worst;
+ for (final account in accounts) {
+ final window = account.reading.railWindow;
+ if (window == null || !account.reading.hasFigures) continue;
+ if (worst == null || window.usedPercent > worst) {
+ worst = window.usedPercent;
+ }
+ }
+ return worst == null ? null : '${worst.round()}% used';
+}
diff --git a/mobile/lib/state/attention.dart b/mobile/lib/state/attention.dart
new file mode 100644
index 000000000..2627b5c74
--- /dev/null
+++ b/mobile/lib/state/attention.dart
@@ -0,0 +1,106 @@
+import 'package:harness_mobile/phone/agent_index.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/pending_question.dart';
+
+/// One agent that has stopped to ask the person something, together with everything needed to
+/// draw it and to open it.
+///
+/// The desktop's equivalent (`state/swarm_attention.dart`) is built out of `SwarmDestination`s,
+/// because there a selection has to decide WHICH pane of WHICH swarm the agent lands in. A phone
+/// has neither: one tap, one full-screen terminal. So this carries the agent itself instead, and
+/// the whole destination/ranking half of the desktop file is dropped rather than ported into a
+/// shape nothing here would read.
+class AttentionEntry {
+ const AttentionEntry({required this.agent, required this.question});
+
+ /// The agent and its machine, from the same [agentIndex] the Agents tab and the tab badge are
+ /// built from — so a row here cannot exist for an agent the list refuses to draw.
+ final AgentEntry agent;
+
+ /// What it is asking, when the question is still on screen at the other end.
+ ///
+ /// ⚠️ Nullable on purpose, and not the same thing as "no question". `blockedAgents` is what marks
+ /// an agent as waiting in the first place, so in practice this is set — but the entry is built
+ /// from the agent index rather than from the question map, and a row that vanished because its
+ /// prompt text was momentarily unavailable would be worse than one drawn without its prompt.
+ final PendingQuestion? question;
+
+ String get machineId => agent.machineId;
+ String get machineName => agent.machineName;
+ String get agentId => agent.agent.id;
+
+ /// Stable across rebuilds — a machine and an agent, the pair the app keys everything else on.
+ String get id => '$machineId/$agentId';
+
+ /// The question as a row prints it: one line, whitespace collapsed.
+ ///
+ /// A prompt arrives as whatever the pane held, newlines and runs of spaces included, and a
+ /// `maxLines: 2` `Text` of that draws a mostly-empty box. Collapsing here rather than in the
+ /// widget keeps the trimming with the data, the way the desktop keeps its search fields.
+ String? get promptLine {
+ final prompt = question?.prompt.replaceAll(RegExp(r'\s+'), ' ').trim();
+ return prompt == null || prompt.isEmpty ? null : prompt;
+ }
+}
+
+/// Every agent waiting on an answer, oldest question first.
+///
+/// Ordered by [PendingQuestion.since] like the desktop's picker, for the same reason: the one that
+/// has been waiting longest is the one holding work up. Ties — and an agent whose question is not
+/// in the map — fall back to [AttentionEntry.id] so the list cannot reshuffle itself under a
+/// finger already reaching for a row.
+List<AttentionEntry> attentionEntries(AppNotifier notifier) {
+ final entries = [
+ for (final agent in waitingAgents(agentIndex(notifier)))
+ AttentionEntry(
+ agent: agent,
+ question: notifier.questionFor(agent.machineId, agent.agent.id),
+ ),
+ ];
+ entries.sort((a, b) {
+ final aSince = a.question?.since;
+ final bSince = b.question?.since;
+ if (aSince != null && bSince != null) {
+ final age = aSince.compareTo(bSince);
+ if (age != 0) return age;
+ } else if (aSince != bSince) {
+ // An entry with no question sorts last: it is the one we know least about.
+ return aSince == null ? 1 : -1;
+ }
+ return a.id.compareTo(b.id);
+ });
+ return entries;
+}
+
+/// The same entries, grouped by machine and keeping the order above within each group.
+///
+/// The machines themselves are ordered by their most urgent entry — the first one [attentionEntries]
+/// produced for them — so a machine whose agent has waited longest heads the page. Anything else
+/// (account order, alphabetical) would bury the row the page exists to surface.
+List<AttentionGroup> attentionGroups(List<AttentionEntry> entries) {
+ final byMachine = <String, List<AttentionEntry>>{};
+ for (final entry in entries) {
+ (byMachine[entry.machineId] ??= []).add(entry);
+ }
+ return [
+ for (final rows in byMachine.values)
+ AttentionGroup(
+ machineId: rows.first.machineId,
+ machineName: rows.first.machineName,
+ entries: List.unmodifiable(rows),
+ ),
+ ];
+}
+
+/// One machine's worth of waiting agents.
+class AttentionGroup {
+ const AttentionGroup({
+ required this.machineId,
+ required this.machineName,
+ required this.entries,
+ });
+
+ final String machineId;
+ final String machineName;
+ final List<AttentionEntry> entries;
+}
diff --git a/mobile/lib/usage/usage_controller.dart b/mobile/lib/usage/usage_controller.dart
new file mode 100644
index 000000000..0848de6ca
--- /dev/null
+++ b/mobile/lib/usage/usage_controller.dart
@@ -0,0 +1,221 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import 'package:harness_mobile/core/test_run.dart';
+import 'usage_accounts.dart';
+import 'usage_source.dart';
+import 'usage_window.dart';
+
+/// What each agent account has spent, kept current for the usage page.
+///
+/// Polling, because neither vendor pushes, and neither figure moves fast enough
+/// to be worth a socket. A minute is also the granularity the countdowns are
+/// printed at, so a faster poll would redraw the same minute.
+///
+/// **The last good reading stays on screen through a failed refresh** — a page
+/// that blanked whenever a network hiccup landed would be worse than one that
+/// quietly went [stale].
+///
+/// ⚠️ **Deliberately different from the desktop's controller in ONE way: this
+/// one reads no LOCAL sources.** The desktop constructs
+/// `[ClaudeUsageSource(), CodexUsageSource()]` by default, because the machine
+/// it runs on is also the machine `claude login` and `codex login` wrote their
+/// tokens on — the macOS Keychain item `Claude Code-credentials`,
+/// `~/.claude/.credentials.json`, `~/.codex/auth.json`. **A phone has none of
+/// those**, and never will: no agent CLI ever signs in here, and the sandbox
+/// has no `~` in the sense those paths mean. `UsageCredentials` would answer
+/// null for every one of them — safely, since it only ever `existsSync`s a file
+/// and skips the Keychain off macOS — but the readings it produced would all be
+/// [UsageStatus.signedOut], which is the exact wrong sentence: it invites the
+/// reader to sign in on a device where signing in is not a thing that exists,
+/// and the empty state it drives would hide the real answer, that no machine
+/// has been linked yet.
+///
+/// So on the phone the sources list is EMPTY and every figure comes from
+/// `usage_read` over the relay — see [remote] and `AppNotifier.readRemoteUsage`.
+/// The seam is kept rather than removed: the parameter still takes sources, so
+/// the grouping, the statuses and this file's shape stay identical to the
+/// desktop's, and a build that one day has a local account to read needs no new
+/// controller.
+class UsageController extends ChangeNotifier {
+ UsageController({
+ List<UsageSource> sources = const [],
+ this.remote,
+ this.interval = const Duration(seconds: 60),
+ bool autoStart = true,
+ }) : _sources = List.unmodifiable(sources) {
+ for (final source in _sources) {
+ _readings[source.provider] = ProviderUsage.loading(source.provider);
+ }
+ // Never on its own under test: a periodic timer stops `pumpAndSettle` ever
+ // settling, and a cycle here opens real sockets over the relay. A test that
+ // wants a cycle asks for one with [refresh], or starts the timer itself.
+ if (autoStart && !kUnderTest) start();
+ }
+
+ /// This device's own accounts. Empty on the phone — see the class comment.
+ final List<UsageSource> _sources;
+
+ /// Asks every connected remote machine what ITS accounts have spent
+ /// (`AppNotifier.readRemoteUsage`). Null asks nobody, which on the phone
+ /// means there is nothing to read at all.
+ final Future<List<MachineUsage>> Function()? remote;
+
+ List<MachineUsage> _remote = const [];
+ int _remoteRequest = 0;
+
+ /// How often to ask again.
+ final Duration interval;
+
+ final Map<UsageProvider, ProviderUsage> _readings = {};
+
+ Timer? _timer;
+ bool _disposed = false;
+ int _request = 0;
+
+ /// A cycle has been asked for and none has landed yet.
+ ///
+ /// Both halves matter. It is false before [start], because a controller
+ /// nobody has started is not *waiting* for anything — and a page that drew a
+ /// skeleton for it would be promising an answer that was never coming. It is
+ /// false again after the first cycle lands, so a later refresh keeps the
+ /// figures already on screen rather than replacing them with skeletons once a
+ /// minute.
+ bool get loading => _started && !_landed;
+
+ bool _started = false;
+ bool _landed = false;
+
+ /// The last cycle failed for every provider and what is on screen is older
+ /// than it looks.
+ ///
+ /// With no local sources this can only be false — `every` over an empty list
+ /// is true, so it is computed from the remote half here instead: a cycle in
+ /// which every machine that was asked failed to answer is exactly the same
+ /// claim the desktop makes about its two sources.
+ bool stale = false;
+
+ /// Every LOCAL provider's reading, in the order the sources were given. Empty
+ /// on the phone, which is what makes [accounts] entirely remote.
+ List<ProviderUsage> get readings => [
+ for (final source in _sources) _readings[source.provider]!,
+ ];
+
+ /// The providers with figures worth printing.
+ List<ProviderUsage> get answered => [
+ for (final reading in readings)
+ if (reading.hasFigures) reading,
+ ];
+
+ /// One figure per ACCOUNT, this device's first — see [groupUsageAccounts].
+ ///
+ /// [readings] stays this device's alone; this is the grouped view. On the
+ /// phone every entry comes from a machine across the relay, so every entry
+ /// carries the machine label that names it.
+ List<UsageAccount> get accounts => groupUsageAccounts(readings, _remote);
+
+ /// The machines that answered the last cycle, in the order they answered.
+ /// Empty is a real answer here rather than a blank: it is what "no machine
+ /// has anything to say" looks like once [hasAnswer] is true.
+ List<MachineUsage> get machines => _remote;
+
+ /// Whether the page has anything at all to say — figures, or a reason there
+ /// are none. False only before the first cycle resolves.
+ ///
+ /// The remote half is what decides it here, since there are no local
+ /// readings to move out of [UsageStatus.loading].
+ bool get hasAnswer =>
+ _landed || readings.any((r) => r.status != UsageStatus.loading);
+
+ void start() {
+ if (_disposed || _timer != null) return;
+ _started = true;
+ unawaited(refresh());
+ _timer = Timer.periodic(interval, (_) => unawaited(refresh()));
+ }
+
+ /// This device's accounts and every remote machine's, asked at once — and
+ /// landing apart. A remote machine is a relay round trip away and may never
+ /// answer at all (see `AppNotifier.readRemoteUsage`), so it must not hold up
+ /// figures this device already has. Each half notifies when it lands; the
+ /// future completes when both have.
+ Future<void> refresh() async {
+ await Future.wait([_refreshLocal(), _refreshRemote()]);
+ }
+
+ Future<void> _refreshRemote() async {
+ final ask = remote;
+ if (ask == null) {
+ // Nothing to ask, and nothing to wait for: the first cycle has still
+ // RESOLVED, so the page shows its empty state rather than a skeleton
+ // that would sit there for the life of the screen.
+ if (_disposed) return;
+ _started = true;
+ _landed = true;
+ notifyListeners();
+ return;
+ }
+ final request = ++_remoteRequest;
+ _started = true;
+ final List<MachineUsage> answers;
+ try {
+ answers = await ask();
+ } catch (_) {
+ // Keep the last good answer, the same rule the local half follows — but
+ // the cycle has still resolved, so a first refresh that threw shows the
+ // empty state instead of loading forever. What is on screen, if anything,
+ // is now older than it looks.
+ if (_disposed || request != _remoteRequest) return;
+ _landed = true;
+ stale = _remote.isNotEmpty;
+ notifyListeners();
+ return;
+ }
+ // A slower, older answer must not overwrite a newer one.
+ if (_disposed || request != _remoteRequest) return;
+ // ⚠️ A cycle that came back EMPTY while figures are on screen does not
+ // overwrite them — it marks them stale. `readRemoteUsage` drops a machine
+ // that timed out rather than reporting it, so "no machine answered" and
+ // "every machine answered with nothing" arrive identically, and blanking a
+ // whole page on one bad relay round trip is the failure this rule exists to
+ // prevent. An app with nothing linked lands here too, with `_remote` empty
+ // both before and after, and is not stale — it has nothing, not something
+ // old.
+ if (answers.isEmpty && _remote.isNotEmpty) {
+ _landed = true;
+ stale = true;
+ notifyListeners();
+ return;
+ }
+ _remote = answers;
+ _landed = true;
+ stale = false;
+ notifyListeners();
+ }
+
+ Future<void> _refreshLocal() async {
+ if (_sources.isEmpty) return;
+ _started = true;
+ final request = ++_request;
+ final results = await Future.wait(_sources.map((s) => s.read()));
+ // A refresh that finished after a newer one started is thrown away: its
+ // figures are the older truth, and writing them would make the page count
+ // backwards.
+ if (_disposed || request != _request) return;
+ for (final result in results) {
+ _readings[result.provider] = result;
+ }
+ _landed = true;
+ stale = results.every((r) => r.status == UsageStatus.failed);
+ notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _timer?.cancel();
+ _timer = null;
+ super.dispose();
+ }
+}
diff --git a/mobile/lib/usage/usage_pressure.dart b/mobile/lib/usage/usage_pressure.dart
new file mode 100644
index 000000000..7002cd48b
--- /dev/null
+++ b/mobile/lib/usage/usage_pressure.dart
@@ -0,0 +1,34 @@
+import 'usage_window.dart';
+
+/// How close a rate-limit window is to being spent.
+///
+/// Two thresholds, one step each: [warn] turns a figure amber and [critical]
+/// turns it red. A third shade between them would be one nobody could name.
+enum UsagePressure {
+ calm,
+
+ /// Amber. The window is worth noticing on the way past.
+ warn,
+
+ /// Red. The window is nearly spent.
+ critical,
+}
+
+/// Where a window starts reading amber.
+///
+/// The figure beside it is already exact, so this number is not carrying the
+/// quantity — it is carrying the moment the quantity starts to matter.
+const double kUsageWarnPercent = 80;
+
+/// Where a window starts reading red.
+const double kUsageCriticalPercent = 90;
+
+UsagePressure usagePressureOf(double usedPercent) {
+ if (usedPercent >= kUsageCriticalPercent) return UsagePressure.critical;
+ if (usedPercent >= kUsageWarnPercent) return UsagePressure.warn;
+ return UsagePressure.calm;
+}
+
+extension UsageWindowPressure on UsageWindow {
+ UsagePressure get pressure => usagePressureOf(usedPercent);
+}