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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
refactor(mobile): delete helpers and classes nothing in lib calls
dee346b964c744f
diff --git a/mobile/lib/analytics/analytics_sink.dart b/mobile/lib/analytics/analytics_sink.dartindex 44e273326..9d386728c 100644--- a/mobile/lib/analytics/analytics_sink.dart+++ b/mobile/lib/analytics/analytics_sink.dart@@ -117,52 +117,6 @@ class MutedAnalytics implements Analytics {Future<void> close() async {}}-/// What the Tracking screen's header card reports: where events go, whether-/// they are going at all, and the two ids they are filed under.-@immutable-class AnalyticsStreamStatus {- const AnalyticsStreamStatus({- required this.endpoint,- required this.offReason,- required this.deviceId,- required this.sessionId,- });-- final Uri endpoint;-- /// Why nothing is being sent, or null when the stream is live.- final String? offReason;-- final String deviceId;-- /// Empty until the first event of a launch has been tracked.- final String sessionId;-- bool get enabled => offReason == null;-}--/// Reads the live configuration and the ids on disk.-///-/// Injected into the Tracking screen the way `probeDebugEnvironment` is into-/// Settings ▸ Debug, and for the same reason: this reads a real `~/.harness`,-/// which a test must not.-///-/// The opt-out is checked here as well as in [_build] — a card that said-/// "Reporting" over a stream the user switched off would be the dishonest-/// label this screen exists to prevent.-AnalyticsStreamStatus probeAnalyticsStatus() {- final config = AnalyticsConfig.resolve();- final store = AnalyticsIdentityStore();- final ids = store.peek();- final optedOut = store.optedOut ? kAnalyticsOptedOutReason : null;- return AnalyticsStreamStatus(- endpoint: config.endpoint,- offReason: config.offReason ?? optedOut,- deviceId: ids.pseudoId,- sessionId: ids.sessionId,- );-}-/// Who events are filed under.////// `AppNotifier` writes it when sign-in resolves and clears it on sign-out; thediff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dartindex efe117143..4e51a4fd9 100644--- a/mobile/lib/api/api_client.dart+++ b/mobile/lib/api/api_client.dart@@ -150,10 +150,6 @@ class ApiException implements Exception {String toString() => message;}-bool isUnauthorizedError(Object error) =>- error is DioException && error.response?.statusCode == 401 ||- error is ApiException && error.status == 401;-/// Unwraps the backend's `{success, data, error}` envelope, which both legs/// speak: the CLI's loopback server mirrors it, and the viewer's own auth calls/// (`viewer/direct_auth_api.dart`) read it straight from the backend.diff --git a/mobile/lib/core/agent_output_stats.dart b/mobile/lib/core/agent_output_stats.dartindex ad2521a02..57c690f35 100644--- a/mobile/lib/core/agent_output_stats.dart+++ b/mobile/lib/core/agent_output_stats.dart@@ -50,11 +50,3 @@ class AgentOutputStats {/// A count off the wire, or null for anything that is not a JavaScript-safe non-negative integer.int? wireCount(Object? n) =>n is int && n >= 0 && n <= 9007199254740991 ? n : null;--/// `4.5M`, `12.3k`, `980` — the desktop's `formatTokens`, used for every count a row draws.-String formatCount(int count) {- if (count >= 1000000000) return '${(count / 1000000000).toStringAsFixed(1)}B';- if (count >= 1000000) return '${(count / 1000000).toStringAsFixed(1)}M';- if (count >= 1000) return '${(count / 1000).toStringAsFixed(1)}k';- return '$count';-}diff --git a/mobile/lib/core/snapshot_store.dart b/mobile/lib/core/snapshot_store.dartindex cfa7990ef..2701fe0f4 100644--- a/mobile/lib/core/snapshot_store.dart+++ b/mobile/lib/core/snapshot_store.dart@@ -82,22 +82,3 @@ class FileSnapshotStore implements SnapshotStore {}}}--/// The same contract with no disk under it — for tests, and for a build that-/// deliberately keeps nothing.-class MemorySnapshotStore implements SnapshotStore {- MemorySnapshotStore([this.contents]);-- String? contents;-- bool get isEmpty => contents == null;-- @override- Future<String?> read() async => contents;-- @override- Future<void> write(String value) async => contents = value;-- @override- Future<void> clear() async => contents = null;-}diff --git a/mobile/lib/demo/sample_harness.dart b/mobile/lib/demo/sample_harness.dartindex 22f5b665e..850ce1f8a 100644--- a/mobile/lib/demo/sample_harness.dart+++ b/mobile/lib/demo/sample_harness.dart@@ -21,13 +21,6 @@ class VerbStep extends SampleStep {final String verb;}-/// The agent stops to ask. [then] is what it does with the answer — the row's index, from 0.-class AskStep extends SampleStep {- const AskStep(this.ask, this.then, super.delay);- final SampleAsk ask;- final List<SampleStep> Function(int answer) then;-}-/// The turn ends, having said [reply].class DoneStep extends SampleStep {const DoneStep(this.reply, super.delay);@@ -335,17 +328,6 @@ class SampleHarness {case VerbStep(:final verb):live.verb = verb;host.liveChanged(this);- case AskStep(:final ask, :final then):- _stopSpin();- final wasWorking = working;- live- ..mode = LiveMode.asking- ..ask = ask- ..selected = 0;- _onAnswer = then;- if (wasWorking) host.workingChanged(this, false);- host.askChanged(this, ask);- host.liveChanged(this);case DoneStep(:final reply):replies.insert(0, reply);if (replies.length > 3) replies.removeLast();diff --git a/mobile/lib/logging/startup_trace.dart b/mobile/lib/logging/startup_trace.dartindex 7b54894e0..8217b44ec 100644--- a/mobile/lib/logging/startup_trace.dart+++ b/mobile/lib/logging/startup_trace.dart@@ -33,9 +33,6 @@ abstract final class StartupTrace {/// mid-launch would report negative elapsed time.static final Stopwatch _sinceLaunch = Stopwatch()..start();- /// How long since the app entered `startHarness`.- static Duration get sinceLaunch => _sinceLaunch.elapsed;-/// One moment on the launch timeline, stamped with its offset from launch.////// For things that have no duration of their own — the first frame, the point@@ -73,10 +70,7 @@ abstract final class StartupTrace {static void _record(String step, Duration started) {final elapsed = _sinceLaunch.elapsed - started;- appLog.info(- 'startup',- '$step took ${_ms(elapsed)} (at ${_ms(started)})',- );+ appLog.info('startup', '$step took ${_ms(elapsed)} (at ${_ms(started)})');}/// Milliseconds, the unit a launch is argued about in.diff --git a/mobile/lib/phone/agent_model_rows.dart b/mobile/lib/phone/agent_model_rows.dartindex 2ee65d2d2..7671d7ca7 100644--- a/mobile/lib/phone/agent_model_rows.dart+++ b/mobile/lib/phone/agent_model_rows.dart@@ -86,7 +86,7 @@ class ModelSectionHeading extends StatelessWidget {////// ⚠️ **The tick takes the leading slot, and the row wears the accent wash.**/// Both, because that is this app's own way of saying "this is the one" — see-/// [AppMenuItem], where the tick replaces the row's glyph rather than sitting+/// the desktop's `AppMenuItem`, where the tick replaces the row's glyph rather than sitting/// beside it so the column keeps one left edge. A fourth column for the tick/// would leave every unselected row with a gap the eye must cross to reach the/// name; the wash alone would be easy to miss at arm's length.diff --git a/mobile/lib/phone/machine_index.dart b/mobile/lib/phone/machine_index.dartindex c3fb5f49e..2665a844b 100644--- a/mobile/lib/phone/machine_index.dart+++ b/mobile/lib/phone/machine_index.dart@@ -1,4 +1,5 @@import 'package:harness_mobile/state/app_state.dart';+import 'phone_status.dart';/// Every machine the Machines tab draws, in the order a finger meets them.@@ -16,7 +17,8 @@ import 'phone_status.dart';/// than by being missing.List<MachineState> visibleMachines(AppNotifier notifier) {final states = [- for (final machine in notifier.machines) ?notifier.stateOf(machine.machineId),+ for (final machine in notifier.machines)+ ?notifier.stateOf(machine.machineId),];// Two runs, by whether the machine is usable as it stands — the split [MachinesTab] renders as// its two sections. A machine merely connecting belongs with the working ones: it needs nothing@@ -35,24 +37,3 @@ List<MachineState> visibleMachines(AppNotifier notifier) {}return [...working, ...needsAttention];}--/// The machines that work as they stand, in [visibleMachines] order.-///-/// Derived from that one list rather than re-partitioned here, so the sections the tab draws and-/// the order the pager walks cannot drift apart.-List<MachineState> workingMachines(List<MachineState> machines) => [- for (final machine in machines)- if (_works(machine)) machine,-];--/// The machines wanting something first — a password, or a Harness that is not running.-List<MachineState> machinesNeedingAttention(List<MachineState> machines) => [- for (final machine in machines)- if (!_works(machine)) machine,-];--bool _works(MachineState machine) =>- switch (phoneMachineStatusOf(machine)) {- PhoneMachineStatus.connecting || PhoneMachineStatus.ready => true,- PhoneMachineStatus.needsPassword || PhoneMachineStatus.offline => false,- };diff --git a/mobile/lib/phone/voice_mic_action.dart b/mobile/lib/phone/voice_mic_action.dartindex 5493de9a7..6c127bc17 100644--- a/mobile/lib/phone/voice_mic_action.dart+++ b/mobile/lib/phone/voice_mic_action.dart@@ -46,7 +46,8 @@ VoiceMicAction voiceMicAction(/// the person's back is worse than asking for one more tap.VoiceMicAction _tapAction(VoiceInputController voice, TerminalSession session) {final canSend = session.acceptsInput;- void send() => unawaited(voice.submit(session.voiceDeliver ?? session.sendComposerText));+ void send() =>+ unawaited(voice.submit(session.voiceDeliver ?? session.sendComposerText));if (voice.isSending) return _face(VoiceMicFace.sending);return switch (voice.status) {VoiceInputStatus.transcribing => _face(VoiceMicFace.busy),@@ -131,7 +132,9 @@ VoiceMicAction _holdAction(: VoiceMicFace.talk,onPressed: live ? _live : null,onHoldStart: live- ? () => unawaited(voice.startHold(session.voiceDeliver ?? session.sendComposerText))+ ? () => unawaited(+ voice.startHold(session.voiceDeliver ?? session.sendComposerText),+ ): null,onHoldFinish: live ? _release(voice, session) : null,);@@ -180,30 +183,3 @@ VoiceMicAction _face(onHoldStart: onHoldStart,onHoldFinish: onHoldFinish,);--/// What the mic is doing, in a word or two — null with it at rest.-///-/// In hold-to-talk the listening line says what the RELEASE will do instead of-/// naming the state: the thumb is already down and holding, so "Listening…" is-/// the one thing the person can see for themselves, and what happens when they-/// let go is the thing they cannot.-String? voiceActivityLabel(VoiceInputController voice) {- if (voice.isSending) return 'Sending…';- return switch (voice.status) {- // ⚠️ "Wait" rather than "Starting…" in hold mode, and it is the difference- // between working and not. Opening the microphone is real hardware time, and- // somebody holding a button starts talking the instant they press it — so- // the first word lands before anything is recording and the take comes back- // as half a sentence that transcribes to nothing. The line has to ASK them- // to wait, and the buzz when [VoiceInputStatus.listening] arrives is what- // tells them to go.- VoiceInputStatus.starting =>- micHoldsToTalk ? 'Opening the mic — wait for the buzz' : 'Starting…',- VoiceInputStatus.listening =>- micHoldsToTalk- ? 'Listening… release to send, slide off to cancel'- : 'Listening… tap to send',- VoiceInputStatus.transcribing => 'Transcribing…',- VoiceInputStatus.idle || VoiceInputStatus.unavailable => null,- };-}diff --git a/mobile/lib/shared/widgets/skeleton.dart b/mobile/lib/shared/widgets/skeleton.dartindex 1cc3eb164..e75297aab 100644--- a/mobile/lib/shared/widgets/skeleton.dart+++ b/mobile/lib/shared/widgets/skeleton.dart@@ -36,17 +36,6 @@ class Skeleton extends StatelessWidget {this.shape = BoxShape.rectangle,});- /// A round placeholder — an avatar, a status dot.- ///- /// ⚠️ Only for slots that ARE round. A 10-radius badge wants a 10-radius- /// [Skeleton], or the one detail that changes shape when data lands is the- /// one the eye catches.- const Skeleton.circle({super.key, required double size})- : width = size,- height = size,- radius = 0,- shape = BoxShape.circle;-/// A line of text: the tighter radius the app's type scale wants.const Skeleton.text({super.key, this.width, this.height = 12}): radius = 4,@@ -84,24 +73,6 @@ class Skeleton extends StatelessWidget {}}-/// A text line as a fraction of the row it sits in.-///-/// Fractions, not pixels, so a set of lines keeps its proportions in a 284px-/// menu and a 900px table alike. Needs a bounded width from its parent.-class SkeletonLine extends StatelessWidget {- const SkeletonLine({super.key, this.widthFactor = 1, this.height = 12});-- final double widthFactor;- final double height;-- @override- Widget build(BuildContext context) => FractionallySizedBox(- alignment: Alignment.centerLeft,- widthFactor: widthFactor,- child: Skeleton.text(height: height),- );-}-/// A text line that occupies exactly the line box of [style].////// The bar is drawn shorter than the line — text has ascenders and descenders@@ -109,7 +80,7 @@ class SkeletonLine extends StatelessWidget {/// style with a real [TextPainter], under the ambient [DefaultTextStyle] and/// text scaler. That is what makes a skeleton row and a real row the same/// height whatever font the fallback chain lands on: read a height off the-/// code and you get the arithmetic, which [AppMenuRowMetrics] documents is+/// code and you get the arithmetic, which the desktop's `AppMenuRowMetrics` documents is/// wrong by a fraction of a pixel per line.////// Give it a [width] (pixels) or a [widthFactor] (share of a bounded parent);@@ -193,78 +164,11 @@ class SkeletonText extends StatelessWidget {double skeletonFade(int i, int rows, {double depth = 0.65}) =>rows <= 0 ? 1 : 1 - (i / rows) * depth;-/// The gentler fade for a block that is capped short — a menu, a popover.-const double skeletonFadeLight = 0.5;--/// One list row: a round or square leading slot and two lines of unequal-/// width (0.42 / 0.68), the shape of most "icon + name + summary" rows.-///-/// Wear the real row's surface and padding around this — a bare skeleton-/// list draws grey bars with no home on the page ground, and the cards then-/// *appear* when data lands, which is exactly the shift a skeleton exists to-/// prevent.-class SkeletonListTile extends StatelessWidget {- const SkeletonListTile({- super.key,- this.leading = 30,- this.leadingRadius,- this.subtitle = true,- this.titleFactor = 0.42,- this.subtitleFactor = 0.68,- this.padding = const EdgeInsets.symmetric(vertical: 8),- });-- /// Size of the leading slot; 0 for none.- final double leading;-- /// Null draws a circle; a value draws a rounded square with that radius —- /// match the real badge.- final double? leadingRadius;-- final bool subtitle;- final double titleFactor;- final double subtitleFactor;- final EdgeInsets padding;-- @override- Widget build(BuildContext context) => Padding(- padding: padding,- child: Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- if (leading > 0) ...[- leadingRadius == null- ? Skeleton.circle(size: leading)- : Skeleton(- width: leading,- height: leading,- radius: leadingRadius!,- ),- const SizedBox(width: 12),- ],- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- mainAxisSize: MainAxisSize.min,- children: [- SkeletonLine(widthFactor: titleFactor, height: 13),- if (subtitle) ...[- const SizedBox(height: 6),- SkeletonLine(widthFactor: subtitleFactor, height: 11),- ],- ],- ),- ),- ],- ),- );-}-/// A column of [rows] placeholders, already faded towards the bottom and/// deaf to the pointer.///-/// [itemBuilder] gets the row index and builds its shape; the default is a-/// [SkeletonListTile]. Pick [rows] from what it replaces, not from habit: a+/// [itemBuilder] gets the row index and builds its shape. Pick [rows] from what it replaces, not+/// from habit: a/// long list pane wants 5–7, a capped block (dialog, popover) wants 3 — a/// skeleton *taller* than the list it stands in for causes an upward jump,/// which is worse than a downward one.@@ -272,14 +176,14 @@ class SkeletonList extends StatelessWidget {const SkeletonList({super.key,this.rows = 5,- this.itemBuilder,+ required this.itemBuilder,this.fadeDepth = 0.65,this.padding = EdgeInsets.zero,this.semanticsLabel = 'Loading',});final int rows;- final IndexedWidgetBuilder? itemBuilder;+ final IndexedWidgetBuilder itemBuilder;final double fadeDepth;final EdgeInsetsGeometry padding;final String semanticsLabel;@@ -300,7 +204,7 @@ class SkeletonList extends StatelessWidget {for (var i = 0; i < rows; i++)Opacity(opacity: skeletonFade(i, rows, depth: fadeDepth),- child: itemBuilder?.call(context, i) ?? const SkeletonListTile(),+ child: itemBuilder(context, i),),],),diff --git a/mobile/lib/shortcuts/app_keymap.dart b/mobile/lib/shortcuts/app_keymap.dartindex 3d94c4214..0a47f5b40 100644--- a/mobile/lib/shortcuts/app_keymap.dart+++ b/mobile/lib/shortcuts/app_keymap.dart@@ -3,7 +3,6 @@ import 'dart:io';import 'package:flutter/widgets.dart';import '../core/host_platform.dart';-import 'app_shortcuts.dart';import 'keymap.dart';import 'keymap_commands.dart';import 'keymap_store.dart';@@ -158,98 +157,3 @@ class KeymapRegion extends InheritedWidget {@overridebool updateShouldNotify(KeymapRegion oldWidget) => false;}--String? effectiveShortcutHint(BuildContext context, ShortcutAction action) {- final command = harnessCommands- .where((command) => command.action == action)- .firstOrNull;- final map = KeymapTheme.of(context);- if (command == null) return null;- final binding = (map?.current ?? harnessDefaultKeymap)- .bindingsFor(KeymapContext.workspace)- .where((binding) => binding.command == command.id)- .firstOrNull;- return binding == null ? null : describeKeyBinding(binding);-}--String withEffectiveShortcutHint(- BuildContext context,- String label,- ShortcutAction action,-) {- final hint = effectiveShortcutHint(context, action);- return hint == null ? label : '$label $hint';-}--String? effectiveCommandHint(- BuildContext context,- String command, {- KeymapContext contextKind = KeymapContext.workspace,-}) {- final bindings = (KeymapTheme.of(context)?.current ?? harnessDefaultKeymap)- .bindingsFor(contextKind);- final binding = bindings- .where((binding) => binding.command == command)- .firstOrNull;- return binding == null ? null : describeKeyBinding(binding);-}--List<ShortcutRow> effectiveShortcutRows(- BuildContext context,- KeymapContext contextKind,-) {- final map = KeymapTheme.of(context)?.current;- if (map == null && contextKind == KeymapContext.workspace) {- return shortcutRows();- }- final bindings = (map ?? harnessDefaultKeymap).bindingsFor(contextKind);- final defaultDigits =- contextKind != KeymapContext.picker &&- List.generate(kTabDigitCount, (i) {- final matches = bindings- .where((b) => b.command == 'swarm.select_${i + 1}')- .toList();- return matches.length == 1 &&- matches.single.keys.length == 1 &&- matches.single.keys.single == KeyStroke.parse('cmd+${i + 1}');- }).every((value) => value);- final shortcuts = appShortcuts();- return [- for (final command in harnessCommands)- if ((command.context == KeymapContext.workspace ||- command.context == contextKind) &&- (!defaultDigits ||- !RegExp(r'^swarm\.select_[1-9]$').hasMatch(command.id)))- if (command.action != null ||- bindings.any((b) => b.command == command.id))- ShortcutRow(- label:- shortcuts- .where((s) => s.action == command.action)- .firstOrNull- ?.label ??- command.label,- chords: [- for (final binding in bindings.where(- (b) => b.command == command.id,- ))- binding.keys.length == 1- ? describeKeyStrokeKeys(binding.keys.single)- : [- describeKeyBinding(binding)- .replaceAll('↵', 'Return')- .replaceAll('⇥', 'Tab'),- ],- ],- group: command.group,- ),- if (defaultDigits)- const ShortcutRow(- label: 'Select tabs 1–9',- chords: [- ['⌘', '1 – 9'],- ],- group: ShortcutGroup.navigate,- ),- ];-}diff --git a/mobile/lib/shortcuts/app_shortcuts.dart b/mobile/lib/shortcuts/app_shortcuts.dartindex 1440e12c4..a645a0ea8 100644--- a/mobile/lib/shortcuts/app_shortcuts.dart+++ b/mobile/lib/shortcuts/app_shortcuts.dart@@ -446,187 +446,3 @@ const kSwarmShortcuts = [group: ShortcutGroup.actions,),];--/// Command-number selects the first nine tabs in their visible order. The-/// shortcut sheet prints one row; pane movement uses Command-arrows.-const int kTabDigitCount = 9;--List<SingleActivator> tabDigitActivators() => const [- SingleActivator(LogicalKeyboardKey.digit1, meta: true),- SingleActivator(LogicalKeyboardKey.digit2, meta: true),- SingleActivator(LogicalKeyboardKey.digit3, meta: true),- SingleActivator(LogicalKeyboardKey.digit4, meta: true),- SingleActivator(LogicalKeyboardKey.digit5, meta: true),- SingleActivator(LogicalKeyboardKey.digit6, meta: true),- SingleActivator(LogicalKeyboardKey.digit7, meta: true),- SingleActivator(LogicalKeyboardKey.digit8, meta: true),- SingleActivator(LogicalKeyboardKey.digit9, meta: true),-];--/// One line in the shortcuts UI: what it does, and every chord that does it.-///-/// Not the same shape as [AppShortcut], and deliberately. Two activators can-/// drive one action — `⌘]` and `⌃⇥` both focus the next pane — which the-/// bindings need as two entries and the reader needs as one line. Printed as-/// two rows it reads as a duplicate the screen forgot to collapse.-class ShortcutRow {- const ShortcutRow({- required this.label,- required this.chords,- required this.group,- });-- final String label;-- /// Every way to fire it, in declaration order — the first is the one to- /// learn, the rest are alternates.- final List<KeyChord> chords;-- final ShortcutGroup group;-}--/// [kAppShortcuts] as the UI prints it: one row per action, alternates folded-/// in, and `⌘1`–`⌘9` as the single line it deserves.-///-/// Derived rather than written out, so a shortcut cannot be added to the-/// bindings and forgotten here.-List<ShortcutRow> shortcutRows() {- final byAction = <ShortcutAction, List<KeyChord>>{};- final order = <ShortcutAction>[];- final labels = <ShortcutAction, String>{};- final groups = <ShortcutAction, ShortcutGroup>{};-- for (final shortcut in appShortcuts()) {- if (byAction.putIfAbsent(shortcut.action, () => []).isEmpty) {- order.add(shortcut.action);- labels[shortcut.action] = shortcut.label;- groups[shortcut.action] = shortcut.group;- }- byAction[shortcut.action]!.add(describeShortcutKeys(shortcut.activator));- }-- final rows = [- for (final action in order)- ShortcutRow(- label: labels[action]!,- chords: byAction[action]!,- group: groups[action]!,- ),- ];-- // The digits are not in [kAppShortcuts] — nine near-identical rows would bury- // everything around them — so they join here, at the end of their group.- final digits = ShortcutRow(- label: 'Select tabs 1–9',- chords: const [- ['⌘', '1 – $kTabDigitCount'],- ],- group: ShortcutGroup.navigate,- );- final lastTab = rows.lastIndexWhere(- (row) => row.group == ShortcutGroup.navigate,- );- rows.insert(lastTab + 1, digits);- return rows;-}--/// A key this app deliberately does **not** take, and who has it instead.-class TerminalKey {- const TerminalKey(this.chord, this.label);-- final KeyChord chord;- final String label;-}--/// What the terminal keeps — the doc comment at the top of this file, stated-/// where a user can read it.-///-/// The shortcuts screen prints these beside the ones the app takes, because-/// "why is there no shortcut for X" is answered by seeing that X already-/// belongs to something.-const List<TerminalKey> kTerminalOwnedKeys = [- TerminalKey(['⌘', 'C'], 'Copy'),- TerminalKey(['⌘', 'V'], 'Paste'),- TerminalKey(['⌘', 'A'], 'Select all'),- TerminalKey(['esc'], 'Interrupt the engine'),- TerminalKey(['⌥', '⏎'], "Newline in the engine's prompt"),- TerminalKey(['⌃', 'C'], 'Cancel / interrupt in the agent'),-];--/// Turns the declared shortcuts into the map [CallbackShortcuts] wants.-///-/// A missing handler is left unbound rather than bound to nothing: a key that-/// silently does nothing is worse than a key that was never taken, because the-/// terminal underneath could have had it.-Map<ShortcutActivator, VoidCallback> buildShortcutBindings({- required Map<ShortcutAction, VoidCallback> handlers,- void Function(int index)? onSelectTabIndex,- bool swarmMode = true,-}) {- final bindings = <ShortcutActivator, VoidCallback>{};- for (final shortcut in appShortcuts(swarmMode: swarmMode)) {- final handler = handlers[shortcut.action];- if (handler != null) bindings[shortcut.activator] = handler;- }- if (onSelectTabIndex != null) {- final digits = tabDigitActivators();- for (var i = 0; i < digits.length; i++) {- bindings[digits[i]] = () => onSelectTabIndex(i);- }- }- return bindings;-}--/// One chord, split into the keys a keyboard actually has — `['⇧', '⌘', ']']`.-///-/// Split rather than joined because the shortcuts UI draws one keycap per key.-/// [describeShortcut] is the same thing run together, for the places that want-/// a string (a tooltip, a test's failure message).-typedef KeyChord = List<String>;--/// The caps for [activator], in the order Apple prints them.-KeyChord describeShortcutKeys(SingleActivator activator) => [- if (activator.control) '⌃',- if (activator.alt) '⌥',- if (activator.shift) '⇧',- if (activator.meta) '⌘',- _keyLabel(activator.trigger),-];--/// "⇧⌘]" — the way a Mac menu prints it, in the order Apple prints it.-String describeShortcut(SingleActivator activator) =>- describeShortcutKeys(activator).join();--String _keyLabel(LogicalKeyboardKey key) {- // keyLabel spells these out ("Arrow Left"), which is not how a Mac prints a- // shortcut.- if (key == LogicalKeyboardKey.arrowLeft) return '←';- if (key == LogicalKeyboardKey.arrowRight) return '→';- if (key == LogicalKeyboardKey.arrowUp) return '↑';- if (key == LogicalKeyboardKey.arrowDown) return '↓';- if (key == LogicalKeyboardKey.enter) return '⏎';- if (key == LogicalKeyboardKey.tab) return '⇥';- if (key == LogicalKeyboardKey.escape) return 'esc';- return key.keyLabel;-}--/// The chord for [action], ready to append to a tooltip.-///-/// Tooltips read this instead of spelling the keys out, so a rebinding cannot-/// leave a button advertising a key that no longer works.-String? shortcutHintFor(ShortcutAction action, {bool swarmMode = true}) {- for (final shortcut in appShortcuts(swarmMode: swarmMode)) {- if (shortcut.action == action) return describeShortcut(shortcut.activator);- }- return null;-}--/// "Reload machines ⌘R"-String withShortcutHint(- String tooltip,- ShortcutAction action, {- bool swarmMode = true,-}) {- final hint = shortcutHintFor(action, swarmMode: swarmMode);- return hint == null ? tooltip : '$tooltip $hint';-}diff --git a/mobile/lib/shortcuts/keymap_keyboard.dart b/mobile/lib/shortcuts/keymap_keyboard.dartindex c4941e211..90b6421af 100644--- a/mobile/lib/shortcuts/keymap_keyboard.dart+++ b/mobile/lib/shortcuts/keymap_keyboard.dart@@ -115,14 +115,3 @@ KeyStroke? keyStrokeFor(shift: shift,);}--KeyStroke? keyStrokeForEvent(KeyEvent event) {- final keyboard = HardwareKeyboard.instance;- return keyStrokeFor(- event.logicalKey,- control: keyboard.isControlPressed,- alt: keyboard.isAltPressed,- command: keyboard.isMetaPressed,- shift: keyboard.isShiftPressed,- );-}diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 3cd6c7680..ce175bc4f 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -155,13 +155,6 @@ class LocalManualFixture {});}-@visibleForTesting-Map<String, dynamic> eventWithClearPayload(- Map<String, dynamic> frame,- String type,- Map<String, dynamic> payload,-) => {...frame, 'type': type, 'payload': payload};-class MachineState {Machine machine;ConnectionStatus connectionStatus = ConnectionStatus.disconnected;diff --git a/mobile/lib/state/pane_preset.dart b/mobile/lib/state/pane_preset.dartindex 668a4c0cf..5eee2075a 100644--- a/mobile/lib/state/pane_preset.dart+++ b/mobile/lib/state/pane_preset.dart@@ -274,56 +274,6 @@ enum PanePreset {return _legacyIds[id];}- /// At most six useful shapes. Balanced grids that resolve to the same- /// rectangles at a particular count are offered only once.- static List<PanePreset> forCount(int count) {- if (count < 2) return const [];- return _choices.putIfAbsent(count, () {- final seen = <String>{};- return List.unmodifiable([- for (final preset in _candidates(count))- if (seen.add(_shapeKey(preset.tilesFor(count)))) preset,- ]);- });- }-- static final _choices = <int, List<PanePreset>>{};-- static List<PanePreset> _candidates(int count) => switch (count) {- < 2 => const [],- 2 => const [PanePreset.columns, PanePreset.rows],- 3 => const [- PanePreset.twoOverOne,- PanePreset.oneOverTwo,- PanePreset.mainLeft,- PanePreset.mainRight,- PanePreset.cols3,- PanePreset.rows,- ],- 4 => const [- PanePreset.quad,- PanePreset.mainAndStack,- PanePreset.mainOverGrid,- PanePreset.cols4,- PanePreset.rows,- ],- 5 => const [- PanePreset.balanced3,- PanePreset.twoOverThree,- PanePreset.middleMain,- PanePreset.mainAndGrid,- PanePreset.mainOverGrid,- PanePreset.cols5,- ],- _ => [- PanePreset.balanced2,- PanePreset.balanced3,- PanePreset.balanced4,- PanePreset.balanced5,- if (count <= 9) ...[PanePreset.mainAndGrid, PanePreset.mainOverGrid],- ],- };-/// Saved automatic/regular grids remain valid even though the picker now/// offers explicit, filled arrangements. Do not silently discard their IDs.bool supportsCount(int count) => switch (this) {@@ -347,29 +297,6 @@ enum PanePreset {PanePreset.mainOverGrid => count >= 4,};- /// Match the visible geometry rather than the old preset's name or tile- /// order. This highlights Columns/Rows for saved automatic two-pane splits.- static PanePreset? matchingChoice(int count, List<Rect> tiles) {- final key = _shapeKey(tiles);- for (final choice in forCount(count)) {- if (_shapeKey(choice.tilesFor(count)) == key) return choice;- }- return null;- }-- static String _shapeKey(List<Rect> tiles) {- final parts = [- for (final tile in tiles)- [- tile.left,- tile.top,- tile.right,- tile.bottom,- ].map((edge) => (edge * 1e8).round()).join(','),- ]..sort();- return parts.join(';');- }-/// What a grid of this size looks like when nobody has chosen.static PanePreset? defaultFor(int count) {return switch (count) {diff --git a/mobile/lib/terminal/terminal_input.dart b/mobile/lib/terminal/terminal_input.dartindex 088fa9c99..a192ab08d 100644--- a/mobile/lib/terminal/terminal_input.dart+++ b/mobile/lib/terminal/terminal_input.dart@@ -7,8 +7,8 @@ import 'package:xterm/xterm.dart';/// that only when it is configured to treat ⌥ as Meta (iTerm's "Esc+", Terminal.app's "Use Option/// as Meta Key"); xterm.dart has no such setting, and its [AltInputHandler] deliberately does/// nothing on macOS so ⌥ stays the compose key for `å`/`ø`/`¬`. So ⌥⏎ fell through to the keytab,-/// which matches on `Return` alone and answers `\r` — the submit. The key the shortcuts sheet-/// promises (`kTerminalOwnedKeys`) sent the turn instead of breaking the line.+/// which matches on `Return` alone and answers `\r` — the submit. The key the desktop's shortcuts+/// sheet promises (its `kTerminalOwnedKeys`) sent the turn instead of breaking the line.////// ⌥ is Meta for THIS ONE KEY, not for the keyboard: Enter carries no character to compose, so/// prefixing it costs nothing that ⌥-as-compose needs, and the rest of the alphabet is untouched.diff --git a/mobile/lib/terminal/terminal_typography.dart b/mobile/lib/terminal/terminal_typography.dartindex 929b9cdc7..96c30c9b7 100644--- a/mobile/lib/terminal/terminal_typography.dart+++ b/mobile/lib/terminal/terminal_typography.dart@@ -1,7 +1,5 @@import 'package:flutter/foundation.dart';-import '../core/apple_fonts.dart';-/// The default terminal face, per platform.////// Every family named here has to actually resolve on the OS it is named for,@@ -65,17 +63,6 @@ const linuxTerminalFontFallback = <String>['monospace',];-/// The default face for the platform this build is running on.-///-/// A getter, not a `const`: the answer depends on the host. The per-platform-/// constants above stay `const` so `TerminalFontChoice` can still name them-/// from its const constructor.-String get terminalFontFamily =>- hasAppleFonts ? macTerminalFontFamily : linuxTerminalFontFamily;--List<String> get terminalFontFallback =>- hasAppleFonts ? macTerminalFontFallback : linuxTerminalFontFallback;-/// 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 thediff --git a/mobile/lib/usage/claude_usage_source.dart b/mobile/lib/usage/claude_usage_source.dartindex 4787f6ff6..af085cc93 100644--- a/mobile/lib/usage/claude_usage_source.dart+++ b/mobile/lib/usage/claude_usage_source.dart@@ -1,124 +1,13 @@-import 'package:dio/dio.dart';--import '../logging/http_log.dart';-import 'usage_account_key.dart';-import 'usage_credentials.dart';import 'usage_source.dart';import 'usage_window.dart';-/// Claude Code's rate limits, read with the token `claude login` left behind.-///-/// ⚠️ **This endpoint is undocumented.** It is what the CLI itself asks when it-/// prints `/usage`, and it answers only to a token minted for the CLI — hence-/// the beta header and the CLI's own user agent, which together are what make-/// an OAuth token issued to Claude Code acceptable here. It can change without-/// notice, and when it does the failure is a parse error or a 4xx, both of-/// which this reports as a state rather than a crash. **TODO(BE):** replace-/// with a supported endpoint if one appears.-class ClaudeUsageSource implements UsageSource {- ClaudeUsageSource({Dio? dio, UsageCredentials? credentials})- : _dio = dio ?? attachHttpLog(buildUsageDio()),- _credentials = credentials ?? const UsageCredentials();-- final Dio _dio;- final UsageCredentials _credentials;-- static const _url = 'https://api.anthropic.com/api/oauth/usage';-- @override- UsageProvider get provider => UsageProvider.claude;-- @override- Future<ProviderUsage> read() async {- final token = await _credentials.claude();- if (token == null) return signedOut(provider);- final accountId = await _credentials.claudeAccountId();- // An expired token is spent as a sign-in rather than as a round trip: this- // app does not refresh what the CLI owns, so the request could only fail.- if (token.isExpired) {- return ProviderUsage(- provider: provider,- status: UsageStatus.signedOut,- message: 'Claude session expired — run claude to sign in again',- );- }- try {- final response = await _dio.getUri<Object?>(- Uri.parse(_url),- options: Options(- headers: {- 'Authorization': 'Bearer ${token.accessToken}',- 'anthropic-beta': 'oauth-2025-04-20',- 'User-Agent': 'claude-code/2.1.0',- },- ),- );- return claudeUsageFromAnswer(- statusCode: response.statusCode,- body: response.data,- account: accountId == null- ? null- : usageAccountKey(provider, accountId),- );- } on DioException {- return usageFailureFor(provider, null)!;- }- }-- /// The three windows the CLI itself shows, in the order they bite.- ///- /// Fable's weekly allowance has been spelled three ways across releases, so- /// all three are tried — an absent window is simply not drawn, which is why- /// a build reading a newer server loses a row rather than the whole panel.- static ProviderUsage _mapWindows(- Map<Object?, Object?> data, {- String? account,- }) {- final windows = <UsageWindow>[- ?_window('Session', data['five_hour']),- ?_window(kWeeklyWindowLabel, data['seven_day']),- ?_window(- 'Fable',- data['fable_weekly'] ??- data['fable_seven_day'] ??- data['seven_day_fable'],- ),- ];- if (windows.isEmpty) {- return const ProviderUsage(- provider: UsageProvider.claude,- status: UsageStatus.failed,- message: 'Claude reported no limits',- );- }- return ProviderUsage(- provider: UsageProvider.claude,- status: UsageStatus.ok,- windows: windows,- fetchedAt: DateTime.now(),- account: account,- );- }-- static UsageWindow? _window(String label, Object? raw) {- if (raw is! Map) return null;- final used = parseUsedPercent([raw['utilization'], raw['used_percentage']]);- if (used == null) return null;- return UsageWindow(- label: label,- usedPercent: used,- resetsAt: parseResetTimestamp(raw['resets_at']),- );- }-}--/// What Claude's usage endpoint said, as the rail draws it.+/// What Claude's usage endpoint said, as the rail draws it. A phone has no Claude login of its own:+/// a linked machine asks with its own token and hands back exactly what the endpoint sent+/// (`usage_read`, see `remote_usage.dart`), and this reads that answer.///-/// Shared by the two places an answer comes from — this computer asking with-/// its own token, and a REMOTE machine asking with its own and handing back-/// exactly what the vendor sent (`usage_read`, see `remote_usage.dart`). One-/// reading of the answer for both, so a window cannot be named one way here and-/// another way for a machine across the relay.+/// ⚠️ **The endpoint is undocumented.** It is what the CLI itself asks when it prints `/usage`, and+/// it answers only to a token minted for the CLI. It can change without notice, and when it does the+/// failure is a parse error or a 4xx, both of which this reports as a state rather than a crash.ProviderUsage claudeUsageFromAnswer({required int? statusCode,required Object? body,@@ -133,5 +22,48 @@ ProviderUsage claudeUsageFromAnswer({message: 'Claude answered in a shape this build cannot read',);}- return ClaudeUsageSource._mapWindows(body, account: account);+ return _claudeWindows(body, account: account);+}++/// The three windows the CLI itself shows, in the order they bite.+///+/// Fable's weekly allowance has been spelled three ways across releases, so+/// all three are tried — an absent window is simply not drawn, which is why+/// a build reading a newer server loses a row rather than the whole panel.+ProviderUsage _claudeWindows(Map<Object?, Object?> data, {String? account}) {+ final windows = <UsageWindow>[+ ?_claudeWindow('Session', data['five_hour']),+ ?_claudeWindow(kWeeklyWindowLabel, data['seven_day']),+ ?_claudeWindow(+ 'Fable',+ data['fable_weekly'] ??+ data['fable_seven_day'] ??+ data['seven_day_fable'],+ ),+ ];+ if (windows.isEmpty) {+ return const ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.failed,+ message: 'Claude reported no limits',+ );+ }+ return ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.ok,+ windows: windows,+ fetchedAt: DateTime.now(),+ account: account,+ );+}++UsageWindow? _claudeWindow(String label, Object? raw) {+ if (raw is! Map) return null;+ final used = parseUsedPercent([raw['utilization'], raw['used_percentage']]);+ if (used == null) return null;+ return UsageWindow(+ label: label,+ usedPercent: used,+ resetsAt: parseResetTimestamp(raw['resets_at']),+ );}diff --git a/mobile/lib/usage/codex_usage_source.dart b/mobile/lib/usage/codex_usage_source.dartindex 25b5b59cd..279094fdd 100644--- a/mobile/lib/usage/codex_usage_source.dart+++ b/mobile/lib/usage/codex_usage_source.dart@@ -1,121 +1,17 @@-import 'package:dio/dio.dart';--import '../logging/http_log.dart';-import 'usage_account_key.dart';-import 'usage_credentials.dart';import 'usage_source.dart';import 'usage_window.dart';-/// Codex's rate limits, read with the token `codex login` left in-/// `~/.codex/auth.json`.+/// What Codex's usage endpoint said, as the rail draws it — asked by a linked machine with its own+/// `codex login` token and handed back over the relay (`usage_read`, see `remote_usage.dart`).///-/// ⚠️ Undocumented, on the same terms as [ClaudeUsageSource]: this is the-/// backend the Codex CLI itself asks, and it can change without notice.+/// ⚠️ Undocumented, on the same terms as Claude's (`claude_usage_source.dart`): this is the backend the+/// Codex CLI itself asks, and it can change without notice.////// Codex numbers its windows rather than naming them — a primary and a/// secondary, whose real durations arrive in the payload — so the labels here/// are derived from `limit_window_seconds` instead of hardcoded. A build that/// printed "5h" for a window the server had quietly changed to 24h would be/// confidently wrong, which is worse than saying nothing.-class CodexUsageSource implements UsageSource {- CodexUsageSource({Dio? dio, UsageCredentials? credentials})- : _dio = dio ?? attachHttpLog(buildUsageDio()),- _credentials = credentials ?? const UsageCredentials();-- final Dio _dio;- final UsageCredentials _credentials;-- static const _url = 'https://chatgpt.com/backend-api/wham/usage';-- @override- UsageProvider get provider => UsageProvider.codex;-- @override- Future<ProviderUsage> read() async {- final token = await _credentials.codex();- if (token == null) return signedOut(provider);- final accountId = await _credentials.codexAccountId();- try {- final response = await _dio.getUri<Object?>(- Uri.parse(_url),- options: Options(- headers: {- 'Authorization': 'Bearer ${token.accessToken}',- 'ChatGPT-Account-Id': ?accountId,- },- ),- );- return codexUsageFromAnswer(- statusCode: response.statusCode,- body: response.data,- account: accountId == null- ? null- : usageAccountKey(provider, accountId),- );- } on DioException {- return usageFailureFor(provider, null)!;- }- }-- static ProviderUsage _mapWindows(- Map<Object?, Object?> data, {- String? account,- }) {- final limits = data['rate_limit'];- final windows = limits is Map- ? <UsageWindow>[- ?_window(limits['primary_window']),- ?_window(limits['secondary_window']),- ]- : const <UsageWindow>[];- if (windows.isEmpty) {- return const ProviderUsage(- provider: UsageProvider.codex,- status: UsageStatus.failed,- message: 'Codex reported no limits',- );- }- return ProviderUsage(- provider: UsageProvider.codex,- status: UsageStatus.ok,- windows: windows,- fetchedAt: DateTime.now(),- account: account,- );- }-- static UsageWindow? _window(Object? raw) {- if (raw is! Map) return null;- final used = parseUsedPercent([raw['used_percent']]);- if (used == null) return null;- return UsageWindow(- label: _labelFor(raw['limit_window_seconds']),- usedPercent: used,- resetsAt: parseResetTimestamp(raw['reset_at']),- );- }-- /// Names a window by how long it actually is.- ///- /// Falls back to the neutral "Limit" rather than guessing: a window whose- /// duration the server did not send is one this build knows nothing about,- /// and a made-up "5h" beside a real percentage would be read as measured.- static String _labelFor(Object? seconds) {- final value = seconds is num && seconds.isFinite && seconds > 0- ? seconds.round()- : null;- if (value == null) return 'Limit';- final hours = value ~/ 3600;- if (hours < 1) return '${value ~/ 60}m';- if (hours < 24) return '${hours}h';- final days = hours ~/ 24;- return days == 7 ? kWeeklyWindowLabel : '${days}d';- }-}--/// What Codex's usage endpoint said, as the rail draws it — shared by this-/// computer's own reading and a remote machine's, for the reason-/// [claudeUsageFromAnswer] gives.ProviderUsage codexUsageFromAnswer({required int? statusCode,required Object? body,@@ -130,5 +26,57 @@ ProviderUsage codexUsageFromAnswer({message: 'Codex answered in a shape this build cannot read',);}- return CodexUsageSource._mapWindows(body, account: account);+ return _codexWindows(body, account: account);+}++ProviderUsage _codexWindows(Map<Object?, Object?> data, {String? account}) {+ final limits = data['rate_limit'];+ final windows = limits is Map+ ? <UsageWindow>[+ ?_codexWindow(limits['primary_window']),+ ?_codexWindow(limits['secondary_window']),+ ]+ : const <UsageWindow>[];+ if (windows.isEmpty) {+ return const ProviderUsage(+ provider: UsageProvider.codex,+ status: UsageStatus.failed,+ message: 'Codex reported no limits',+ );+ }+ return ProviderUsage(+ provider: UsageProvider.codex,+ status: UsageStatus.ok,+ windows: windows,+ fetchedAt: DateTime.now(),+ account: account,+ );+}++UsageWindow? _codexWindow(Object? raw) {+ if (raw is! Map) return null;+ final used = parseUsedPercent([raw['used_percent']]);+ if (used == null) return null;+ return UsageWindow(+ label: _codexLabelFor(raw['limit_window_seconds']),+ usedPercent: used,+ resetsAt: parseResetTimestamp(raw['reset_at']),+ );+}++/// Names a window by how long it actually is.+///+/// Falls back to the neutral "Limit" rather than guessing: a window whose+/// duration the server did not send is one this build knows nothing about,+/// and a made-up "5h" beside a real percentage would be read as measured.+String _codexLabelFor(Object? seconds) {+ final value = seconds is num && seconds.isFinite && seconds > 0+ ? seconds.round()+ : null;+ if (value == null) return 'Limit';+ final hours = value ~/ 3600;+ if (hours < 1) return '${value ~/ 60}m';+ if (hours < 24) return '${hours}h';+ final days = hours ~/ 24;+ return days == 7 ? kWeeklyWindowLabel : '${days}d';}diff --git a/mobile/lib/usage/usage_account_key.dart b/mobile/lib/usage/usage_account_key.dartdeleted file mode 100644index e55b9271f..000000000--- a/mobile/lib/usage/usage_account_key.dart+++ /dev/null@@ -1,31 +0,0 @@-import 'dart:convert';--import 'package:cryptography/dart.dart';--import 'usage_window.dart';--/// An account, as both ends of `usage_read` name it: the first 16 hex-/// characters of sha256(`<provider>:<id>`).-///-/// Hashed rather than carried raw because RPC answers are LOGGED — `WsConn`-/// writes every reply to `~/.harness/logs` — and an account id has no business-/// there. Equality survives hashing, and equality is all the strip needs: it is-/// what decides whether a remote machine's subscription is this one again or a-/// different one worth its own figure.-///-/// ⚠️ **A cross-language contract.** A remote machine computes the SAME key in-/// `autonomous-harness/cli/src/lib/accountUsage.ts` (`accountKey`), and the two-/// must agree byte for byte — drift, and every remote reading looks like a-/// different account, so the strip prints one subscription twice. Both suites-/// pin the same vector (`test/usage_account_key_test.dart` here,-/// `accountUsage.spec.ts` there) for exactly that reason.-String usageAccountKey(UsageProvider provider, String accountId) {- final digest = const DartSha256().hashSync(- utf8.encode('${provider.name}:$accountId'),- );- final hex = StringBuffer();- for (final byte in digest.bytes) {- hex.write(byte.toRadixString(16).padLeft(2, '0'));- }- return hex.toString().substring(0, 16);-}diff --git a/mobile/lib/usage/usage_controller.dart b/mobile/lib/usage/usage_controller.dartindex 0848de6ca..750b00609 100644--- a/mobile/lib/usage/usage_controller.dart+++ b/mobile/lib/usage/usage_controller.dart@@ -3,6 +3,7 @@ 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';@@ -18,13 +19,14 @@ import 'usage_window.dart';/// 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+/// one reads no LOCAL sources.** The desktop constructs its+/// `[ClaudeUsageSource(), CodexUsageSource()]` by default (neither has a copy+/// here), 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+/// has no `~` in the sense those paths mean. The desktop's `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 thediff --git a/mobile/lib/usage/usage_credentials.dart b/mobile/lib/usage/usage_credentials.dartdeleted file mode 100644index ae5351165..000000000--- a/mobile/lib/usage/usage_credentials.dart+++ /dev/null@@ -1,153 +0,0 @@-/// Where the agent CLIs keep the tokens their usage endpoints want.-///-/// This app reads them; it never writes them and never refreshes them. One-/// sign-in per machine, owned by the CLI that made it. A second copy here-/// would be a second thing to expire and to disagree about.-///-/// **Nothing in this file may be logged.** Every value it returns is a bearer-/// token; the CLI transcript exists precisely so secrets stay out of argv, and-/// a `print` here would undo that. Callers get the token and nothing else —-/// no wrapper carrying it into an error message.-library;--import 'dart:convert';-import 'dart:io';--/// A token, and when it stops working.-class UsageToken {- const UsageToken({required this.accessToken, this.expiresAt});-- final String accessToken;-- /// When the token expires, when the store said so. Null means unknown, which- /// is treated as "try it" rather than "assume dead" — the endpoint answering- /// 401 is a better authority than a clock we may be reading wrong.- final DateTime? expiresAt;-- /// Already dead, so the request can be skipped and reported as a sign-in- /// rather than spent as a round trip that will fail.- bool get isExpired {- final at = expiresAt;- return at != null && at.isBefore(DateTime.now());- }-}--/// Reads the tokens the usage endpoints need, from wherever each CLI put them.-class UsageCredentials {- const UsageCredentials({this.home, this.runProcess});-- /// Overridden by tests. Null means this machine's real home.- final String? home;-- /// Overridden by tests so nothing shells out to the real `security`.- final Future<ProcessResult> Function(String, List<String>)? runProcess;-- String? get _home => home ?? Platform.environment['HOME'];-- /// Claude Code's OAuth token.- ///- /// macOS keeps it in the login Keychain and Linux in a file, so both are- /// tried in that order — and the file is tried on macOS too, because a- /// Keychain that will not answer (a locked login chain, a Finder launch with- /// no authorization) is a state, not the end of the road.- Future<UsageToken?> claude() async {- final fromKeychain = await _readKeychain();- final token =- _parseClaude(fromKeychain) ??- _parseClaude(_readFile('.claude/.credentials.json'));- return token;- }-- /// Codex's OAuth token, written by `codex login`.- Future<UsageToken?> codex() async {- final raw = _readFile('.codex/auth.json');- if (raw == null) return null;- final decoded = _decode(raw);- final tokens = decoded?['tokens'];- if (tokens is! Map) return null;- final access = tokens['access_token'];- if (access is! String || access.isEmpty) return null;- return UsageToken(accessToken: access);- }-- /// The account id Codex's backend scopes the reading to.- Future<String?> codexAccountId() async {- final decoded = _decode(_readFile('.codex/auth.json'));- final tokens = decoded?['tokens'];- if (tokens is! Map) return null;- final id = tokens['account_id'];- return id is String && id.isNotEmpty ? id : null;- }-- /// The account Claude Code is signed in as: `oauthAccount.accountUuid` in- /// `~/.claude.json`, which is where it records who it is on every platform.- /// The token store — Keychain or `.credentials.json` — does not carry it.- Future<String?> claudeAccountId() async {- final profile = _decode(_readFile('.claude.json'))?['oauthAccount'];- if (profile is! Map) return null;- final id = profile['accountUuid'];- return id is String && id.isNotEmpty ? id : null;- }-- UsageToken? _parseClaude(String? raw) {- if (raw == null) return null;- final oauth = _decode(raw)?['claudeAiOauth'];- if (oauth is! Map) return null;- final access = oauth['accessToken'];- if (access is! String || access.isEmpty) return null;- final expires = oauth['expiresAt'];- return UsageToken(- accessToken: access,- expiresAt: expires is num- ? DateTime.fromMillisecondsSinceEpoch(expires.round())- : null,- );- }-- Map<String, Object?>? _decode(String? raw) {- if (raw == null) return null;- try {- final decoded = jsonDecode(raw);- return decoded is Map<String, Object?> ? decoded : null;- } on FormatException {- // A half-written credentials file is not news: the CLI that owns it is- // mid-refresh, and the next poll a minute from now will read it whole.- return null;- }- }-- String? _readFile(String relative) {- final home = _home;- if (home == null) return null;- final file = File('$home${Platform.pathSeparator}$relative');- if (!file.existsSync()) return null;- try {- return file.readAsStringSync();- } on FileSystemException {- return null;- }- }-- /// The macOS Keychain item Claude Code writes.- ///- /// `security` is used rather than a plugin because the item is a plain- /// generic password and this is one read on a timer — a native channel would- /// be a second thing to keep in step across two platforms for it.- Future<String?> _readKeychain() async {- if (!Platform.isMacOS) return null;- final run = runProcess ?? Process.run;- try {- final result = await run('security', const [- 'find-generic-password',- '-s',- 'Claude Code-credentials',- '-w',- ]);- if (result.exitCode != 0) return null;- final out = result.stdout;- return out is String && out.trim().isNotEmpty ? out.trim() : null;- } on ProcessException {- return null;- }- }-}diff --git a/mobile/lib/usage/usage_source.dart b/mobile/lib/usage/usage_source.dartindex 679d088cf..5e5806172 100644--- a/mobile/lib/usage/usage_source.dart+++ b/mobile/lib/usage/usage_source.dart@@ -1,5 +1,3 @@-import 'package:dio/dio.dart';-import 'usage_window.dart';/// One account's usage, fetched from whoever knows it.@@ -20,19 +18,6 @@ abstract class UsageSource {Future<ProviderUsage> read();}-/// A Dio configured the way every usage call wants it.-///-/// `validateStatus` lets 4xx through so a 401 can be read as "sign in" rather-/// than surfacing as a transport failure — the split [ApiClient] draws too.-Dio buildUsageDio({String? baseUrl}) => Dio(- BaseOptions(- baseUrl: baseUrl ?? '',- connectTimeout: const Duration(seconds: 10),- receiveTimeout: const Duration(seconds: 15),- validateStatus: (status) => status != null && status >= 200 && status < 600,- ),-);-/// Turns a finished request into the state the rail should draw.////// Shared because the two vendors fail in the same four ways even though theydiff --git a/mobile/lib/usage/usage_window.dart b/mobile/lib/usage/usage_window.dartindex 6ea8e1a93..4f508bf02 100644--- a/mobile/lib/usage/usage_window.dart+++ b/mobile/lib/usage/usage_window.dart@@ -118,8 +118,8 @@ class ProviderUsage {/// When these figures were read. Null until the first answer lands.final DateTime? fetchedAt;- /// Which account these figures belong to — `usageAccountKey`, never the id- /// itself — or null when the machine that read them could not say.+ /// Which account these figures belong to — a key the machine that read them derives from the+ /// id, never the id itself — or null when that machine could not say.////// It is what lets the strip show one figure per ACCOUNT rather than one per/// machine: a remote machine signed in to this same subscription is this