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.

fix(mobile): Android fonts, usage headline, newline key

tony43c3d92669a7
diff --git a/mobile/lib/phone/terminal_input_dock.dart b/mobile/lib/phone/terminal_input_dock.dart
index 63fa5ef2b..f518876e8 100644
--- a/mobile/lib/phone/terminal_input_dock.dart
+++ b/mobile/lib/phone/terminal_input_dock.dart
@@ -133,6 +133,9 @@ class _TerminalInputDockState extends State<TerminalInputDock>
onPickImage: widget.onPickImage,
onTakePhoto: widget.onTakePhoto,
questionOpen: widget.questionOpen,
+ // An agent's prompt takes `↵`; a plain shell does not — see
+ // [TerminalKeyBar.enginePrompt].
+ enginePrompt: widget.session.engineId != 'terminal',
hints: widget.hints,
ctrlArmed: widget.session.controlArmed,
onArmCtrl: widget.session.armControl,
diff --git a/mobile/lib/phone/terminal_key_bar.dart b/mobile/lib/phone/terminal_key_bar.dart
index bfde97ad1..9d30d2db1 100644
--- a/mobile/lib/phone/terminal_key_bar.dart
+++ b/mobile/lib/phone/terminal_key_bar.dart
@@ -32,18 +32,22 @@ import 'tty.dart';
/// phone keyboard cannot produce, or buries, and a pane is driven by:
///
/// ```
-/// esc ^C tab clear paste ⇧ ctrl ← ↑ ↓ → │ img ▾
+/// esc ^C tab clear paste ⇧ ctrl ← ↑ ↓ → ↵ │ img ▾
/// ```
///
/// Every key stays in the same place every time; this strip is used while
/// looking at the TERMINAL, not at the strip.
///
-/// ⚠️ **One exception: `/` becomes `⏎` while an agent is asking something.**
+/// `↵` is a new line in an engine's prompt, without sending the turn: the
+/// keyboard's own `return` submits, and nothing else a phone has can break a
+/// line. See [TerminalKeyBar.enginePrompt].
+///
+/// ⚠️ **One exception: `↵` becomes `⏎` while an agent is asking something.**
/// A question dialog is driven by the arrows and Enter, and Enter is the one
/// the strip did not have — the keyboard's own `return` sends it, but nothing
/// on screen says so, and on a dialog that reads "enter to submit answer" a
-/// strip of every other key it names reads as "Enter is missing". `/` is the
-/// slot to give up: a dialog has no prompt to start a command in.
+/// strip of every other key it names reads as "Enter is missing". `↵` is the
+/// slot to give up: a dialog has no prompt to add a line to.
///
/// ⚠️ **The other exception: the pane's own keys — [hints] — join the row, and
/// only then does it scroll.** They are what Codex offers on this screen and
@@ -69,6 +73,7 @@ class TerminalKeyBar extends StatefulWidget {
this.onPickImage,
this.onTakePhoto,
this.questionOpen = false,
+ this.enginePrompt = false,
this.hints = const [],
this.ctrlArmed,
this.onArmCtrl,
@@ -82,10 +87,18 @@ class TerminalKeyBar extends StatefulWidget {
final bool? ctrlArmed;
final ValueChanged<bool>? onArmCtrl;
- /// An agent's question dialog is on the pane: `/` gives its slot to `⏎` —
+ /// An agent's question dialog is on the pane: `↵` gives its slot to `⏎` —
/// see the class docblock.
final bool questionOpen;
+ /// The pane runs an engine, whose prompt takes `↵`: what a hardware ⌥⏎
+ /// sends — ESC, then the Return bytes — which Claude Code, Codex and every
+ /// other Ink/readline prompt read as "add a line, do not send this turn yet"
+ /// (`MetaEnterInputHandler`). Sent through the pane's own input handler,
+ /// so the two cannot differ. Not on a plain shell, the `terminal` engine,
+ /// where ESC + Return is no newline: false leaves the key out.
+ final bool enginePrompt;
+
/// The keys the pane's chrome offers and a phone cannot press — see
/// [parseKeyHints]. Each is drawn as the key and Codex's own word for what
/// it does, as the pane printed them, in the terminal's face — so it reads
@@ -385,6 +398,25 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>
// Sent as the key, not as text: the keyboard's buffer holds nothing
// a dialog cares about, and Return is `\r` to every TUI here.
onTap: () => _sendKey(TerminalKey.enter),
+ )
+ // The same slot at a prompt: a new line, not a submit — see
+ // [TerminalKeyBar.enginePrompt]. In the slot `⏎` takes rather than one
+ // of its own, so the row is never more keys than a question already
+ // makes it.
+ else if (widget.enginePrompt)
+ _key(
+ label: '↵',
+ semanticLabel: 'Newline',
+ onTap: () {
+ // ⌥⏎ is the whole chord: an armed `ctrl` would make it ⌃⌥⏎, which
+ // the prompt does not read as a line, so like `^C` this puts the
+ // modifiers down rather than adding them.
+ _disarm();
+ widget.terminal.keyInput(TerminalKey.enter, alt: true);
+ // The keyboard's buffer still holds the line just broken — as
+ // after a hardware Return, which empties it too.
+ widget.onPromptEdited?.call();
+ },
),
];
// ⚠️ **Neither of these sends a byte anywhere**, and that is why they sit
diff --git a/mobile/lib/phone/usage_entry.dart b/mobile/lib/phone/usage_entry.dart
index 0690fe8bc..bcf1ad47b 100644
--- a/mobile/lib/phone/usage_entry.dart
+++ b/mobile/lib/phone/usage_entry.dart
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/usage/usage_summary.dart';
import 'phone_navigation.dart';
import 'settings_row.dart';
@@ -15,10 +16,11 @@ import 'usage_page.dart';
/// 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.
+/// The value is what the account closest to running out has left of its
+/// tightest window, worded as the Usage page heads its card — the one worth a
+/// glance from a list of rows, since that account is the one that will stop
+/// the work. Nothing when nothing has been read yet, never a zero — `0%
+/// remaining` is a measurement, and this has none.
Widget buildUsageSettingsRow(
BuildContext context,
AppNotifier notifier,
diff --git a/mobile/lib/phone/usage_page.dart b/mobile/lib/phone/usage_page.dart
index d9029a419..0330c5130 100644
--- a/mobile/lib/phone/usage_page.dart
+++ b/mobile/lib/phone/usage_page.dart
@@ -4,32 +4,16 @@ 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_summary.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
@@ -80,7 +64,8 @@ class _UsagePageState extends State<UsagePage> {
super.dispose();
}
- /// Hands the Settings row the figure this cycle came to.
+ /// Hands the Settings row the figure this cycle came to — see
+ /// [lastUsageSummary].
///
/// 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
@@ -258,8 +243,8 @@ class _EmptyUsage extends StatelessWidget {
}
}
-/// One account: its provider, where it was read, its weekly figure — and, once
-/// expanded, every window it reports.
+/// One account: its provider, where it was read, what is left of its tightest
+/// window — 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
@@ -280,11 +265,12 @@ class _AccountCardState extends State<_AccountCard> {
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;
+ // ⚠️ ONE window in the headline — the tightest, never all of them: 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. The tightest, as on the desktop and on
+ // this phone's own model sheet — see [ProviderUsage.tightest].
+ final headline = reading.tightest;
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
@@ -460,9 +446,9 @@ class _WindowRow extends StatelessWidget {
),
),
Text(
- '${window.usedPercent.round()}% used',
+ window.remainingLabel,
style: TextStyle(
- // Amber past 80, red past 90. The figure is exact either way,
+ // Amber at 20% left, red at 5%. 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),
@@ -493,24 +479,26 @@ class _WindowRow extends StatelessWidget {
/// 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.
+/// amber in one and plain in the other. The desktop's allowance colours, so one
+/// subscription reads the same on both — muted, and a red of their own, since a
+/// limit coming up is not an app error.
Color usagePressureInk(UsagePressure pressure, Color calm) =>
switch (pressure) {
UsagePressure.calm => calm,
- UsagePressure.warn => AppPalette.warn,
- UsagePressure.critical => AppColors.danger,
+ UsagePressure.warn => AppPalette.usageLow,
+ UsagePressure.critical => AppPalette.usageCritical,
};
-/// How full one window is.
+/// What is left of one window.
+///
+/// Filled with the REMAINDER, as the desktop's meter is: under a figure that
+/// says `80% remaining`, a bar a fifth full would read as the opposite.
///
/// 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.
+/// colour as the mark at the head of the card. Turns amber at
+/// [kUsageLowRemaining] left and red at [kUsageCriticalRemaining], 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,
@@ -519,6 +507,8 @@ class UsageBar extends StatelessWidget {
this.height = 6,
});
+ /// How much of the window is spent, as the vendor reports it. The bar draws
+ /// what is left of it.
final double usedPercent;
/// The account's colour. Overridden once the window is nearly spent, because
@@ -531,8 +521,9 @@ class UsageBar extends StatelessWidget {
///
/// 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.
+ /// with 2% left is *not* one with nothing left, 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
@@ -546,9 +537,12 @@ class UsageBar extends StatelessWidget {
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 left = usageRemainingOf(usedPercent);
+ final measured = left.isFinite
+ ? full * (left / 100).clamp(0.0, 1.0)
+ : 0.0;
+ // Zero stays zero: a spent window draws no colour at all, or the
+ // bar would claim an allowance that is gone.
final width = measured <= 0
? 0.0
: measured.clamp(_minFill, full).toDouble();
@@ -575,20 +569,20 @@ class UsageBar extends StatelessWidget {
}
}
-/// 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.
+/// The summary a settings row prints for the whole page — the headline of the
+/// account with the least left, worded as its card words it, 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.
+/// Null when there is nothing to summarise, which the row leaves blank rather
+/// than printing a figure it never measured.
String? usageSummaryLabel(List<UsageAccount> accounts) {
- double? worst;
+ UsageWindow? worst;
for (final account in accounts) {
- final window = account.reading.railWindow;
+ final window = account.reading.tightest;
if (window == null || !account.reading.hasFigures) continue;
- if (worst == null || window.usedPercent > worst) {
- worst = window.usedPercent;
+ if (worst == null || window.usedPercent > worst.usedPercent) {
+ worst = window;
}
}
- return worst == null ? null : '${worst.round()}% used';
+ return worst?.remainingLabel;
}
diff --git a/mobile/lib/shared/theme/app_theme.dart b/mobile/lib/shared/theme/app_theme.dart
index 6072769ca..4036401d5 100644
--- a/mobile/lib/shared/theme/app_theme.dart
+++ b/mobile/lib/shared/theme/app_theme.dart
@@ -354,6 +354,15 @@ abstract final class AppPalette {
static Color get warn =>
AppTheme.pick(const Color(0xFF9A4708), const Color(0xFFFFB020));
+ /// A quiet allowance limit, distinct from an app error — the desktop's own, so
+ /// one subscription reads the same colour on both (20% or less left).
+ static Color get usageLow =>
+ AppTheme.pick(const Color(0xFF87632A), const Color(0xFFC4A46C));
+
+ /// Remaining subscription capacity is nearly exhausted (5% or less).
+ static Color get usageCritical =>
+ AppTheme.pick(const Color(0xFFB3261E), const Color(0xFFFF7068));
+
// grey dot — a state mark, so ≥3:1 in light (3.14 on Paper's search ground).
static Color get offline =>
AppTheme.pick(const Color(0xFF7F7E78), const Color(0xFF6E6E6E));
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 07f73d8e2..e725be3f1 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -64,6 +64,7 @@ import 'search_when.dart';
import 'session_content_search.dart';
import '../usage/remote_usage.dart';
import '../usage/usage_accounts.dart';
+import '../usage/usage_summary.dart';
import '../phone/phone_name_store.dart';
import '../viewer/device_log.dart';
import '../viewer/device_history.dart';
@@ -1642,6 +1643,8 @@ class AppNotifier extends ChangeNotifier {
unawaited(_machineCache?.clear());
sessionPreviews.clear();
agentNotices.reset();
+ // The Settings row's usage figure was this account's — see [lastUsageSummary].
+ lastUsageSummary.value = null;
expandedMachines.clear();
selectedMachineId = null;
// ⚠️ The saved session goes too. The socket that said so (a refresh refused, 4403) is the only
@@ -1878,6 +1881,9 @@ class AppNotifier extends ChangeNotifier {
// sign-in code: held for the sign-in it asked for, not the one after this.
pendingPairing = null;
pendingComputerSignIn = null;
+ // The Settings row's usage figure was this account's — see [lastUsageSummary]. Here, before the
+ // awaits below: a sign-in started meanwhile ends this early, and must not inherit the figure.
+ lastUsageSummary.value = null;
_closedHistory.clear();
// Best-effort and fire-and-forget: local state is cleared below regardless, but the saved
// session goes too, so the NEXT launch doesn't silently sign back in without ever showing the
diff --git a/mobile/lib/terminal/terminal_font_store.dart b/mobile/lib/terminal/terminal_font_store.dart
index db623cce3..84d8b496a 100644
--- a/mobile/lib/terminal/terminal_font_store.dart
+++ b/mobile/lib/terminal/terminal_font_store.dart
@@ -1,3 +1,5 @@
+import 'dart:io' show Platform;
+
import '../core/apple_fonts.dart';
import 'package:flutter/foundation.dart';
@@ -24,9 +26,15 @@ import 'terminal_typography.dart';
/// `Ubuntu Sans Mono` is the 25.04-and-later family and `Ubuntu Mono` the older
/// one, so both are listed rather than guessing the release.
///
+/// Android has a list of its own, the two faces it ships under the names its
+/// `fonts.xml` gives them (see `androidTerminalFontFamily`). It ships none of
+/// the Apple faces or the Linux ones, and while it was offered the Linux list
+/// every pick drew the same Droid Sans Mono.
+///
/// Every value exists on every platform. A `state.json` written on a Mac and
/// carried to a Linux box still loads, and the Settings dropdown keeps showing
-/// whatever is actually selected (see `_FamilyDropdown`).
+/// whatever is actually selected (see `_FamilyDropdown`). Android is the
+/// exception — see [TerminalFontStore.load].
enum TerminalFontChoice {
sfMono('SF Mono', macTerminalFontFamily, macTerminalFontFallback),
menlo('Menlo', 'Menlo', ['Monaco', 'Courier New', 'monospace']),
@@ -58,7 +66,16 @@ enum TerminalFontChoice {
'DejaVu Sans Mono',
'Liberation Mono',
'monospace',
- ]);
+ ]),
+
+ droidSansMono(
+ 'Droid Sans Mono',
+ androidTerminalFontFamily,
+ androidTerminalFontFallback,
+ ),
+ // A typewriter face with a smaller repertoire than Droid Sans Mono, which
+ // covers what it lacks before the system's own fallback has to.
+ cutiveMono('Cutive Mono', 'serif-monospace', [androidTerminalFontFamily]);
const TerminalFontChoice(
this.label,
@@ -78,19 +95,52 @@ enum TerminalFontChoice {
liberationMono,
notoSansMono,
];
+ static const _androidChoices = [droidSansMono, cutiveMono];
- /// The faces worth offering on the host this build is running on.
+ /// The faces worth offering on [host].
///
/// Windows falls in with Linux deliberately rather than with macOS: its
/// runner is unexercised (see CLAUDE.md), and of the two lists the Linux one
/// at least ends every fallback at the generic `monospace`, which Windows
/// does resolve.
+ static List<TerminalFontChoice> availableOn(TerminalFontHost host) =>
+ switch (host) {
+ TerminalFontHost.apple => _macChoices,
+ TerminalFontHost.android => _androidChoices,
+ TerminalFontHost.other => _linuxChoices,
+ };
+
+ /// What a fresh install on [host] opens with, and what `reset()` returns to.
+ static TerminalFontChoice defaultOn(TerminalFontHost host) => switch (host) {
+ TerminalFontHost.apple => sfMono,
+ TerminalFontHost.android => droidSansMono,
+ TerminalFontHost.other => dejaVuSansMono,
+ };
+
+ /// The faces worth offering on the host this build is running on.
static List<TerminalFontChoice> get available =>
- hasAppleFonts ? _macChoices : _linuxChoices;
+ availableOn(TerminalFontHost.current);
+}
- /// What a fresh install opens with, and what `reset()` returns to.
- static TerminalFontChoice get defaultForPlatform =>
- hasAppleFonts ? sfMono : dejaVuSansMono;
+/// Which set of fonts the OS under the app ships — what decides the terminal's
+/// [TerminalFontChoice.availableOn] list and its default.
+///
+/// Read from `dart:io` rather than `defaultTargetPlatform`, as [hasAppleFonts]
+/// is: the question is which fonts are installed, not which platform the
+/// widgets imitate, and a test overriding the latter runs on the same fonts.
+enum TerminalFontHost {
+ /// macOS and iOS — see [hasAppleFonts].
+ apple,
+ android,
+
+ /// Linux, and Windows with it — see [TerminalFontChoice.availableOn].
+ other;
+
+ static TerminalFontHost get current => hasAppleFonts
+ ? apple
+ : Platform.isAndroid
+ ? android
+ : other;
}
/// The user's chosen terminal typography (family + size), remembered across
@@ -110,9 +160,17 @@ enum TerminalFontChoice {
/// guard and [ValueNotifier]'s own "don't notify on a no-op set" work for
/// free.
class TerminalFontStore extends ValueNotifier<TerminalStyle> {
- TerminalFontStore({LocalKeyValueStore? storage})
+ /// [host] is the OS whose fonts this store picks among — the running one
+ /// unless a test names another.
+ TerminalFontStore({LocalKeyValueStore? storage, TerminalFontHost? host})
: _storage = storage ?? HarnessFileStore.shared,
- super(_styleFor(TerminalFontChoice.defaultForPlatform, terminalFontSize));
+ _host = host ?? TerminalFontHost.current,
+ super(
+ _styleFor(
+ TerminalFontChoice.defaultOn(host ?? TerminalFontHost.current),
+ terminalFontSize,
+ ),
+ );
static const _familyKey = 'terminal_font_family';
static const _sizeKey = 'terminal_font_size';
@@ -125,6 +183,11 @@ class TerminalFontStore extends ValueNotifier<TerminalStyle> {
static const _step = 1.0;
final LocalKeyValueStore _storage;
+ final TerminalFontHost _host;
+
+ /// What a fresh install opens with on this store's host, and what [reset]
+ /// returns to.
+ TerminalFontChoice get defaultChoice => TerminalFontChoice.defaultOn(_host);
static final _cache = <(TerminalFontChoice, double), TerminalStyle>{};
static TerminalStyle _styleFor(TerminalFontChoice choice, double size) =>
@@ -139,7 +202,7 @@ class TerminalFontStore extends ValueNotifier<TerminalStyle> {
TerminalFontChoice get family => TerminalFontChoice.values.firstWhere(
(choice) => choice.fontFamily == value.fontFamily,
- orElse: () => TerminalFontChoice.defaultForPlatform,
+ orElse: () => defaultChoice,
);
double get size => value.fontSize;
@@ -147,6 +210,12 @@ class TerminalFontStore extends ValueNotifier<TerminalStyle> {
/// Read the saved choice, if there is one. Failure (or a stale/unknown
/// family name from an older build) is silent and lands on the default —
/// an unreadable state file is not a reason to refuse to start.
+ ///
+ /// ⚠️ **On Android a face Android does not ship lands on the default too.**
+ /// Before it had a list of its own the phone offered Android the Linux one,
+ /// so a pick saved then names a face no Android phone has — drawn as Droid
+ /// Sans Mono while Settings named DejaVu or Ubuntu. Elsewhere every value
+ /// still loads, for the reason given on [TerminalFontChoice].
Future<void> load() async {
try {
final saved = await _storage.readMany([_familyKey, _sizeKey]);
@@ -154,34 +223,34 @@ class TerminalFontStore extends ValueNotifier<TerminalStyle> {
final savedSize = saved[_sizeKey];
final choice = TerminalFontChoice.values
.where((c) => c.name == savedFamily)
+ .where(_loads)
.firstOrNull;
final size = savedSize == null ? null : double.tryParse(savedSize);
value = _styleFor(
- choice ?? TerminalFontChoice.defaultForPlatform,
+ choice ?? defaultChoice,
_clamp(size ?? terminalFontSize),
);
} catch (_) {
- value = _styleFor(
- TerminalFontChoice.defaultForPlatform,
- terminalFontSize,
- );
+ value = _styleFor(defaultChoice, terminalFontSize);
}
}
+ /// Whether a saved [choice] is taken as it is — see [load].
+ bool _loads(TerminalFontChoice choice) =>
+ _host != TerminalFontHost.android ||
+ TerminalFontChoice.availableOn(_host).contains(choice);
+
Future<void> setFamily(TerminalFontChoice choice) => _set(choice, size);
Future<void> increaseSize() => _set(family, size + _step);
Future<void> decreaseSize() => _set(family, size - _step);
Future<void> setSize(double size) => _set(family, size);
- Future<void> reset() =>
- _set(TerminalFontChoice.defaultForPlatform, terminalFontSize);
+ Future<void> reset() => _set(defaultChoice, terminalFontSize);
/// Whether the current pick *is* the default — what [reset] would leave the
/// store at, so a Reset control can say it has nothing to do.
- bool get isDefault =>
- family == TerminalFontChoice.defaultForPlatform &&
- size == terminalFontSize;
+ bool get isDefault => family == defaultChoice && size == terminalFontSize;
double _clamp(double size) => size.clamp(minSize, maxSize);
diff --git a/mobile/lib/terminal/terminal_input.dart b/mobile/lib/terminal/terminal_input.dart
index a192ab08d..711e52ccf 100644
--- a/mobile/lib/terminal/terminal_input.dart
+++ b/mobile/lib/terminal/terminal_input.dart
@@ -35,7 +35,37 @@ class MetaEnterInputHandler implements TerminalInputHandler {
}
}
-/// The handler every pane's [Terminal] is built with — xterm's default behaviour, plus ⌥⏎.
+/// Keeps ⇧⏎ as CSI-u (`CSI 13;2u`) instead of losing Shift in the default keytab — the desktop's
+/// `ShiftEnterInputHandler`, so a hardware keyboard on a phone sends what it sends on the laptop.
+///
+/// The keytab answers ⇧⏎ with `\EOM`, the keypad's Enter, which no engine's prompt reads as a
+/// newline. As CSI-u a prompt can tell the newline it binds to ⇧⏎ from the plain Return that
+/// submits. One that does not read CSI-u is no worse off than with `\EOM`, and ⌥⏎
+/// ([MetaEnterInputHandler]) is the newline every Ink/readline prompt reads — which is why the key
+/// bar's own newline sends that one.
+///
+/// Fixed bytes rather than asked of [_inner], as on the desktop: CSI-u has one spelling, LNM
+/// (`lineFeedMode`) included.
+class ShiftEnterInputHandler implements TerminalInputHandler {
+ const ShiftEnterInputHandler(this._inner);
+
+ final TerminalInputHandler _inner;
+
+ @override
+ String? call(TerminalKeyboardEvent event) {
+ final isEnter =
+ event.key == TerminalKey.enter || event.key == TerminalKey.numpadEnter;
+ // ⌥⇧⏎ is [MetaEnterInputHandler]'s, ⌃⇧⏎ the keytab's: only Shift alone is this.
+ if (isEnter && event.shift && !event.alt && !event.ctrl) {
+ return '\x1b[13;2u';
+ }
+ return _inner(event);
+ }
+}
+
+/// The handler every pane's [Terminal] is built with — xterm's default behaviour, plus ⌥⏎ and ⇧⏎,
+/// in the desktop's order: ⌥ is translated first, so ⌥⇧⏎ asks the keytab for a plain Return and
+/// stays a Meta-prefixed Return rather than a prefixed CSI-u.
const TerminalInputHandler harnessInputHandler = MetaEnterInputHandler(
- defaultInputHandler,
+ ShiftEnterInputHandler(defaultInputHandler),
);
diff --git a/mobile/lib/terminal/terminal_typography.dart b/mobile/lib/terminal/terminal_typography.dart
index 96c30c9b7..e905b6fd5 100644
--- a/mobile/lib/terminal/terminal_typography.dart
+++ b/mobile/lib/terminal/terminal_typography.dart
@@ -28,7 +28,8 @@ import 'package:flutter/foundation.dart';
/// so it measures exactly like a family that does not exist. It stays in the
/// lists as a last resort for other engines, but it is not a safety net — every
/// chain has to name a real face it can reach. On Linux that anchor is DejaVu
-/// Sans Mono, the only monospace `ubuntu-desktop-minimal` depends on.
+/// Sans Mono, the only monospace `ubuntu-desktop-minimal` depends on. On
+/// Android it is `monospace` itself — see [androidTerminalFontFamily].
///
/// The live, user-chosen typography lives in `terminalFontStore`, not here;
/// these are what a fresh install opens with and what `reset()` returns to.
@@ -63,6 +64,24 @@ const linuxTerminalFontFallback = <String>[
'monospace',
];
+/// Droid Sans Mono, by the only name Android gives it.
+///
+/// Android ships two monospace faces and no others: Droid Sans Mono, which its
+/// `fonts.xml` declares as the family `monospace`, and Cutive Mono, declared as
+/// `serif-monospace`. Skia's Android font manager looks families up by the
+/// names `fonts.xml` declares, so those generic names are the real families
+/// here — the opposite of Linux, where Skia ignores fontconfig's generic
+/// aliases and `monospace` is inert (above). Every Linux and Apple face names
+/// nothing on a phone, so before Android had a list of its own each of them
+/// fell through to this same face: the Font sheet offered five names for one
+/// font.
+///
+/// No fallback of its own: Cutive Mono covers less than this does, and a glyph
+/// missing here goes to the system's own fallback chain.
+const androidTerminalFontFamily = 'monospace';
+
+const androidTerminalFontFallback = <String>[];
+
/// The default terminal font size: 13 on a desktop, 14 on a phone.
///
/// Tried on an iPhone: 13 read as small print, 16 as far too big. Monospace is wider than the
diff --git a/mobile/lib/usage/models_menu_controller.dart b/mobile/lib/usage/models_menu_controller.dart
index 42fcf1d6f..aa9055ae2 100644
--- a/mobile/lib/usage/models_menu_controller.dart
+++ b/mobile/lib/usage/models_menu_controller.dart
@@ -6,6 +6,7 @@ import 'package:harness_mobile/widgets/engine_identity.dart';
import 'usage_accounts.dart';
import 'usage_controller.dart';
+import 'usage_pressure.dart';
import 'usage_window.dart';
/// Subscription readings for the model sheet's own first row. Opening the
@@ -149,10 +150,7 @@ class ModelsMenuController extends ChangeNotifier {
return '';
}
- static String _remaining(UsageWindow window) {
- final left = (100 - window.usedPercent).clamp(0, 100);
- // Never round a positive remainder to zero (or a partial balance to 100).
- if (left > 0 && left < 1) return '<1%';
- return '${left.floor()}%';
- }
+ // The Usage page's figure too, so the sheet and the page cannot disagree.
+ static String _remaining(UsageWindow window) =>
+ usageRemainingLabel(window.usedPercent);
}
diff --git a/mobile/lib/usage/usage_pressure.dart b/mobile/lib/usage/usage_pressure.dart
index 7002cd48b..3534b00e4 100644
--- a/mobile/lib/usage/usage_pressure.dart
+++ b/mobile/lib/usage/usage_pressure.dart
@@ -7,28 +7,54 @@ import 'usage_window.dart';
enum UsagePressure {
calm,
- /// Amber. The window is worth noticing on the way past.
+ /// Muted amber. The window is worth noticing on the way past.
warn,
/// Red. The window is nearly spent.
critical,
}
-/// Where a window starts reading amber.
+/// Where a window starts reading amber: this much left, or less.
///
-/// 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;
+/// The desktop's own numbers (`workspace_subscription_usage.dart`), on what is
+/// LEFT rather than what is spent, so one subscription is the same colour on
+/// the laptop and the phone. 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 int kUsageLowRemaining = 20;
-/// Where a window starts reading red.
-const double kUsageCriticalPercent = 90;
+/// Where a window starts reading red: this much left, or less.
+const int kUsageCriticalRemaining = 5;
+/// What is left of a window that is [usedPercent] spent, 0–100.
+double usageRemainingOf(double usedPercent) =>
+ (100 - usedPercent).clamp(0, 100).toDouble();
+
+/// What is left, as printed: `80%`. Floored, so a partly spent window never
+/// reads `100%`; and a remainder under one percent reads `<1%`, never `0%`.
+/// The same figure the model sheet prints (`ModelsMenuController`), so the two
+/// cannot disagree.
+String usageRemainingLabel(double usedPercent) {
+ final left = usageRemainingOf(usedPercent);
+ if (!left.isFinite) return '—';
+ if (left > 0 && left < 1) return '<1%';
+ return '${left.floor()}%';
+}
+
+/// Judged on the whole percent [usageRemainingLabel] prints, as the desktop
+/// judges it: a window printed as `20%` is amber whatever its fraction was.
UsagePressure usagePressureOf(double usedPercent) {
- if (usedPercent >= kUsageCriticalPercent) return UsagePressure.critical;
- if (usedPercent >= kUsageWarnPercent) return UsagePressure.warn;
+ final left = usageRemainingOf(usedPercent);
+ if (!left.isFinite) return UsagePressure.calm;
+ final whole = left.floor();
+ if (whole <= kUsageCriticalRemaining) return UsagePressure.critical;
+ if (whole <= kUsageLowRemaining) return UsagePressure.warn;
return UsagePressure.calm;
}
extension UsageWindowPressure on UsageWindow {
UsagePressure get pressure => usagePressureOf(usedPercent);
+
+ /// `80% remaining`, as the desktop words it.
+ String get remainingLabel => '${usageRemainingLabel(usedPercent)} remaining';
}
diff --git a/mobile/lib/usage/usage_summary.dart b/mobile/lib/usage/usage_summary.dart
new file mode 100644
index 000000000..d749ba4bb
--- /dev/null
+++ b/mobile/lib/usage/usage_summary.dart
@@ -0,0 +1,23 @@
+import 'package:flutter/foundation.dart';
+
+/// The last figure the Usage 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 the page last measured, and the 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.
+///
+/// ⚠️ **It belongs to the account that read it.** `AppNotifier` clears it when
+/// that account leaves — a sign-out by hand or one from elsewhere — because
+/// the next sign-in may be another account's, and its Settings row printed the
+/// last one's figure until Usage was opened again. Here rather than beside the
+/// page so the state can reach it without importing a screen.
+final ValueNotifier<String?> lastUsageSummary = ValueNotifier<String?>(null);
diff --git a/mobile/lib/usage/usage_window.dart b/mobile/lib/usage/usage_window.dart
index 18513b9f1..d7ac89e98 100644
--- a/mobile/lib/usage/usage_window.dart
+++ b/mobile/lib/usage/usage_window.dart
@@ -10,9 +10,7 @@ library;
///
/// Claude names it outright; Codex's label is derived from
/// `limit_window_seconds` and lands on the same word at seven days. Written
-/// down once because the rail MATCHES on it — see [ProviderUsage.railWindow] —
-/// and a match against a string spelled in two files is a match that breaks
-/// silently the day one of them is reworded.
+/// down once so the two sources cannot spell it differently.
const String kWeeklyWindowLabel = 'Weekly';
/// Which account a reading belongs to.
@@ -132,31 +130,16 @@ class ProviderUsage {
/// The window closest to being spent — the limit that will actually stop the
/// work first.
+ ///
+ /// The ONE window an account's figure is read off, on the Usage page and on
+ /// the model sheet alike, as on the desktop. It used to be the weekly one on
+ /// the page, which made the app contradict itself — and a weekly figure can
+ /// look healthy while a shorter window is already exhausted. The detail
+ /// behind the figure still shows every window.
UsageWindow? get tightest {
if (windows.isEmpty) return null;
return windows.reduce((a, b) => b.usedPercent > a.usedPercent ? b : a);
}
-
- /// The ONE window the status rail prints.
- ///
- /// The weekly one. Claude reports three windows and Codex usually one, so
- /// printing them all made one account three figures wide and the other one —
- /// two readouts that looked like different KINDS of thing rather than the
- /// same thing about two accounts. Weekly is also the figure worth a glance:
- /// the five-hour window refills all day and is back to nothing by the time
- /// anyone reads it, while the week is the budget somebody actually plans
- /// against.
- ///
- /// Falls back to [tightest] for a provider that reports no weekly window at
- /// all — one figure is the rule, and an empty strip would be a worse answer
- /// than the wrong window. The panel behind the figure still shows every
- /// window, which is where the detail belongs.
- UsageWindow? get railWindow {
- for (final window in windows) {
- if (window.label == kWeeklyWindowLabel) return window;
- }
- return tightest;
- }
}
/// Reads a vendor's reset timestamp, which arrives as an ISO string, epoch
diff --git a/mobile/test/app_state_sign_in_test.dart b/mobile/test/app_state_sign_in_test.dart
index 80251d5ba..00f25d773 100644
--- a/mobile/test/app_state_sign_in_test.dart
+++ b/mobile/test/app_state_sign_in_test.dart
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/usage/usage_summary.dart';
import 'package:harness_mobile/ws/ws_conn.dart';
import 'viewer_app_fixture.dart';
@@ -231,6 +232,21 @@ void main() {
expect(rig.signIn.logouts, 1);
});
+ test('the Settings row\'s usage figure goes with the account', () async {
+ // Kept, the next account to sign in read this one's figure on its row.
+ addTearDown(() => lastUsageSummary.value = null);
+ final rig = viewerApp();
+ addTearDown(rig.app.dispose);
+ rig.api.onMachines = () async => [remoteMachine('m')];
+ await rig.app.bootstrap();
+ await settle();
+ lastUsageSummary.value = '15% remaining';
+
+ await rig.app.logout();
+
+ expect(lastUsageSummary.value, isNull);
+ });
+
test('a machine list that lands after sign-out is thrown away', () async {
final rig = viewerApp();
addTearDown(rig.app.dispose);
@@ -304,6 +320,23 @@ void main() {
expect(redraws, 1, reason: 'several sockets can race to say so');
},
);
+
+ test(
+ 'a session revoked under a running app takes its usage figure',
+ () async {
+ addTearDown(() => lastUsageSummary.value = null);
+ final rig = viewerApp();
+ addTearDown(rig.app.dispose);
+ rig.api.onMachines = () async => [remoteMachine('m')];
+ await rig.app.bootstrap();
+ await settle();
+ lastUsageSummary.value = '15% remaining';
+
+ rig.app.authFailureForTest('Your sign-in expired. Sign in again.');
+
+ expect(lastUsageSummary.value, isNull);
+ },
+ );
});
group('the token a relay socket dials with', () {
diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dart
index d9bb2bb05..258de66c9 100644
--- a/mobile/test/phone_edge/focus_behavior_test.dart
+++ b/mobile/test/phone_edge/focus_behavior_test.dart
@@ -500,6 +500,24 @@ void main() {
});
});
+ testWidgets('↵ breaks the prompt\'s line without sending the turn', (
+ tester,
+ ) async {
+ final focus = await _Focus.open(tester);
+ focus.fill();
+ await frames(tester);
+ await focus.tapPrompt();
+ await tester.pump();
+ raiseKeyboard(tester);
+ await frames(tester);
+ focus.typed.clear();
+ await tester.tap(find.byKey(const ValueKey('terminal-key-Newline')));
+ await frames(tester);
+ // What a hardware ⌥⏎ sends — never the bare Return that submits.
+ expect(focus.typed, ['\x1b\r']);
+ await focus.close();
+ });
+
group('the app going away and coming back', () {
testWidgets('the keyboard it left with is the keyboard it comes back to', (
tester,
diff --git a/mobile/test/terminal_input_test.dart b/mobile/test/terminal_input_test.dart
new file mode 100644
index 000000000..f59718ad8
--- /dev/null
+++ b/mobile/test/terminal_input_test.dart
@@ -0,0 +1,113 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/terminal/terminal_input.dart';
+import 'package:xterm/xterm.dart';
+
+/// A hardware keyboard on a phone breaks a line in an engine's prompt exactly
+/// as the desktop does: ⇧⏎ as CSI-u, ⌥⏎ as ESC + Return — never the keytab's
+/// `\EOM` for ⇧⏎, and never a bare Return, which is the submit.
+void main() {
+ /// A pane's terminal, as `TerminalSession` builds it.
+ Terminal pane(List<String> out) => Terminal(
+ maxLines: 200,
+ platform: TerminalTargetPlatform.macos,
+ inputHandler: harnessInputHandler,
+ reflowEnabled: false,
+ )..onOutput = out.add;
+
+ for (final key in [TerminalKey.enter, TerminalKey.numpadEnter]) {
+ test('⇧$key leaves as CSI-u, LNM or not', () {
+ final out = <String>[];
+ final terminal = pane(out);
+
+ terminal.keyInput(key, shift: true);
+ terminal.write('\x1b[20h'); // LNM must not turn this into a submit.
+ terminal.keyInput(key, shift: true);
+
+ expect(out, ['\x1b[13;2u', '\x1b[13;2u']);
+ });
+
+ test('⌥$key leaves as ESC + Return, LNM\'s Return included', () {
+ final out = <String>[];
+ final terminal = pane(out);
+
+ terminal.keyInput(key, alt: true);
+ terminal.write('\x1b[20h');
+ terminal.keyInput(key, alt: true);
+
+ expect(out, ['\x1b\r', '\x1b\r\n']);
+ });
+ }
+
+ test('⌥⇧⏎ is a Meta-prefixed Return, not a prefixed CSI-u', () {
+ final out = <String>[];
+ pane(out).keyInput(TerminalKey.enter, alt: true, shift: true);
+ expect(out, ['\x1b\r']);
+ });
+
+ test('plain Return still submits, and ⌃⇧⏎ keeps the keytab\'s answer', () {
+ final out = <String>[];
+ final baseline = <String>[];
+ final unmodified = Terminal(platform: TerminalTargetPlatform.macos)
+ ..onOutput = baseline.add;
+ final terminal = pane(out);
+
+ terminal.keyInput(TerminalKey.enter);
+ terminal.keyInput(TerminalKey.enter, ctrl: true, shift: true);
+ unmodified.keyInput(TerminalKey.enter);
+ unmodified.keyInput(TerminalKey.enter, ctrl: true, shift: true);
+
+ expect(out, baseline);
+ expect(out.first, '\r');
+ });
+
+ group('from a hardware keyboard on the phone', () {
+ Future<List<String>> press(
+ WidgetTester tester,
+ LogicalKeyboardKey modifier,
+ ) async {
+ final out = <String>[];
+ final terminal = pane(out)..resize(80, 12);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SizedBox(
+ width: 400,
+ height: 320,
+ child: TerminalView(terminal, autofocus: true),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ final platform = switch (defaultTargetPlatform) {
+ TargetPlatform.iOS => 'ios',
+ _ => 'android',
+ };
+ await tester.sendKeyDownEvent(modifier, platform: platform);
+ await tester.sendKeyDownEvent(
+ LogicalKeyboardKey.enter,
+ platform: platform,
+ );
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.enter, platform: platform);
+ await tester.sendKeyUpEvent(modifier, platform: platform);
+ await tester.pump();
+ return out;
+ }
+
+ final phones = TargetPlatformVariant({
+ TargetPlatform.iOS,
+ TargetPlatform.android,
+ });
+
+ testWidgets('⇧⏎ reaches the pty as CSI-u', (tester) async {
+ expect(await press(tester, LogicalKeyboardKey.shiftLeft), ['\x1b[13;2u']);
+ }, variant: phones);
+
+ testWidgets('⌥⏎ reaches the pty as ESC + Return', (tester) async {
+ expect(await press(tester, LogicalKeyboardKey.altLeft), ['\x1b\r']);
+ }, variant: phones);
+ });
+}
diff --git a/mobile/test/terminal_key_bar_test.dart b/mobile/test/terminal_key_bar_test.dart
index c0f2a97e3..ceb7261da 100644
--- a/mobile/test/terminal_key_bar_test.dart
+++ b/mobile/test/terminal_key_bar_test.dart
@@ -1,7 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/terminal_input_dock.dart';
import 'package:harness_mobile/phone/terminal_key_bar.dart';
import 'package:harness_mobile/terminal/key_hints.dart';
+import 'package:harness_mobile/terminal/terminal_input.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
import 'package:xterm/xterm.dart';
void main() {
@@ -162,6 +165,177 @@ void main() {
expect(dismissals, 1);
});
+ group('↵ at an engine\'s prompt', () {
+ late Terminal pane;
+
+ setUp(() {
+ // As `TerminalSession` builds a pane's terminal: the bytes ↵ sends are
+ // the ones its input handler gives a hardware ⌥⏎.
+ pane = Terminal(
+ maxLines: 200,
+ platform: TerminalTargetPlatform.macos,
+ inputHandler: harnessInputHandler,
+ reflowEnabled: false,
+ )..resize(80, 12);
+ pane.onOutput = outbound.add;
+ });
+
+ Future<void> pumpPrompt(
+ WidgetTester tester, {
+ double width = 375,
+ bool enabled = true,
+ bool enginePrompt = true,
+ bool questionOpen = false,
+ bool? ctrl,
+ ValueChanged<bool>? armCtrl,
+ }) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.bottomCenter,
+ child: SizedBox(
+ width: width,
+ child: TerminalKeyBar(
+ terminal: pane,
+ enabled: enabled,
+ enginePrompt: enginePrompt,
+ questionOpen: questionOpen,
+ onDismissKeyboard: () => dismissals++,
+ onPromptEdited: () => edits++,
+ // Every optional key the row can hold but `paste`, whose
+ // clipboard poll would outlive the test.
+ onClearPrompt: () {},
+ onPickImage: () {},
+ ctrlArmed: ctrl,
+ onArmCtrl: armCtrl,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ final newline = find.byKey(const ValueKey('terminal-key-Newline'));
+ final enter = find.byKey(const ValueKey('terminal-key-Enter'));
+
+ testWidgets('breaks the line as ⌥⏎ does, and does not submit', (
+ tester,
+ ) async {
+ await pumpPrompt(tester);
+
+ await tester.tap(newline);
+ await tester.pump();
+
+ expect(outbound, ['\x1b\r'], reason: 'ESC + Return, never a bare \\r');
+ expect(edits, 1, reason: 'the keyboard lets go of the line just broken');
+ });
+
+ testWidgets('puts armed modifiers down rather than adding them', (
+ tester,
+ ) async {
+ // The row's own: armed, spent by ↵ unchanged, and gone after it.
+ await pumpPrompt(tester);
+ await tester.tap(find.byKey(const ValueKey('terminal-key-ctrl')));
+ await tester.tap(find.byKey(const ValueKey('terminal-key-shift')));
+ await tester.pump();
+ await tester.tap(newline);
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('terminal-key-Up')));
+ await tester.pump();
+ expect(outbound, ['\x1b\r', '\x1b[A']);
+
+ // The session's ctrl is put down too.
+ final armed = <bool>[];
+ outbound.clear();
+ await pumpPrompt(tester, ctrl: true, armCtrl: armed.add);
+ await tester.tap(newline);
+ await tester.pump();
+ expect(outbound, ['\x1b\r']);
+ expect(armed, [false]);
+ });
+
+ testWidgets(
+ 'gives its slot to ⏎ during a question; no ↵ on a plain shell',
+ (tester) async {
+ await pumpPrompt(tester, questionOpen: true);
+ expect(newline, findsNothing);
+ expect(enter, findsOneWidget);
+
+ await pumpPrompt(tester, enginePrompt: false);
+ expect(newline, findsNothing);
+ expect(enter, findsNothing);
+ },
+ );
+
+ testWidgets('dims with the rest of the row while input is not taken', (
+ tester,
+ ) async {
+ await pumpPrompt(tester, enabled: false);
+ await tester.tap(newline);
+ await tester.pump();
+ expect(outbound, isEmpty);
+ });
+
+ testWidgets('the dock offers it to an agent and not to a plain shell', (
+ tester,
+ ) async {
+ for (final (engine, offered) in [('claude', true), ('terminal', false)]) {
+ final session = TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'a',
+ engineId: engine,
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ );
+ addTearDown(session.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: TerminalInputDock(
+ session: session,
+ keyboardUp: true,
+ onDismiss: () {},
+ ),
+ ),
+ ),
+ );
+ expect(
+ newline,
+ offered ? findsOneWidget : findsNothing,
+ reason: engine,
+ );
+ }
+ });
+
+ for (final width in [320.0, 375.0]) {
+ testWidgets('fits a ${width.round()}pt phone at the width a question '
+ 'already gives every key', (tester) async {
+ final esc = find.byKey(const ValueKey('terminal-key-esc'));
+ await pumpPrompt(tester, width: width, questionOpen: true);
+ final asked = tester.getSize(esc);
+ await pumpPrompt(tester, width: width);
+ expect(tester.takeException(), isNull);
+ expect(tester.getSize(esc), asked);
+ // Inside the row, before the rule and the two keys past it.
+ final image = find.byKey(const ValueKey('terminal-key-Send image'));
+ expect(
+ tester.getTopRight(newline).dx,
+ lessThan(tester.getTopLeft(image).dx),
+ );
+ expect(newline.hitTestable(), findsOneWidget);
+ expect(
+ find
+ .byKey(const ValueKey('terminal-key-Hide keyboard'))
+ .hitTestable(),
+ findsOneWidget,
+ );
+ });
+ }
+ });
+
// Claude Code's footer offers it on every prompt.
final cycle = parseKeyHints([' ⏵⏵ auto mode on (shift+tab to cycle)']);
// Codex's queue of async questions, over the composer.
diff --git a/mobile/test/terminal_preferences_test.dart b/mobile/test/terminal_preferences_test.dart
index 669d7e6af..e124fe3bf 100644
--- a/mobile/test/terminal_preferences_test.dart
+++ b/mobile/test/terminal_preferences_test.dart
@@ -102,6 +102,103 @@ void main() {
);
});
+ group('the faces each OS ships', () {
+ test('Android offers its own two, and opens on Droid Sans Mono', () async {
+ // Offered the Linux list, every pick drew the same face on Android.
+ expect(TerminalFontChoice.availableOn(TerminalFontHost.android), [
+ TerminalFontChoice.droidSansMono,
+ TerminalFontChoice.cutiveMono,
+ ]);
+ // The names Android's `fonts.xml` declares — its faces' own names
+ // resolve to nothing there.
+ expect(TerminalFontChoice.droidSansMono.fontFamily, 'monospace');
+ expect(TerminalFontChoice.cutiveMono.fontFamily, 'serif-monospace');
+
+ final font = TerminalFontStore(
+ storage: _Store(),
+ host: TerminalFontHost.android,
+ );
+ addTearDown(font.dispose);
+ expect(font.family, TerminalFontChoice.droidSansMono);
+ expect(font.value.fontFamily, 'monospace');
+ expect(font.isDefault, isTrue);
+ await font.load();
+ expect(font.family, TerminalFontChoice.droidSansMono);
+ });
+
+ test(
+ 'a Linux face saved on Android comes back as Android\'s default',
+ () async {
+ final storage = _Store()
+ ..values.addAll({
+ 'terminal_font_family': TerminalFontChoice.dejaVuSansMono.name,
+ 'terminal_font_size': '16',
+ });
+ final font = TerminalFontStore(
+ storage: storage,
+ host: TerminalFontHost.android,
+ );
+ addTearDown(font.dispose);
+ await font.load();
+ expect(font.family, TerminalFontChoice.droidSansMono);
+ expect(font.value.fontFamily, 'monospace');
+ expect(font.size, 16, reason: 'the size was never the problem');
+
+ // An Apple face is no better on Android.
+ storage.values['terminal_font_family'] = TerminalFontChoice.sfMono.name;
+ await font.load();
+ expect(font.family, TerminalFontChoice.droidSansMono);
+
+ // Android's own second face loads as it was saved.
+ await font.setFamily(TerminalFontChoice.cutiveMono);
+ final restored = TerminalFontStore(
+ storage: storage,
+ host: TerminalFontHost.android,
+ );
+ addTearDown(restored.dispose);
+ await restored.load();
+ expect(restored.family, TerminalFontChoice.cutiveMono);
+ expect(restored.isDefault, isFalse);
+ await restored.reset();
+ expect(restored.family, TerminalFontChoice.droidSansMono);
+ },
+ );
+
+ test('Apple and Linux keep their lists, and load any saved face', () async {
+ expect(TerminalFontChoice.availableOn(TerminalFontHost.apple), [
+ TerminalFontChoice.sfMono,
+ TerminalFontChoice.menlo,
+ TerminalFontChoice.monaco,
+ TerminalFontChoice.courierNew,
+ ]);
+ expect(
+ TerminalFontChoice.defaultOn(TerminalFontHost.apple),
+ TerminalFontChoice.sfMono,
+ );
+ expect(
+ TerminalFontChoice.availableOn(TerminalFontHost.other),
+ isNot(contains(TerminalFontChoice.droidSansMono)),
+ );
+ expect(
+ TerminalFontChoice.defaultOn(TerminalFontHost.other),
+ TerminalFontChoice.dejaVuSansMono,
+ );
+
+ // Unchanged on iOS: a face saved from another list still loads.
+ final storage = _Store()
+ ..values['terminal_font_family'] =
+ TerminalFontChoice.dejaVuSansMono.name;
+ final font = TerminalFontStore(
+ storage: storage,
+ host: TerminalFontHost.apple,
+ );
+ addTearDown(font.dispose);
+ expect(font.family, TerminalFontChoice.sfMono);
+ await font.load();
+ expect(font.family, TerminalFontChoice.dejaVuSansMono);
+ });
+ });
+
test(
'terminal colors persist and reset without notifying on a no-op',
() async {
diff --git a/mobile/test/usage/usage_answers_test.dart b/mobile/test/usage/usage_answers_test.dart
index 363a1fd12..6ce819d69 100644
--- a/mobile/test/usage/usage_answers_test.dart
+++ b/mobile/test/usage/usage_answers_test.dart
@@ -160,7 +160,7 @@ void main() {
expect(reading.status, UsageStatus.ok);
expect(reading.account, 'acct');
expect(reading.windows, hasLength(2));
- expect(reading.railWindow!.usedPercent, 64);
+ expect(reading.tightest!.usedPercent, 64);
expect(reading.windows.first.resetsAt, isNotNull);
});
diff --git a/mobile/test/usage/usage_controller_test.dart b/mobile/test/usage/usage_controller_test.dart
index bd382d4b7..a05752c5d 100644
--- a/mobile/test/usage/usage_controller_test.dart
+++ b/mobile/test/usage/usage_controller_test.dart
@@ -53,7 +53,7 @@ void main() {
.where((a) => a.provider == provider)
.firstOrNull
?.reading
- .railWindow
+ .tightest
?.usedPercent;
test('nobody asked yet: not loading, and no answer', () {
diff --git a/mobile/test/usage/usage_page_test.dart b/mobile/test/usage/usage_page_test.dart
new file mode 100644
index 000000000..8550186ee
--- /dev/null
+++ b/mobile/test/usage/usage_page_test.dart
@@ -0,0 +1,155 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/phone/usage_entry.dart';
+import 'package:harness_mobile/phone/usage_page.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/usage/usage_accounts.dart';
+import 'package:harness_mobile/usage/usage_summary.dart';
+import 'package:harness_mobile/usage/usage_window.dart';
+
+/// A phone whose linked machines answer `usage_read` with [answer].
+class _Usage extends AppNotifier {
+ _Usage(this.answer)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+
+ final List<MachineUsage> answer;
+
+ @override
+ Future<List<MachineUsage>> readRemoteUsage({String? machineId}) async =>
+ answer;
+}
+
+/// The Usage page's headline and the Settings row it feeds: the tightest
+/// window, as what is LEFT of it — the figure the model sheet and the desktop
+/// print — never the weekly one as what is spent.
+void main() {
+ setUp(() => lastUsageSummary.value = null);
+ tearDown(() => lastUsageSummary.value = null);
+
+ ProviderUsage reading(UsageProvider provider, List<UsageWindow> windows) =>
+ ProviderUsage(
+ provider: provider,
+ status: UsageStatus.ok,
+ windows: windows,
+ account: provider.name,
+ );
+
+ /// Opens the page on [answer] and pulls it down once: under test the page's
+ /// controller never polls on its own, so the pull is its first cycle.
+ Future<_Usage> openPage(
+ WidgetTester tester,
+ List<MachineUsage> answer,
+ ) async {
+ final app = _Usage(answer);
+ addTearDown(app.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: buildAppTheme(brightness: Brightness.dark),
+ home: UsagePage(notifier: app),
+ ),
+ );
+ await tester.fling(
+ find.byType(Scrollable).first,
+ const Offset(0, 400),
+ 1000,
+ );
+ await tester.pumpAndSettle();
+ return app;
+ }
+
+ Color? inkOf(WidgetTester tester, String text) =>
+ tester.widget<Text>(find.text(text)).style?.color;
+
+ testWidgets('each card heads with its tightest window, as what is left', (
+ tester,
+ ) async {
+ await openPage(tester, [
+ MachineUsage(
+ machineName: 'Studio',
+ readings: [
+ reading(UsageProvider.claude, const [
+ UsageWindow(label: 'Session', usedPercent: 85),
+ UsageWindow(label: kWeeklyWindowLabel, usedPercent: 40),
+ ]),
+ ],
+ ),
+ MachineUsage(
+ machineName: 'Laptop',
+ readings: [
+ reading(UsageProvider.codex, const [
+ UsageWindow(label: kWeeklyWindowLabel, usedPercent: 10),
+ ]),
+ ],
+ ),
+ ]);
+
+ // Claude's session window is the one about to stop the work, though its
+ // week looks healthy.
+ expect(find.text('Session'), findsOneWidget);
+ expect(find.text('15% remaining'), findsOneWidget);
+ expect(find.text('90% remaining'), findsOneWidget);
+ expect(find.textContaining('used'), findsNothing);
+ // The week is detail, behind a tap.
+ expect(find.text('60% remaining'), findsNothing);
+ await tester.tap(find.text('Claude'));
+ await tester.pumpAndSettle();
+ expect(find.text('60% remaining'), findsOneWidget);
+
+ // The Settings row prints the same words, for the account with least left.
+ expect(lastUsageSummary.value, '15% remaining');
+ final settings = _Usage(const []);
+ addTearDown(settings.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => buildUsageSettingsRow(context, settings),
+ ),
+ ),
+ ),
+ );
+ expect(find.text('15% remaining'), findsOneWidget);
+ });
+
+ testWidgets('neutral above 20% left, muted amber to 6%, red at 5%', (
+ tester,
+ ) async {
+ await openPage(tester, [
+ MachineUsage(
+ machineName: 'Studio',
+ readings: [
+ reading(UsageProvider.claude, const [
+ UsageWindow(label: 'Session', usedPercent: 79),
+ UsageWindow(label: kWeeklyWindowLabel, usedPercent: 80),
+ UsageWindow(label: 'Fable', usedPercent: 94),
+ ]),
+ ],
+ ),
+ MachineUsage(
+ machineName: 'Laptop',
+ readings: [
+ reading(UsageProvider.codex, const [
+ UsageWindow(label: kWeeklyWindowLabel, usedPercent: 95),
+ ]),
+ ],
+ ),
+ ]);
+ await tester.tap(find.text('Claude'));
+ await tester.pumpAndSettle();
+
+ expect(inkOf(tester, '21% remaining'), AppPalette.textPrimary);
+ expect(inkOf(tester, '20% remaining'), AppPalette.usageLow);
+ expect(inkOf(tester, '6% remaining'), AppPalette.usageLow);
+ expect(inkOf(tester, '5% remaining'), AppPalette.usageCritical);
+ // Claude's headline is its 6% window; Codex's 5% is the least left.
+ expect(lastUsageSummary.value, '5% remaining');
+ });
+}
diff --git a/mobile/test/usage/usage_window_test.dart b/mobile/test/usage/usage_window_test.dart
index c6c7eb8fc..056660d33 100644
--- a/mobile/test/usage/usage_window_test.dart
+++ b/mobile/test/usage/usage_window_test.dart
@@ -89,7 +89,6 @@ void main() {
expect(loading.account, isNull);
expect(loading.hasFigures, isFalse);
expect(loading.tightest, isNull);
- expect(loading.railWindow, isNull);
});
test('has figures only when it answered AND reported a window', () {
@@ -119,23 +118,23 @@ void main() {
expect(reading.tightest, same(session));
});
- test('the rail prints the weekly window, even when another is tighter', () {
- const reading = ProviderUsage(
- provider: UsageProvider.claude,
- status: UsageStatus.ok,
- windows: [session, weekly, fable],
- );
- expect(reading.railWindow, same(weekly));
- });
-
- test('with no weekly window the rail falls back to the tightest', () {
- const reading = ProviderUsage(
- provider: UsageProvider.codex,
- status: UsageStatus.ok,
- windows: [fable, session],
- );
- expect(reading.railWindow, same(session));
- });
+ test(
+ 'a healthy weekly window does not stand in for a spent shorter one',
+ () {
+ // The weekly window used to head the Usage page while the model sheet
+ // printed the tightest — one account, two different figures.
+ const reading = ProviderUsage(
+ provider: UsageProvider.claude,
+ status: UsageStatus.ok,
+ windows: [
+ weekly,
+ UsageWindow(label: 'Session', usedPercent: 97),
+ ],
+ );
+ expect(reading.tightest!.label, 'Session');
+ expect(reading.tightest!.remainingLabel, '3% remaining');
+ },
+ );
});
group('parseResetTimestamp', () {
@@ -214,15 +213,41 @@ void main() {
});
group('usage pressure', () {
- test('calm below 80, amber from 80, red from 90', () {
- expect(usagePressureOf(79.9), UsagePressure.calm);
- expect(usagePressureOf(kUsageWarnPercent), UsagePressure.warn);
- expect(usagePressureOf(89.9), UsagePressure.warn);
- expect(usagePressureOf(kUsageCriticalPercent), UsagePressure.critical);
+ // The desktop's thresholds, on what is LEFT: neutral above 20%, amber from
+ // 20% down to 6%, red at 5% and below.
+ UsageWindow left(double remaining) =>
+ UsageWindow(label: 'Weekly', usedPercent: 100 - remaining);
+
+ test('calm at 21% left, amber at 20% and at 6%, red at 5%', () {
+ expect(left(21).pressure, UsagePressure.calm);
+ expect(left(kUsageLowRemaining.toDouble()).pressure, UsagePressure.warn);
+ expect(left(6).pressure, UsagePressure.warn);
expect(
- const UsageWindow(label: 'Weekly', usedPercent: 95).pressure,
+ left(kUsageCriticalRemaining.toDouble()).pressure,
UsagePressure.critical,
);
+ expect(left(0).pressure, UsagePressure.critical);
+ expect(left(100).pressure, UsagePressure.calm);
+ });
+
+ test('judged on the whole percent it prints, as the desktop judges it', () {
+ // 20.5% left prints as 20%, and a figure printed as 20% is amber.
+ expect(left(20.5).remainingLabel, '20% remaining');
+ expect(left(20.5).pressure, UsagePressure.warn);
+ expect(left(5.9).remainingLabel, '5% remaining');
+ expect(left(5.9).pressure, UsagePressure.critical);
+ });
+
+ test('remaining is worded as the desktop words it, never rounded away', () {
+ expect(left(80).remainingLabel, '80% remaining');
+ expect(left(0.4).remainingLabel, '<1% remaining');
+ expect(left(0).remainingLabel, '0% remaining');
+ // A partly spent window never reads as untouched.
+ expect(left(99.6).remainingLabel, '99% remaining');
+ expect(
+ const UsageWindow(label: 'Weekly', usedPercent: double.nan).pressure,
+ UsagePressure.calm,
+ );
});
});
}