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.

Models: one usage reading for the menu, the picker and New Harness

Tim59e2a9d01e7b
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 051e7a432..b413db404 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -283,8 +283,8 @@ class _SwarmScreenState extends State<SwarmScreen>
unawaited(_projects.load());
unawaited(_navigation.load());
_spokenTasks = app.spokenTasks.listen(_openSpokenTask);
- _modelsMenu =
- widget.modelsMenu ?? ModelsMenuController(remote: app.readRemoteUsage);
+ // The app's shared controller, so this menu and every pane's model picker show one reading.
+ _modelsMenu = widget.modelsMenu ?? app.modelsMenu;
app.modelManager.addListener(_modelManagerChanged);
_modelsRequests = app.modelsRequests.listen((_) {
if (mounted && _modelsOverlay == null) {
@@ -293,7 +293,10 @@ class _SwarmScreenState extends State<SwarmScreen>
});
if (!kUnderTest) {
WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) app.modelManager.start();
+ if (!mounted) return;
+ app.modelManager.start();
+ // Subscription usage is read ahead, so opening a menu shows it without waiting.
+ _modelsMenu!.start();
});
}
if (_native) {
@@ -381,7 +384,6 @@ class _SwarmScreenState extends State<SwarmScreen>
_commandFocus.dispose();
if (_hasCommandBar) _commandBar.dispose();
unawaited(_spokenTasks?.cancel());
- if (widget.modelsMenu == null) _modelsMenu?.dispose();
if (_native) {
unawaited(_channel.invokeMethod<void>('machinesState', {'machines': []}));
app.removeListener(_syncNative);
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index e23cff2f1..ffed4a391 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -67,6 +67,7 @@ import 'pane_preset.dart';
import 'pane_arrangement.dart';
import 'pending_question.dart';
import 'session_preview.dart';
+import '../usage/models_menu_controller.dart';
import '../usage/remote_usage.dart';
import '../usage/usage_accounts.dart';
import '../orchestrator/orchestrator_controller.dart';
@@ -5097,6 +5098,14 @@ class AppNotifier extends ChangeNotifier {
ModelManagerController get modelManager =>
_modelManager ??= ModelManagerController(this);
+ ModelsMenuController? _modelsMenu;
+
+ /// Subscription readings for the whole window: the Models panel, New Harness and every pane's model
+ /// picker read this ONE controller. Each used to own its own, read at a different moment, and the
+ /// picker said "Not signed in" beside a menu showing the same account with 8% left.
+ ModelsMenuController get modelsMenu =>
+ _modelsMenu ??= ModelsMenuController(remote: readRemoteUsage);
+
Future<Map<String, dynamic>> localModels(
String machineId, {
bool refresh = false,
@@ -6238,8 +6247,8 @@ class AppNotifier extends ChangeNotifier {
/// A seam, because reaching it through real panes means `focusPane`, which
/// announces the focus to the machine, which dials it — and a test with no
/// live connection hangs rather than fails.
- late Iterable<({String machineId, String agentId})> Function()
- watchedAgents = _visibleOnTab;
+ late Iterable<({String machineId, String agentId})> Function() watchedAgents =
+ _visibleOnTab;
/// The real answer, reachable from a test without going through `focusPane`.
@visibleForTesting
@@ -10989,6 +10998,7 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
_modelManager?.dispose();
+ _modelsMenu?.dispose();
for (final project in _orchestratorProjects.values) {
project.dispose();
}
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 87aabff50..a1a2f0e1c 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -914,7 +914,10 @@ class NewHarnessController extends ChangeNotifier {
final machine = _machineId;
_loadingModels = true;
if (_modelUsage == null) {
- _modelUsage = ModelsMenuController(remote: app.readRemoteUsage);
+ // The app's shared readings, the same the Models menu and pane pickers show. Owned by the
+ // app, so this form never disposes it.
+ _modelUsage = app.modelsMenu;
+ _ownsModelUsage = false;
_modelUsage!.addListener(_refresh);
}
// Native credential reads stay out of fixture tests, as in the session picker.
diff --git a/desktop/lib/usage/models_menu_controller.dart b/desktop/lib/usage/models_menu_controller.dart
index 3f384fffe..530a0a0cb 100644
--- a/desktop/lib/usage/models_menu_controller.dart
+++ b/desktop/lib/usage/models_menu_controller.dart
@@ -7,14 +7,18 @@ import 'usage_accounts.dart';
import 'usage_controller.dart';
import 'usage_window.dart';
-/// Subscription readings for the Models panel. Opening the panel reads
-/// the cached snapshot immediately and refreshes at most once per minute.
-/// No polling, credential reads or requests run on startup or tab changes.
+/// Subscription readings for the Models panel, the pane pickers and New Harness.
+///
+/// Read ahead, not on click: [start] reads once and then every [interval] in the background, so
+/// opening the panel shows a figure already in hand instead of "Checking usage…". Opening still asks
+/// for a fresh read, capped at once per minute. A figure stays on screen for up to [maxAge]; after
+/// that it is too old to trust and the row says "Usage unavailable".
class ModelsMenuController extends ChangeNotifier {
ModelsMenuController({
UsageController? usage,
Future<List<MachineUsage>> Function()? remote,
DateTime Function()? now,
+ this.interval = const Duration(minutes: 5),
}) : _usage = usage ?? UsageController(remote: remote, autoStart: false),
_ownsUsage = usage == null,
_now = now ?? DateTime.now {
@@ -24,6 +28,14 @@ class ModelsMenuController extends ChangeNotifier {
final UsageController _usage;
final bool _ownsUsage;
final DateTime Function() _now;
+
+ /// How often [start] reads in the background.
+ final Duration interval;
+
+ /// How long a figure is shown before it is too old to trust.
+ static const maxAge = Duration(hours: 1);
+
+ Timer? _timer;
Future<void>? _pending;
DateTime? _lastAttempt;
bool _failed = false;
@@ -31,7 +43,7 @@ class ModelsMenuController extends ChangeNotifier {
List<Map<String, Object?>> get rows => [
for (final account in _usage.accounts)
- _row(account, _now(), failed: _failed),
+ _row(account, _now(), failed: _failed, refreshing: _pending != null),
];
/// The subscription the selected agent machine can actually use. An account
@@ -44,12 +56,25 @@ class ModelsMenuController extends ChangeNotifier {
for (final account in _usage.accounts) {
if (account.provider.engineId == engine &&
(local ? account.isLocal : account.machines.contains(machineName))) {
- return _row(account, _now(), failed: _failed);
+ return _row(
+ account,
+ _now(),
+ failed: _failed,
+ refreshing: _pending != null,
+ );
}
}
return null;
}
+ /// Read now and then every [interval], so the figure is ready before anyone opens a menu.
+ /// Callers keep this out of tests: a periodic timer never lets `pumpAndSettle` settle.
+ void start() {
+ if (_disposed || _timer != null) return;
+ unawaited(refresh());
+ _timer = Timer.periodic(interval, (_) => unawaited(refresh()));
+ }
+
Future<void> refresh() {
if (_disposed) return Future.value();
// Re-evaluate expired windows even if another request is already running.
@@ -61,7 +86,11 @@ class ModelsMenuController extends ChangeNotifier {
}
_lastAttempt = _now();
_failed = false;
- return _pending = _refresh();
+ final pending = _pending = _refresh();
+ // Announce the read itself, so an expired row says "Checking usage…" while it runs rather than
+ // "Usage unavailable" for a figure that is on its way.
+ _changed();
+ return pending;
}
Future<void> _refresh() async {
@@ -84,6 +113,7 @@ class ModelsMenuController extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
+ _timer?.cancel();
_usage.removeListener(_changed);
if (_ownsUsage) _usage.dispose();
super.dispose();
@@ -93,6 +123,7 @@ class ModelsMenuController extends ChangeNotifier {
UsageAccount account,
DateTime now, {
required bool failed,
+ bool refreshing = false,
}) {
final reading = account.reading;
final provider = switch (reading.provider) {
@@ -102,7 +133,7 @@ class ModelsMenuController extends ChangeNotifier {
final windows = reading.windows;
final expired =
(reading.fetchedAt != null &&
- now.difference(reading.fetchedAt!) > const Duration(minutes: 2)) ||
+ now.difference(reading.fetchedAt!) > maxAge) ||
windows.any((w) => w.resetsAt != null && !w.resetsAt!.isAfter(now));
final valid =
!failed &&
@@ -122,6 +153,11 @@ class ModelsMenuController extends ChangeNotifier {
status = '${_remaining(limiting)} remaining';
remainingPercent = (100 - limiting.usedPercent).clamp(0, 100).toDouble();
details.add('Limiting window: ${limiting.label}');
+ // A cached figure says how old it is, so an hour-old reading never passes for a live one.
+ final age = reading.fetchedAt == null
+ ? null
+ : now.difference(reading.fetchedAt!).inMinutes;
+ if (age != null && age >= 2) details.add('Read $age min ago');
for (final window in windows) {
final reset = window.resetsInLabel(now: now);
details.add(
@@ -130,15 +166,21 @@ class ModelsMenuController extends ChangeNotifier {
);
}
} else {
- status = failed || expired
+ // An expired reading with a read already under way is not "unavailable": the new figure is
+ // seconds out, and saying otherwise flashed "Usage unavailable" on every open after a pause.
+ status = failed
? 'Usage unavailable'
+ : expired
+ ? (refreshing ? 'Checking usage…' : 'Usage unavailable')
: switch (reading.status) {
UsageStatus.loading => 'Checking usage…',
UsageStatus.signedOut => 'Not signed in',
_ => 'Usage unavailable',
};
details.add(
- expired
+ expired && refreshing && !failed
+ ? 'Reading the latest usage…'
+ : expired
? 'The last reading has expired. Reopen Models to refresh.'
: reading.message ?? status,
);
diff --git a/desktop/lib/usage/usage_controller.dart b/desktop/lib/usage/usage_controller.dart
index ff116fd47..5a2457238 100644
--- a/desktop/lib/usage/usage_controller.dart
+++ b/desktop/lib/usage/usage_controller.dart
@@ -134,6 +134,12 @@ class UsageController extends ChangeNotifier {
// backwards.
if (_disposed || request != _request) return;
for (final result in results) {
+ // A failed read keeps the last good figures, as the class promises: a network hiccup or a
+ // rate-limited request used to replace a live reading with "Usage unavailable".
+ final previous = _readings[result.provider];
+ if (result.status == UsageStatus.failed && previous?.hasFigures == true) {
+ continue;
+ }
_readings[result.provider] = result;
}
_landed = true;
diff --git a/desktop/lib/widgets/grid_model_picker.dart b/desktop/lib/widgets/grid_model_picker.dart
index a83706adf..b5be6c468 100644
--- a/desktop/lib/widgets/grid_model_picker.dart
+++ b/desktop/lib/widgets/grid_model_picker.dart
@@ -94,12 +94,18 @@ class GridModelPicker extends StatefulWidget {
class _GridModelPickerState extends State<GridModelPicker> {
bool _loading = false;
- ModelsMenuController? _usage;
+
+ /// The window's shared subscription readings — the same controller the Models panel draws,
+ /// so this row and that menu cannot disagree. Owned by the app, never disposed here.
+ late final ModelsMenuController _usage = widget.notifier.modelsMenu;
GridModels? _last;
@override
void initState() {
super.initState();
+ // A reading that lands while the menu is open redraws its Subscription row, rather than
+ // leaving "Checking usage…" there until the next open.
+ _usage.addListener(_redrawOpenMenu);
// Warm the answer as soon as the control exists, so a click lands on a memo rather than on two
// subprocess spawns and two network round trips — measured at ~1.4s, which is a person watching
// a header do nothing. Fire-and-forget: nothing here waits on it, and a failure just means the
@@ -108,14 +114,10 @@ class _GridModelPickerState extends State<GridModelPicker> {
}
Future<void> _prefetch() async {
- // Created here, not only on the cold path: a warm open reads `_usage.rows` for the subscription
- // row's provider name and percentage, and skipping it left that row falling back to the bare
- // engine label with no status beside it.
- _usage ??= ModelsMenuController(remote: widget.notifier.readRemoteUsage);
// Not under `flutter test`: a refresh reads the Keychain and asks the vendors, the same reads the
// usage rail keeps out of tests (kUnderTest) — here every test that drew a pane header left that
// work's timers pending after the tree was gone. Opening the menu still refreshes.
- if (!kUnderTest) unawaited(_usage!.refresh().catchError((_) {}));
+ if (!kUnderTest) unawaited(_usage.refresh().catchError((_) {}));
final answer = await widget.notifier.gridModels(widget.machineId);
if (mounted) _last = answer;
}
@@ -216,7 +218,7 @@ class _GridModelPickerState extends State<GridModelPicker> {
// A pane can go away under an open menu — closed, moved, or its swarm switched — and an overlay
// entry outlives the State that inserted it.
_close?.call();
- _usage?.dispose();
+ _usage.removeListener(_redrawOpenMenu);
super.dispose();
}
@@ -233,17 +235,11 @@ class _GridModelPickerState extends State<GridModelPicker> {
/// The subscription reading for THIS agent's engine, or null when there is none to show.
///
- /// Built from the same controller the window's own Models menu uses, so the percentage here and
+ /// Read from the same controller the Models panel uses, so the percentage here and
/// the percentage up there cannot disagree. Its refresh is capped at once a minute and it answers
/// from cache in between, which is why opening this menu does not cost a request.
- Map<String, Object?>? _subscriptionRow() {
- final engine = widget.engineLabel?.trim().toLowerCase();
- if (engine == null || engine.isEmpty) return null;
- for (final row in _usage?.rows ?? const <Map<String, Object?>>[]) {
- if (row['engine'] == engine) return row;
- }
- return null;
- }
+ Map<String, Object?>? _subscriptionRow() =>
+ subscriptionRowFor(widget.engineLabel, _usage.rows);
Future<void> _open() async {
if (_loading) return;
@@ -259,13 +255,12 @@ class _GridModelPickerState extends State<GridModelPicker> {
}
setState(() => _loading = true);
try {
- _usage ??= ModelsMenuController(remote: widget.notifier.readRemoteUsage);
// ⚠️ The usage read is NOT awaited. It is decoration — a percentage beside the subscription
// row — while the grid list is the menu's actual content, and a menu that waits on a credential
// read to draw a list it already has is a menu that feels broken whenever that source is slow.
// This open uses whatever is cached; the refresh lands for the next one. `refresh()` is itself
// capped at once a minute, so opening the menu repeatedly costs nothing.
- unawaited(_usage!.refresh().catchError((_) {}));
+ unawaited(_usage.refresh().catchError((_) {}));
answer = await widget.notifier.gridModels(widget.machineId);
} finally {
if (mounted) setState(() => _loading = false);
@@ -293,14 +288,14 @@ class _GridModelPickerState extends State<GridModelPicker> {
0,
);
- final subscription = _subscriptionRow();
final chosen = await _showMenu(
position: position,
body: (close) => _ModelPickerPanel(
answer: _shown!,
engineLabel: widget.engineLabel,
currentModel: _effectiveModel,
- subscription: subscription,
+ // Read on every draw, so a usage refresh that lands under the open menu shows in it.
+ subscription: _subscriptionRow(),
sections: _sectionsToDraw(_shown!),
subtitleFor: _subtitleFor,
emptySentence: (section) => _emptySentence(_shown!, section),
@@ -750,6 +745,23 @@ class _ModelPickerPanelState extends State<_ModelPickerPanel> {
);
}
+/// The subscription row for [engine] among the Models menu's [rows], or null when there is none.
+///
+/// One engine can have several rows: this computer's login first, then each other account a
+/// remote machine is signed in to. A row with a figure wins over one without — this Mac signed
+/// out beside a machine whose login is live should show the live one, not "Not signed in".
+@visibleForTesting
+Map<String, Object?>? subscriptionRowFor(
+ String? engine,
+ List<Map<String, Object?>> rows,
+) {
+ final key = engine?.trim().toLowerCase();
+ if (key == null || key.isEmpty) return null;
+ final matching = rows.where((row) => row['engine'] == key);
+ return matching.where((row) => row['remainingPercent'] != null).firstOrNull ??
+ matching.firstOrNull;
+}
+
class _Choice {
final GridModel? model;
final bool runLocalModel;
diff --git a/desktop/test/grid_model_picker_test.dart b/desktop/test/grid_model_picker_test.dart
index c30b6c14f..ed5e6cb6d 100644
--- a/desktop/test/grid_model_picker_test.dart
+++ b/desktop/test/grid_model_picker_test.dart
@@ -1144,4 +1144,57 @@ void main() {
expect(ticked(tester, 'Anthropic'), isFalse);
},
);
+
+ // ── the subscription row agrees with the window's Models menu ─────────────────────────────────
+ //
+ // The picker used to own its own usage reader, read at a different moment from the menu's, and
+ // said "Not signed in" beside a menu showing the same Anthropic account with 8% left.
+
+ testWidgets('reads the app\'s shared usage controller and leaves it alive', (
+ tester,
+ ) async {
+ build(
+ models: [
+ {'id': 'Qwen-Test', 'node': 'macbook'},
+ ],
+ );
+ final shared = notifier.modelsMenu;
+ await open(tester);
+ await tester.pumpWidget(const SizedBox());
+
+ expect(notifier.modelsMenu, same(shared));
+ // A controller the picker had disposed would throw here.
+ expect(() => shared.addListener(() {}), returnsNormally);
+ });
+
+ group('which subscription row the picker shows', () {
+ Map<String, Object?> row(String account, {double? percent}) => {
+ 'title': 'Anthropic',
+ 'engine': 'claude',
+ 'account': account,
+ 'status': percent == null ? 'Not signed in' : '$percent% remaining',
+ 'remainingPercent': percent,
+ };
+
+ test('prefers a live account over this Mac signed out', () {
+ final rows = [row(''), row('ed8a75', percent: 8)];
+ expect(subscriptionRowFor('claude', rows)?['account'], 'ed8a75');
+ });
+
+ test('falls back to the first row when none has a figure', () {
+ final rows = [row(''), row('ed8a75')];
+ expect(subscriptionRowFor('claude', rows)?['account'], '');
+ });
+
+ test('keeps the first live row when several have figures', () {
+ final rows = [row('aaaaaa', percent: 50), row('bbbbbb', percent: 8)];
+ expect(subscriptionRowFor('Claude ', rows)?['account'], 'aaaaaa');
+ });
+
+ test('says nothing for another engine or no engine', () {
+ final rows = [row('ed8a75', percent: 8)];
+ expect(subscriptionRowFor('codex', rows), isNull);
+ expect(subscriptionRowFor(null, rows), isNull);
+ });
+ });
}
diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dart
index 699e62373..d0729e487 100644
--- a/desktop/test/models_menu_test.dart
+++ b/desktop/test/models_menu_test.dart
@@ -228,7 +228,7 @@ void main() {
for (final next in [
reading(reset: instant),
reading(session: double.nan),
- reading(fetched: instant.subtract(const Duration(minutes: 3))),
+ reading(fetched: instant.subtract(const Duration(minutes: 61))),
]) {
value = next;
now = now.add(const Duration(minutes: 1));
@@ -239,6 +239,71 @@ void main() {
},
);
+ test(
+ 'an expired reading says "Checking usage…" while the next read runs',
+ () async {
+ var now = instant;
+ var answer = Completer<ProviderUsage>();
+ final source = _Source(UsageProvider.claude, () => answer.future);
+ final usage = UsageController(sources: [source], autoStart: false);
+ final menu = ModelsMenuController(usage: usage, now: () => now);
+ addTearDown(usage.dispose);
+ addTearDown(menu.dispose);
+ final first = menu.refresh();
+ answer.complete(reading());
+ await first;
+ expect(menu.rows.single['status'], '15% remaining');
+
+ now = now.add(const Duration(minutes: 61));
+ expect(menu.rows.single['status'], 'Usage unavailable');
+ answer = Completer<ProviderUsage>();
+ final second = menu.refresh();
+ expect(menu.rows.single['status'], 'Checking usage…');
+ expect(menu.rows.single['remainingPercent'], isNull);
+ answer.complete(reading(fetched: now));
+ await second;
+ expect(menu.rows.single['status'], '15% remaining');
+ },
+ );
+
+ test(
+ 'a cached figure stays for up to an hour and says how old it is',
+ () async {
+ var now = instant;
+ final source = _Source(UsageProvider.claude, () async => reading());
+ final usage = UsageController(sources: [source], autoStart: false);
+ final menu = ModelsMenuController(usage: usage, now: () => now);
+ addTearDown(usage.dispose);
+ addTearDown(menu.dispose);
+ await menu.refresh();
+ now = now.add(const Duration(minutes: 30));
+ expect(menu.rows.single['status'], '15% remaining');
+ expect(menu.rows.single['details'], contains('Read 30 min ago'));
+ },
+ );
+
+ test('a failed read keeps the last good figure', () async {
+ var fail = false;
+ final source = _Source(
+ UsageProvider.claude,
+ () async => fail
+ ? const ProviderUsage(
+ provider: UsageProvider.claude,
+ status: UsageStatus.failed,
+ )
+ : reading(),
+ );
+ final usage = UsageController(sources: [source], autoStart: false);
+ final menu = ModelsMenuController(usage: usage, now: () => instant);
+ addTearDown(usage.dispose);
+ addTearDown(menu.dispose);
+ await usage.refresh();
+ fail = true;
+ await usage.refresh();
+ expect(source.calls, 2);
+ expect(menu.rows.single['status'], '15% remaining');
+ });
+
test(
'a positive fraction of remaining usage is not rounded to zero',
() async {