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
feat: add agent model sheet for mobile interface
Dev jacob5bd1eabdc406
diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dartindex 89c7e7db5..e8b94943b 100644--- a/mobile/lib/core/models.dart+++ b/mobile/lib/core/models.dart@@ -139,6 +139,13 @@ class Agent {/// the agent is on its engine's own login or the engine chose.final String? gridModel;+ /// Whether the agent can search the web on that model, or null when the+ /// daemon said nothing — an agent on its own login, an older daemon, or a+ /// grid agent it merely discovered. Decided by the daemon when it built the+ /// launch and carried on every frame, so it is right after a reconnect or a+ /// restart without anything being replayed.+ final GridWebSearch? gridWebSearch;+/// The runtime profile's model for this session (`gpt-5-codex`, `opus`), null/// when the daemon has none to report.final String? selectedModel;@@ -166,6 +173,7 @@ class Agent {this.engineIconHint,this.codexHome,this.gridModel,+ this.gridWebSearch,this.selectedModel,this.dshName,this.parentAgentId,@@ -214,6 +222,9 @@ class Agent {engineIconHint: _safeLabel(j['engineIconHint']),codexHome: j['engine'] == 'codex' ? _safeCodexHome(j['codexHome']) : null,gridModel: grid is Map ? _safeLabel(grid['model']) : null,+ gridWebSearch: grid is Map+ ? GridWebSearch.fromWire(grid['webSearch'])+ : null,selectedModel: _safeLabel(j['selectedModel']),dshName: _safeLabel(j['dshName']),parentAgentId: _safeLabel(j['parentAgentId'] ?? j['parentId']),@@ -243,6 +254,7 @@ class Agent {engineIconHint: engineIconHint,codexHome: codexHome,gridModel: gridModel,+ gridWebSearch: gridWebSearch,selectedModel: selectedModel,dshName: dshName,parentAgentId: parentAgentId,@@ -482,3 +494,162 @@ class AgentProject {);}}++/// Whether an agent on a Local model can search the web, as the daemon decided+/// when it built the launch (`grid.webSearch` on the agent frame).+///+/// Three words, each a different fact for the person reading the picker: `on`+/// needs no sentence; `unavailable` means the daemon could not obtain the+/// web-tools configuration this time (an outdated CLI, no sign-in) and moving+/// the agent again may fix it; `unsupported` means the engine cannot take the+/// tools on this machine at all (Pi has no MCP client; Hermes under a+/// system-managed install), and nothing about the model changes that.+enum GridWebSearch {+ on,+ unavailable,+ unsupported;++ /// The one sentence shown for a degraded status, or null when there is+ /// nothing to say.+ String? get sentence => switch (this) {+ GridWebSearch.on => null,+ GridWebSearch.unavailable => 'Web search unavailable',+ GridWebSearch.unsupported => 'Web search not supported by this engine',+ };++ /// The wire word, or null for anything else — an older daemon sends no field,+ /// and a newer one might send a fourth word this build should neither print+ /// verbatim nor guess at.+ static GridWebSearch? fromWire(Object? raw) => switch (raw) {+ 'on' => GridWebSearch.on,+ 'unavailable' => GridWebSearch.unavailable,+ 'unsupported' => GridWebSearch.unsupported,+ _ => null,+ };+}++/// One model a harness grid can answer right now.+class GridModel {+ /// The id an engine is pointed at, verbatim from the grid.+ final String id;++ /// Which machine serves it. Display only, and empty when the grid does not+ /// say — on a private grid this is one of the user's own computers, which is+ /// the useful part of the answer.+ final String node;++ /// The grid it is served on — the section it was listed under. Null on an+ /// older daemon that sends only the own grid's list, which the retarget then+ /// targets as it always did.+ final String? grid;++ const GridModel({required this.id, required this.node, this.grid});+}++/// Which `grid` a machine would run, as its daemon reports beside the model+/// list (`gridCli`).+///+/// `managed` is the runtime Harness itself carries and pins; `path` is one the+/// person installed (runnable, but not the pin); `missing` is nothing to run —+/// the one value that changes what the picker says, because an agent moved+/// onto a Local model there would die on its first `grid`. An older daemon+/// sends no field, read as null: nothing is claimed either way.+enum GridCli {+ managed,+ path,+ missing;++ static GridCli? parse(Object? raw) => switch (raw) {+ 'managed' => GridCli.managed,+ 'path' => GridCli.path,+ 'missing' => GridCli.missing,+ _ => null,+ };+}++/// One grid the machine is signed into, with what it serves. [own] marks the+/// account's private grid — the picker calls that one "Local models on your+/// machines"; a shared grid goes by its name.+class GridSection {+ final String name;+ final bool own;+ final List<GridModel> models;++ const GridSection({+ required this.name,+ required this.own,+ required this.models,+ });+}++/// The picker's whole answer: which grids were asked, and what they offer.+///+/// `gridName` is null when the machine has no grid yet — told apart from "a+/// grid with nothing on it", because the two need different sentences in front+/// of a person.+class GridModels {+ final String? gridName;+ final List<GridModel> models;++ /// Every grid the machine is signed into, own grid first, each with its live+ /// models — the picker's sections. Empty on an older daemon, which sends only+ /// [models] for the own grid; the picker then draws that one section.+ final List<GridSection> grids;++ /// The engines a Local model can be offered to at all, as the daemon on that+ /// machine names them (`localModelEngines`). Null when the daemon is older+ /// and sends no such list — read as "offer everything", the behaviour before.+ final Set<String>? localModelEngines;++ /// Which `grid` the machine would run — see [GridCli]. Null when the daemon+ /// is older and does not say, which claims nothing.+ final GridCli? gridCli;++ /// Did the machine ANSWER? False when the request failed — offline, timed+ /// out, or a daemon too old to know the call.+ ///+ /// Kept apart from `gridName == null` because the two mean opposite things to+ /// a person. "This account has no grid" is a fact worth acting on; "we could+ /// not ask" is not a fact about the account at all, and a UI that folds them+ /// together tells a signed-in user to sign in again.+ final bool reachable;++ const GridModels({+ required this.gridName,+ required this.models,+ this.grids = const [],+ this.localModelEngines,+ this.gridCli,+ this.reachable = true,+ });++ /// The machine could not be asked. Says nothing about the account, because+ /// nothing is known — including which engines it would have offered, or+ /// whether it has a `grid`.+ const GridModels.unreachable()+ : gridName = null,+ models = const [],+ grids = const [],+ localModelEngines = null,+ gridCli = null,+ reachable = false;++ /// The sections to draw: [grids] when the daemon sent them, else the own grid+ /// alone.+ List<GridSection> get sections => grids.isNotEmpty+ ? grids+ : [+ if (gridName != null)+ GridSection(name: gridName!, own: true, models: models),+ ];++ /// Whether [engine] may be pointed at one of [models]: unknown engines are+ /// refused only when the daemon gave a list — a picker that guessed would+ /// refuse the wrong ones on an older daemon.+ bool canRunLocally(String? engine) {+ final capable = localModelEngines;+ if (capable == null) return true;+ final id = engine?.trim().toLowerCase();+ return id != null && capable.contains(id);+ }+}diff --git a/mobile/lib/phone/agent_model_controller.dart b/mobile/lib/phone/agent_model_controller.dartnew file mode 100644index 000000000..0bbe9d1ec--- /dev/null+++ b/mobile/lib/phone/agent_model_controller.dart@@ -0,0 +1,100 @@+/// Everything the model sheet knows, kept off the widget that draws it.+library;++import 'dart:async';++import 'package:flutter/foundation.dart';++import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/core/test_run.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/usage/models_menu_controller.dart';++/// The agent as the machine last listed it, or null once it is gone.+Agent? agentOnScreen(AppNotifier notifier, String machineId, String agentId) =>+ notifier+ .stateOf(machineId)+ ?.agents+ .where((a) => a.id == agentId)+ .firstOrNull;++/// The two answers the sheet draws — where this agent could go, and what its+/// engine's own subscription has left — behind one listenable.+///+/// ⚠️ **It does not own the MOVE.** Picking closes the sheet, and this goes+/// with it; the retarget outlives both (see `applyModelChoice`). A controller+/// method would be a call into a disposed object by the time the daemon+/// answered.+class AgentModelController extends ChangeNotifier {+ AgentModelController({+ required this.notifier,+ required this.machineId,+ required this.agentId,+ }) {+ _usage.addListener(_changed);+ // The tick follows the agent: a move made from the desktop, or the one this+ // sheet just asked for, lands as an agent frame and is drawn here.+ notifier.addListener(_changed);+ // ⚠️ Not under `flutter test`: a refresh asks every connected machine over+ // the relay, and a widget test would be left holding its timers after the+ // tree was gone. A test that wants a figure drives the controller itself.+ if (!kUnderTest) unawaited(_usage.refresh().catchError((_) {}));+ unawaited(_load());+ }++ final AppNotifier notifier;+ final String machineId;+ final String agentId;++ /// The same controller the desktop's picker reads, so a percentage on the+ /// phone and one on the laptop cannot disagree. Its refresh is capped at once+ /// a minute and answers from cache in between.+ late final ModelsMenuController _usage = ModelsMenuController(+ remote: notifier.readRemoteUsage,+ );++ GridModels? _answer;+ bool _disposed = false;++ /// The agent this sheet is about, followed live.+ Agent? get agent => agentOnScreen(notifier, machineId, agentId);++ /// What the machine answered, or null while it is still being asked. A+ /// failure is an ANSWER — [GridModels.unreachable] — never a null.+ GridModels? get answer => _answer;++ /// The subscription reading for THIS agent's engine, or null when there is+ /// none to show. Absent means the row says nothing about usage, which reads+ /// as "no figure" rather than as a figure that went missing.+ Map<String, Object?>? get subscription {+ final id = agent?.engine?.trim().toLowerCase();+ if (id == null || id.isEmpty) return null;+ for (final row in _usage.rows) {+ if (row['engine'] == id) return row;+ }+ return null;+ }++ /// Asked as the sheet opens rather than held in app state: an engine can join+ /// or leave a grid between two openings, and an offer nobody is serving any+ /// more is worse than a moment's wait.+ Future<void> _load() async {+ final answer = await notifier.gridModels(machineId);+ if (_disposed) return;+ _answer = answer;+ _changed();+ }++ void _changed() {+ if (!_disposed) notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ notifier.removeListener(_changed);+ _usage.removeListener(_changed);+ _usage.dispose();+ super.dispose();+ }+}diff --git a/mobile/lib/phone/agent_model_rows.dart b/mobile/lib/phone/agent_model_rows.dartnew file mode 100644index 000000000..2ee65d2d2--- /dev/null+++ b/mobile/lib/phone/agent_model_rows.dart@@ -0,0 +1,321 @@+/// The model sheet's parts: a captioned heading, a choosable row, and a+/// sentence where a section has nothing to offer.+///+/// Kept beside the sheet rather than folded into [PhoneSheetAction], because+/// these rows carry what that one cannot: a tick for the one in force, a second+/// line under the name, and a leading engine mark instead of an icon. A row+/// there is an action; a row here is a destination, and the tick is how it says+/// which one you are already at.+library;++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/widgets/touch_target.dart';+import 'package:harness_mobile/widgets/engine_identity.dart';++/// The side inset every row and heading in the sheet shares — the same 20 the+/// rows of [showPhoneSheet] are laid out on, so the two read as one surface+/// when the model sheet opens over it.+const double kModelRowInset = 20;++/// A section's heading, with the grid's own name under it when the section is+/// somebody else's fleet.+class ModelSectionHeading extends StatelessWidget {+ const ModelSectionHeading({+ super.key,+ required this.caption,+ this.detail,+ this.first = false,+ });++ final String caption;++ /// The quieter line under [caption] — a shared grid's name. Null leaves it+ /// out.+ final String? detail;++ /// The first heading in the sheet sits tighter to the title above it; every+ /// later one opens a gap, which is what parts one section from the last.+ final bool first;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Padding(+ padding: EdgeInsets.fromLTRB(+ kModelRowInset,+ first ? 6 : 18,+ kModelRowInset,+ 6,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ caption.toUpperCase(),+ style: TextStyle(+ color: AppPalette.textFaint,+ fontSize: 11.5,+ fontWeight: FontWeight.w600,+ letterSpacing: 0.6,+ ),+ ),+ if (detail != null)+ Padding(+ padding: const EdgeInsets.only(top: 2),+ child: Text(+ detail!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: AppPalette.textSecondary,+ fontSize: 12.5,+ ),+ ),+ ),+ ],+ ),+ );+ }+}++/// One place the agent can run: a model on a grid, or the engine's own login.+///+/// ⚠️ **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+/// 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.+class ModelRow extends StatelessWidget {+ const ModelRow({+ super.key,+ required this.title,+ required this.selected,+ required this.onTap,+ this.engine,+ this.status,+ this.detail,+ this.warning,+ });++ final String title;++ /// The one the agent is on right now.+ final bool selected;++ final VoidCallback onTap;++ /// Drawn as an engine mark where there is no tick — the Subscription row's+ /// own vendor. Null leaves that space empty, which is what a grid model gets.+ final String? engine;++ /// A quiet word at the end of the row: the machine serving the model, or what+ /// is left of a subscription.+ final String? status;++ /// A quiet second line under [title] — which account the subscription row is+ /// reading.+ final String? detail;++ /// A second line that is a WARNING rather than a detail: the web-search+ /// sentence on the model the agent is actually running.+ ///+ /// Its own field rather than a colour passed in beside [detail], because the+ /// two are different kinds of line and only one of them should ever be able+ /// to wear the warning colour.+ final String? warning;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final status = this.status;+ return InkWell(+ onTap: onTap,+ // `Ink` rather than a coloured `Container`: a fill painted inside the+ // InkWell would cover the ink the tap splashes onto the Material.+ child: Ink(+ color: selected ? AppSurface.accentWash : null,+ child: Container(+ // A row is read as a line of type, but it is pressed with a thumb —+ // so the type sets the padding and [minTouchTarget] sets the floor+ // under it, rather than a padding chosen to reach 44 that would leave+ // the one-line rows looser than every other list on the phone.+ constraints: const BoxConstraints(minHeight: minTouchTarget),+ alignment: Alignment.centerLeft,+ padding: const EdgeInsets.symmetric(+ horizontal: kModelRowInset,+ vertical: 10,+ ),+ child: Row(+ children: [+ SizedBox.square(dimension: 22, child: Center(child: _leading())),+ const SizedBox(width: 14),+ Expanded(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: AppPalette.textPrimary,+ fontSize: 15.5,+ fontWeight: selected+ ? FontWeight.w600+ : FontWeight.w500,+ ),+ ),+ if (detail != null) _second(detail!, AppPalette.textFaint),+ if (warning != null) _second(warning!, AppPalette.warn),+ ],+ ),+ ),+ if (status != null && status.isNotEmpty) ...[+ const SizedBox(width: 12),+ ConstrainedBox(+ // A long node name gives way to the model's own name, which+ // is what the row is for.+ constraints: const BoxConstraints(maxWidth: 132),+ child: Text(+ status,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.end,+ style: TextStyle(color: AppPalette.textFaint, fontSize: 13),+ ),+ ),+ ],+ ],+ ),+ ),+ ),+ );+ }++ /// One of the lines under [title]: a detail, or a warning.+ Widget _second(String text, Color color) => Padding(+ padding: const EdgeInsets.only(top: 2),+ child: Text(+ text,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(color: color, fontSize: 12.5),+ ),+ );++ Widget _leading() {+ if (selected) {+ return Icon(+ LucideIcons.check300,+ size: 18,+ color: AppPalette.accentOnSurface,+ );+ }+ final engine = this.engine;+ if (engine == null) return const SizedBox.shrink();+ return EngineMark(engine: engine, size: 18);+ }+}++/// What a section says instead of rows: it could not be asked, the machine has+/// no `grid`, or the account is serving nothing yet.+class ModelSectionNote extends StatelessWidget {+ const ModelSectionNote(this.sentence, {super.key});++ final String sentence;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Padding(+ padding: const EdgeInsets.fromLTRB(kModelRowInset, 2, kModelRowInset, 10),+ child: Text(+ sentence,+ style: TextStyle(color: AppPalette.textSecondary, fontSize: 13.5),+ ),+ );+ }+}++/// The sheet's own title: what is being chosen, and for whom.+class ModelSheetTitle extends StatelessWidget {+ const ModelSheetTitle({super.key, required this.agentName});++ /// Null while the agent is still loading, or once it is gone.+ final String? agentName;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Padding(+ padding: const EdgeInsets.fromLTRB(kModelRowInset, 0, kModelRowInset, 4),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'Model',+ style: TextStyle(+ color: AppPalette.textPrimary,+ fontSize: 15,+ fontWeight: FontWeight.w600,+ ),+ ),+ Text(+ agentName == null+ ? 'Where this agent runs'+ : 'Where $agentName runs',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(color: AppPalette.textSecondary, fontSize: 13),+ ),+ ],+ ),+ );+ }+}++/// What stands where the grids will be while the machine is being asked.+///+/// A heading over the wait rather than a bare spinner: the heading is where the+/// rows are about to appear, so nothing moves when they do.+class ModelSheetWaiting extends StatelessWidget {+ const ModelSheetWaiting({super.key});++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const ModelSectionHeading(caption: 'Local models on your machines'),+ Padding(+ padding: const EdgeInsets.fromLTRB(kModelRowInset, 4, 0, 12),+ child: Row(+ children: [+ const SizedBox.square(+ dimension: 14,+ child: CircularProgressIndicator(strokeWidth: 1.6),+ ),+ const SizedBox(width: 12),+ Text(+ 'Asking this machine…',+ style: TextStyle(+ color: AppPalette.textSecondary,+ fontSize: 13.5,+ ),+ ),+ ],+ ),+ ),+ ],+ );+ }+}diff --git a/mobile/lib/phone/agent_model_sections.dart b/mobile/lib/phone/agent_model_sections.dartnew file mode 100644index 000000000..ad9a1a01b--- /dev/null+++ b/mobile/lib/phone/agent_model_sections.dart@@ -0,0 +1,90 @@+/// What the model sheet draws, decided away from any widget so the shape of the+/// answer can be read — and tested — without pumping a sheet.+///+/// The desktop's `grid_model_picker.dart` makes the same three decisions inline+/// in its menu builder. They are pulled out here because a phone sheet rebuilds+/// on every refresh that lands under it, and a rule buried in a builder is one+/// nothing can assert on.+library;++import 'package:harness_mobile/core/models.dart';++/// The engines whose agents are OFFERED the switch.+///+/// Named here rather than derived from the daemon's `localModelEngines`,+/// because the two answer different questions. That list is which engines a+/// Local model *can* be handed to — a launch contract exists for seven of them.+/// This is the narrower question of which ones a person is offered the switch+/// on, and it is the three whose switching has been driven end to end: Claude+/// Code and Codex move by environment, and OpenCode by a config file plus its+/// own `/models` picker.+///+/// The rest keep the model they have. A row that looks like a choice and may+/// not be one costs an agent answering on a model nobody asked for.+const Set<String> kModelSheetEngines = {'claude', 'codex', 'opencode'};++/// Whether [engine] gets the sheet at all. Unknown or absent is NO — a menu+/// offers nothing it cannot back.+bool modelSheetSupports(String? engine) =>+ kModelSheetEngines.contains(engine?.trim().toLowerCase());++/// The sections worth a heading: the own grid always (so its empty-state+/// sentence has a place to be), and a shared grid only while it serves+/// something.+///+/// A team grid with nothing running is not a choice this sheet can offer, and a+/// heading over "nothing here" is a line to read for no gain — the sheet is for+/// picking a model, not for surveying grids.+List<GridSection> modelSheetSections(GridModels answer) {+ final sections = answer.sections+ .where((s) => s.own || s.models.isNotEmpty)+ .toList();+ if (sections.any((s) => s.own)) return sections;+ return [+ GridSection(name: answer.gridName ?? '', own: true, models: answer.models),+ ...sections,+ ];+}++/// What a section with nothing in it says, or null when it says nothing.+///+/// Three situations, three sentences, because they send a person to three+/// different places. Folding them together is what once put "sign in again" in+/// front of a signed-in user whose daemon happened to be offline — advice that+/// was wrong, and that would not have helped even if the diagnosis had been+/// right.+///+/// A shared grid is never drawn empty (see [modelSheetSections]), so the last+/// branch only ever fires for the own grid.+String? modelSheetEmptySentence(GridModels answer, GridSection section) {+ if (!answer.reachable) return 'Could not reach this machine.';+ // The machine's gap before the account's: with no `grid` on that computer+ // there is nothing a sign-in could set up there, and the feature's name is+ // the only word for it a person knows.+ if (answer.gridCli == GridCli.missing) {+ return "Harness Compute isn't installed on this machine.";+ }+ // ⚠️ **It names the desktop, where the desktop's own picker offers a button.**+ // That button opens Grid — the harness that serves models on a machine — as a+ // new agent, which needs the Store, and the phone has none: no `probeDsh`, no+ // `openStore`, and `createAgent` here cannot name a harness. A door that is+ // not there must not be drawn, but the answer to an empty section still has+ // to be somewhere, so the sentence carries it.+ if (section.own) {+ return 'No local models on this account yet. Grid, on your computer, is '+ 'where models are started.';+ }+ return null;+}++/// The heading over a section, and the quieter line under it.+///+/// Own: one plain sentence, nothing under it — "your machines" is the second+/// half of the same fact and reads oddly split onto its own clause. Shared: the+/// general fact as the heading, the specific grid as the name under it. The two+/// are different kinds of information — why the rows are here, versus which+/// fleet they are — not one sentence.+({String caption, String? detail}) modelSheetHeading(GridSection section) =>+ section.own+ ? (caption: 'Local models on your machines', detail: null)+ : (caption: 'Models shared with you', detail: section.name);diff --git a/mobile/lib/phone/agent_model_sheet.dart b/mobile/lib/phone/agent_model_sheet.dartnew file mode 100644index 000000000..005f77a2e--- /dev/null+++ b/mobile/lib/phone/agent_model_sheet.dart@@ -0,0 +1,256 @@+/// Where one agent runs, chosen from the phone: its engine's own login, or a+/// model on a grid the machine it runs on is signed into.+///+/// ⚠️ **A sheet, not a menu.** The desktop hangs this off the pane header, a+/// control a mouse can reach without leaving the terminal. A phone header has+/// room for the agent's name and `⋯`, so this comes up from the bottom edge+/// like every other list a thumb reaches into here — and it is opened from the+/// `⋯` sheet, which is where this app puts everything the desktop reaches by+/// right-clicking a pane.+///+/// ⚠️ **Picking re-execs the agent's process.** That is why it is a tap in a+/// sheet rather than anything a swipe could do by accident, and why picking+/// what is already picked does nothing at all.+///+/// ⚠️ **No "Open Grid" button, unlike the desktop's picker.** That button opens+/// the Grid harness as a new agent, which needs the Store — `probeDsh`,+/// `openStore`, and a `createAgent` that can name a harness. The phone has none+/// of the three. The sentence under an empty Local section says where to go+/// instead (see [modelSheetEmptySentence]); a button that cannot open anything+/// would be worse than the sentence.+library;++import 'dart:async';++import 'package:flutter/material.dart';++import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/widgets/engine_identity.dart';++import 'agent_model_controller.dart';+import 'agent_model_rows.dart';+import 'agent_model_sections.dart';++/// Open the sheet for one agent. Nothing moves until something is tapped; the+/// list is asked for as the sheet opens.+Future<void> showAgentModelSheet(+ BuildContext context,+ AppNotifier notifier, {+ required String machineId,+ required String agentId,+}) {+ // Taken before the sheet opens, because a refusal lands after it has closed+ // and the sheet's own context is gone by then.+ final messenger = ScaffoldMessenger.maybeOf(context);+ return showModalBottomSheet<void>(+ context: context,+ useRootNavigator: true,+ showDragHandle: true,+ backgroundColor: AppPalette.panelBg,+ // A grid serving a dozen models outgrows Flutter's 9/16 default, which is+ // not a height anything here asked for. The ceiling is [showPhoneSheet]'s,+ // so the sheet this one opens from and this one stand the same way.+ isScrollControlled: true,+ constraints: BoxConstraints(+ maxHeight: MediaQuery.sizeOf(context).height * 0.85,+ ),+ builder: (sheetContext) => _AgentModelSheet(+ notifier: notifier,+ machineId: machineId,+ agentId: agentId,+ // Close first, then act: the snackbar a refusal lands in must not arrive+ // underneath a sheet that is still animating out — the same order every+ // row in [showPhoneSheet] takes.+ onPick: (model) {+ Navigator.of(sheetContext).pop();+ unawaited(+ applyModelChoice(+ notifier,+ machineId: machineId,+ agentId: agentId,+ model: model,+ messenger: messenger,+ ),+ );+ },+ ),+ );+}++/// Move the agent, unless it is already there.+///+/// ⚠️ **Picking what is already picked is a no-op, and that is a rule rather+/// than a nicety.** A retarget re-execs the pane's process; a tap on the row+/// already wearing the tick would throw away the agent's live process to put it+/// back exactly where it was.+///+/// ⚠️ **A free function, not a method on [AgentModelController].** The sheet is+/// closed before this is called, so the controller is disposed by the time the+/// daemon answers.+///+/// A refusal is a sentence, not a code — the daemon decides these before it+/// touches the pane, so the terminal never says why. The phone has no error+/// rail, so it lands in the one surface a pushed page always has.+Future<void> applyModelChoice(+ AppNotifier notifier, {+ required String machineId,+ required String agentId,+ required GridModel? model,+ ScaffoldMessengerState? messenger,+}) async {+ if (model?.id == agentOnScreen(notifier, machineId, agentId)?.gridModel) {+ return;+ }+ final error = model == null+ ? await notifier.clearAgentGrid(machineId, agentId)+ : await notifier.retargetAgentToGridModel(+ machineId,+ agentId,+ model.id,+ gridName: model.grid,+ );+ if (error != null) messenger?.showSnackBar(SnackBar(content: Text(error)));+}++class _AgentModelSheet extends StatefulWidget {+ const _AgentModelSheet({+ required this.notifier,+ required this.machineId,+ required this.agentId,+ required this.onPick,+ });++ final AppNotifier notifier;+ final String machineId;+ final String agentId;++ /// The chosen grid model, or null for the engine's own login.+ final ValueChanged<GridModel?> onPick;++ @override+ State<_AgentModelSheet> createState() => _AgentModelSheetState();+}++class _AgentModelSheetState extends State<_AgentModelSheet> {+ late final AgentModelController _models = AgentModelController(+ notifier: widget.notifier,+ machineId: widget.machineId,+ agentId: widget.agentId,+ );++ @override+ void dispose() {+ _models.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return SafeArea(+ child: ListenableBuilder(+ listenable: _models,+ builder: (context, _) => Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ ModelSheetTitle(agentName: _models.agent?.name),+ Flexible(+ child: ListView(+ shrinkWrap: true,+ padding: const EdgeInsets.only(bottom: 8),+ children: [+ const ModelSectionHeading(+ caption: 'Subscription',+ first: true,+ ),+ _subscriptionRow(),+ ..._gridRows(),+ ],+ ),+ ),+ ],+ ),+ ),+ );+ }++ /// The engine's own login, offered FIRST and always.+ ///+ /// A sheet that can only move an agent ONTO a grid is a one-way door, and the+ /// way back must not be something you have to know a command for.+ Widget _subscriptionRow() {+ final agent = _models.agent;+ final reading = _models.subscription;+ return ModelRow(+ title:+ (reading?['title'] as String?) ??+ engineIdentity(+ agent?.engine,+ displayName: agent?.engineDisplayName,+ ).label,+ engine: agent?.engine,+ selected: agent?.gridModel == null,+ status: reading?['status'] as String?,+ detail: _nonEmpty(reading?['account'] as String?),+ onTap: () => widget.onPick(null),+ );+ }++ /// Every grid section, or the one line that stands in for all of them.+ List<Widget> _gridRows() {+ final answer = _models.answer;+ if (answer == null) return const [ModelSheetWaiting()];+ final agent = _models.agent;+ // An engine with no way onto a Local model (Cursor talks only to its own+ // API; the daemon refuses the move) is told so once, instead of being+ // offered rows whose tap would do nothing. The daemon names the capable+ // engines beside the list; an older one names none, and then every row is+ // offered as before.+ if (!answer.canRunLocally(agent?.engine)) {+ return [+ const ModelSectionHeading(caption: 'Local models on your machines'),+ ModelSectionNote(+ '${engineIdentity(agent?.engine).label} can only run on its '+ 'own login.',+ ),+ ];+ }+ return [+ for (final section in modelSheetSections(answer))+ ..._section(answer, section, agent),+ ];+ }++ /// One grid: its heading, then its models — or the sentence that says why it+ /// has none.+ List<Widget> _section(GridModels answer, GridSection section, Agent? agent) {+ final heading = modelSheetHeading(section);+ final empty = section.models.isEmpty+ ? modelSheetEmptySentence(answer, section)+ : null;+ return [+ ModelSectionHeading(caption: heading.caption, detail: heading.detail),+ if (empty != null) ModelSectionNote(empty),+ for (final model in section.models)+ ModelRow(+ title: model.id,+ selected: agent?.gridModel == model.id,+ // Which machine answers it — on the own grid, one of the user's own+ // computers, which is the useful part of the answer.+ status: _nonEmpty(model.node),+ // The web-search status is about THIS agent's launch; the other rows+ // are places it could go, about which nothing is known.+ warning: agent?.gridModel == model.id+ ? agent?.gridWebSearch?.sentence+ : null,+ onTap: () => widget.onPick(model),+ ),+ ];+ }+}++String? _nonEmpty(String? value) =>+ value == null || value.isEmpty ? null : value;diff --git a/mobile/lib/phone/phone_sheet.dart b/mobile/lib/phone/phone_sheet.dartindex a03e20f55..6799726e7 100644--- a/mobile/lib/phone/phone_sheet.dart+++ b/mobile/lib/phone/phone_sheet.dart@@ -280,11 +280,21 @@ class _SheetRow extends StatelessWidget {),if (value != null) ...[const SizedBox(width: 12),- Text(- value,- style: TextStyle(- color: action.valueColor ?? AppPalette.textFaint,- fontSize: 13,+ // Capped rather than left to its own width: a value can be as+ // long as a model id, and a Row lays a non-flex child out before+ // it gives the label what is left — so an uncapped one would eat+ // the label first and then run off the end of the sheet.+ ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 150),+ child: Text(+ value,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.end,+ style: TextStyle(+ color: action.valueColor ?? AppPalette.textFaint,+ fontSize: 13,+ ),),),],diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dartindex b77a20eea..0a20f3c75 100644--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@ -7,7 +7,7 @@ import 'package:flutter/services.dart';import 'package:image_picker/image_picker.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness_mobile/core/models.dart' show AgentProject;+import 'package:harness_mobile/core/models.dart' show Agent, AgentProject;import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/shared/widgets/app_icon_button.dart';import 'package:harness_mobile/shared/widgets/skeleton.dart';@@ -17,9 +17,13 @@ import 'package:harness_mobile/terminal/terminal_font_store.dart';import 'package:harness_mobile/terminal/terminal_theme.dart';import 'package:harness_mobile/terminal/terminal_theme_store.dart';import 'package:harness_mobile/terminal/terminal_session.dart';+import 'package:harness_mobile/widgets/engine_identity.dart'+ show engineIdentity;import 'package:harness_mobile/widgets/rename_agent_dialog.dart';import 'package:harness_mobile/widgets/terminal_panel.dart';+import 'agent_model_sections.dart';+import 'agent_model_sheet.dart';import 'agents_list_page.dart';import 'agents_page.dart' show openNewAgent;import 'delete_agent.dart';@@ -1250,8 +1254,7 @@ class _TerminalPageState extends State<TerminalPage>onPressed: () => _showActions(machineName:machine?.machine.displayName ?? '',- agentName: agent.name,- project: agent.project,+ agent: agent,),),],@@ -1351,26 +1354,23 @@ class _TerminalPageState extends State<TerminalPage>});}- void _showActions({- required String machineName,- required String agentName,- AgentProject? project,- }) {+ void _showActions({required String machineName, required Agent agent}) {+ final agentName = agent.name;showPhoneSheet(context,title: '$agentName · $machineName',// The agent, then where it runs — machine, folder with its parent, branch — one line each// behind its icon. The header has no room for the path.titleParts: [agentName],- titleDetail: AgentPlaceLines(machineName: machineName, project: project),+ titleDetail: AgentPlaceLines(+ machineName: machineName,+ project: agent.project,+ ),// Two groups: what acts on THIS agent, and the screens the app itself has. Each of those is a// door rather than a list of its own — the lists belong on the pages behind them, where they// have room for every row and do not push the rest of this sheet down.sections: [- PhoneSheetSection(- caption: 'Agent',- actions: [..._agentActions(agentName)],- ),+ PhoneSheetSection(caption: 'Agent', actions: [..._agentActions(agent)]),PhoneSheetSection(caption: 'App',actions: [@@ -1409,7 +1409,35 @@ class _TerminalPageState extends State<TerminalPage>);}- List<PhoneSheetAction> _agentActions(String agentName) => [+ List<PhoneSheetAction> _agentActions(Agent agent) => [+ // Where this agent runs, above the actions that act ON it: the desktop+ // keeps it in the pane header, and this sheet is the phone's pane header.+ //+ // Offered only on the engines whose switching has been driven end to end+ // (see [modelSheetSupports]) — a row that looks like a choice and may not+ // be one costs an agent answering on a model nobody asked for.+ if (modelSheetSupports(agent.engine))+ PhoneSheetAction(+ icon: LucideIcons.cpu300,+ label: 'Model',+ // The model the agent is on now, so the sheet is worth opening only+ // when somebody means to change it. A grid model is named; its own+ // login is the engine's name, which is the word the sheet uses too.+ value:+ agent.gridModel ??+ engineIdentity(+ agent.engine,+ displayName: agent.engineDisplayName,+ ).label,+ onTap: () => unawaited(+ showAgentModelSheet(+ context,+ widget.notifier,+ machineId: widget.machineId,+ agentId: widget.agentId,+ ),+ ),+ ),PhoneSheetAction(icon: LucideIcons.pencil300,label: 'Rename agent…',@@ -1418,7 +1446,7 @@ class _TerminalPageState extends State<TerminalPage>widget.notifier,widget.machineId,widget.agentId,- agentName,+ agent.name,),),PhoneSheetAction(@@ -1444,7 +1472,7 @@ class _TerminalPageState extends State<TerminalPage>widget.notifier,widget.machineId,widget.agentId,- agentName,+ agent.name,),),),diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 508ac0ad6..c151fc7d7 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -35,8 +35,9 @@ import '../settings/config_store.dart';import '../stats/harness_stats.dart';import '../terminal/terminal_session.dart';import '../terminal/remote_media_download.dart';-import '../widgets/engine_identity.dart' show allEngines;+import '../widgets/engine_identity.dart' show allEngines, engineIdentity;import 'dial_status.dart';+import 'retarget_refusal.dart';import 'pane_layout_store.dart';import 'session_preview.dart';import 'terminal_pane.dart';@@ -4993,6 +4994,130 @@ class AppNotifier extends ChangeNotifier {return RestartAgentResult(resumed: resumed is bool ? resumed : true);}+ /// Live models on every harness grid this machine is signed into, for the+ /// model sheet.+ ///+ /// Asked of the machine the agent runs on rather than kept in app state: the+ /// answer is whatever that machine's `grid` reports at this moment (an engine+ /// can join or leave between two opens), and a cached list would offer a+ /// model nobody is serving any more.+ ///+ /// Never throws — a machine whose daemon is too old to know the RPC, one with+ /// no grid, and one that timed out are all "nothing to offer", which is what+ /// the sheet shows.+ Future<GridModels> gridModels(String machineId) async {+ try {+ final response = await _conn(machineId)+ .request('grid_models_list', timeout: const Duration(seconds: 12));+ List<GridModel> parseModels(Object? raw, {String? grid}) =>+ (raw as List<dynamic>? ?? [])+ .whereType<Map<String, dynamic>>()+ .map(+ (m) => GridModel(+ id: (m['id'] as String?) ?? '',+ node: (m['node'] as String?) ?? '',+ grid: grid,+ ),+ )+ .where((m) => m.id.isNotEmpty)+ .toList();+ final capable = response['localModelEngines'];+ return GridModels(+ gridName: response['gridName'] as String?,+ // The own grid's list, which an older daemon sends on its own.+ models: parseModels(response['models']),+ grids: (response['grids'] as List<dynamic>? ?? [])+ .whereType<Map<String, dynamic>>()+ .where((g) => (g['name'] as String?)?.isNotEmpty == true)+ .map(+ (g) => GridSection(+ name: g['name'] as String,+ own: g['own'] == true,+ models: parseModels(g['models'], grid: g['name'] as String),+ ),+ )+ .toList(),+ localModelEngines: capable is List+ ? capable.whereType<String>().map((e) => e.toLowerCase()).toSet()+ : null,+ gridCli: GridCli.parse(response['gridCli']),+ );+ } catch (_) {+ // NOT `gridName: null` with an empty list — that is the shape of "this+ // account has no grid", and a caller cannot tell it from "the machine did+ // not answer". A signed-in user whose daemon was offline would be told to+ // sign in again, which is both wrong and unactionable.+ return const GridModels.unreachable();+ }+ }++ /// Point one agent at a model on a harness grid. Returns null on success, or+ /// the one sentence to show — the phone has no error rail, so the caller+ /// snackbars it (see [retargetRefusalMessage]).+ ///+ /// Sends the model id and nothing else: the daemon on that machine resolves+ /// the endpoint and the credential from its own signed-in `grid`, so neither+ /// travels over the relay and the phone never holds a grid key. Moving an+ /// agent re-execs its pane, which is why this is an explicit choice in a+ /// sheet rather than something a swipe can do.+ ///+ /// [gridName] is the grid the model was picked from — a shared grid's section+ /// in the sheet. Absent, the daemon uses the account's own grid.+ Future<String?> retargetAgentToGridModel(+ String machineId,+ String agentId,+ String modelId, {+ String? gridName,+ }) => _retarget(machineId, agentId, {+ 'agentId': agentId,+ 'gridModel': modelId,+ 'gridName': ?gridName,+ });++ /// Put the agent back on its engine's own vendor login.+ Future<String?> clearAgentGrid(String machineId, String agentId) =>+ _retarget(machineId, agentId, {'agentId': agentId, 'clearGrid': true});++ /// The one `agent_retarget` call both doors take.+ ///+ /// A refusal happens BEFORE the daemon touches the pane — an engine with no+ /// way onto a Local model, a busy agent, a machine that cannot resolve its+ /// models — so nothing in the terminal ever says why, and without this the+ /// tap simply does nothing. One sentence, in the app's own words; the+ /// daemon's own `detail` is written for its log and names the grid.+ ///+ /// A transport failure is NOT a refusal: the daemon may well have done the+ /// move, and the agent frame that follows is the truth. Nothing is said+ /// rather than a story the terminal is about to contradict.+ Future<String?> _retarget(+ String machineId,+ String agentId,+ Map<String, dynamic> payload,+ ) async {+ try {+ await _conn(machineId).request(+ 'agent_retarget',+ payload: payload,+ timeout: const Duration(seconds: 30),+ );+ return null;+ } on WsRequestFailure catch (failure) {+ return _retargetRefusal(machineId, agentId, failure.code);+ } catch (_) {+ return null;+ }+ }++ String _retargetRefusal(String machineId, String agentId, String code) {+ final agent = machineStates[machineId]?.agents+ .where((a) => a.id == agentId)+ .firstOrNull;+ return retargetRefusalMessage(+ code,+ engineLabel: engineIdentity(agent?.engine).label,+ );+ }+/// Every tile on the machine, not just the focused one: the machine is what/// went away, so a tile of the same machine sitting in another corner of the/// grid is just as dead and must say so rather than keep showing a terminaldiff --git a/mobile/lib/state/retarget_refusal.dart b/mobile/lib/state/retarget_refusal.dartnew file mode 100644index 000000000..f1ebca52e--- /dev/null+++ b/mobile/lib/state/retarget_refusal.dart@@ -0,0 +1,47 @@+/// What the app says when the daemon refuses to move an agent to another model.+///+/// One sentence per refusal, in the app's own words. The daemon's `detail` is not shown: it is+/// written for its log and names the grid, and the user's vocabulary is "Subscription" and "Local".+/// Every code the daemon's `agent_retarget` can answer with is here, and an unknown one still gets a+/// sentence rather than the code — a new refusal in a newer daemon must not surface as `SOME_CODE`.+///+/// These refusals happen BEFORE the pane is touched (an engine with no way onto a Local model, a+/// busy agent, a machine that cannot resolve its Local models), so nothing in the terminal ever+/// says why. Until this existed, picking a Local model for a Cursor agent simply did nothing.+library;++String retargetRefusalMessage(String code, {required String engineLabel}) {+ return switch (code) {+ 'GRID_ENGINE_UNSUPPORTED' =>+ '$engineLabel can only run on its own login, not a Local model.',+ 'GRID_MODEL_REQUIRED' =>+ '$engineLabel needs a model named to run on a Local model.',+ 'GRID_UNAVAILABLE' =>+ "Couldn't reach this machine's Local models. Try again in a moment.",+ 'GRID_CONFIG_FAILED' =>+ "Couldn't write $engineLabel's Local-model configuration on this machine.",+ 'GRID_CLEAR_FAILED' =>+ "Couldn't clear the Local-model settings from this agent's terminal.",+ 'TMUX_TOO_OLD_FOR_GRID' => "This machine's tmux is too old to move an agent to a Local model. Update tmux there.",+ 'TMUX_UNAVAILABLE' || 'TMUX_FAILED' =>+ "This machine's tmux did not answer. Try again in a moment.",+ // Changing model restarts the agent's process, which would cut off the+ // reply it is writing — so the daemon waits for the person, and the+ // sentence says what to do rather than naming the state ("mid-turn" read+ // as an error).+ 'AGENT_BUSY' =>+ 'This agent is still responding. Stop it or let it finish, then '+ 'choose the model again.',+ 'AGENT_NOT_FOUND' ||+ 'MISSING_AGENT_ID' => 'This agent is no longer on the machine.',+ 'NO_ACTIVE_PROCESS' || 'RETARGET_UNSUPPORTED_BACKEND' =>+ 'This agent cannot change model right now.',+ 'RESPAWN_FAILED' =>+ "$engineLabel did not start on the new model. The terminal shows what happened.",+ 'INVALID_GRID' =>+ "This machine's Local models could not be resolved. Sign in again on it.",+ 'UNSUPPORTED_ON_REMOTE' ||+ 'UNSUPPORTED' => 'Update the harness CLI on this machine to change models.',+ _ => "Couldn't change this agent's model.",+ };+}diff --git a/mobile/lib/usage/models_menu_controller.dart b/mobile/lib/usage/models_menu_controller.dartnew file mode 100644index 000000000..42fcf1d6f--- /dev/null+++ b/mobile/lib/usage/models_menu_controller.dart@@ -0,0 +1,158 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import 'package:harness_mobile/widgets/engine_identity.dart';++import 'usage_accounts.dart';+import 'usage_controller.dart';+import 'usage_window.dart';++/// Subscription readings for the model sheet's own first row. Opening the+/// sheet reads the cached snapshot immediately and refreshes at most once per+/// minute. No polling runs on startup or on a tab change.+///+/// The desktop's twin of this file backs the same row in its pane-header+/// picker — one shape, so a percentage read on the phone and the one read on+/// the laptop cannot disagree. The seam under it differs by device and not+/// here: [UsageController] on a phone reads no local credentials at all, only+/// `usage_read` over the relay, and the reason is written on that class.+class ModelsMenuController extends ChangeNotifier {+ ModelsMenuController({+ UsageController? usage,+ Future<List<MachineUsage>> Function()? remote,+ DateTime Function()? now,+ }) : _usage = usage ?? UsageController(remote: remote, autoStart: false),+ _ownsUsage = usage == null,+ _now = now ?? DateTime.now {+ _usage.addListener(_changed);+ }++ final UsageController _usage;+ final bool _ownsUsage;+ final DateTime Function() _now;+ Future<void>? _pending;+ DateTime? _lastAttempt;+ bool _failed = false;+ bool _disposed = false;++ List<Map<String, Object?>> get rows => [+ for (final account in _usage.accounts)+ _row(account, _now(), failed: _failed),+ ];++ Future<void> refresh() {+ if (_disposed) return Future.value();+ // Re-evaluate expired windows even if another request is already running.+ _changed();+ if (_pending case final pending?) return pending;+ final last = _lastAttempt;+ if (last != null && _now().difference(last) < const Duration(minutes: 1)) {+ return Future.value();+ }+ _lastAttempt = _now();+ _failed = false;+ return _pending = _refresh();+ }++ Future<void> _refresh() async {+ try {+ await _usage.refresh();+ } catch (_) {+ // A credential/source failure must never escape into a menu callback.+ // Never include a raw exception: it could contain authentication data.+ _failed = true;+ } finally {+ _pending = null;+ _changed();+ }+ }++ void _changed() {+ if (!_disposed) notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ _usage.removeListener(_changed);+ if (_ownsUsage) _usage.dispose();+ super.dispose();+ }++ static Map<String, Object?> _row(+ UsageAccount account,+ DateTime now, {+ required bool failed,+ }) {+ final reading = account.reading;+ final provider = switch (reading.provider) {+ UsageProvider.claude => 'Anthropic',+ UsageProvider.codex => 'OpenAI',+ };+ final windows = reading.windows;+ final expired =+ (reading.fetchedAt != null &&+ now.difference(reading.fetchedAt!) > const Duration(minutes: 2)) ||+ windows.any((w) => w.resetsAt != null && !w.resetsAt!.isAfter(now));+ final valid =+ !failed &&+ !expired &&+ reading.hasFigures &&+ windows.every((w) => w.usedPercent.isFinite);+ final String status;+ final details = <String>[];+ if (valid) {+ // Show the limit that will stop work first. Weekly-only summaries can+ // look healthy while a shorter window is already exhausted.+ final limiting = reading.tightest!;+ status = '${_remaining(limiting)} remaining';+ details.add('Limiting window: ${limiting.label}');+ for (final window in windows) {+ final reset = window.resetsInLabel(now: now);+ details.add(+ '${window.label} — ${_remaining(window)} remaining'+ '${reset == null ? '' : ' · resets in $reset'}',+ );+ }+ } else {+ status = failed || expired+ ? 'Usage unavailable'+ : switch (reading.status) {+ UsageStatus.loading => 'Checking usage…',+ UsageStatus.signedOut => 'Not signed in',+ _ => 'Usage unavailable',+ };+ details.add(+ expired+ ? 'The last reading has expired. Reopen Models to refresh.'+ : reading.message ?? status,+ );+ }+ return {+ 'title': provider,+ 'account': _accountLabel(reading),+ 'status': status,+ 'details': details,+ 'engine': reading.provider.engineId,+ 'iconAsset': engineIdentity(reading.provider.engineId).asset,+ };+ }++ static String _accountLabel(ProviderUsage reading) {+ // The same opaque identity is available locally and across machines.+ // Use it consistently instead of mixing emails with fallback IDs.+ final key = reading.account;+ if (key != null && RegExp(r'^[0-9a-f]{16}$').hasMatch(key)) {+ return key.substring(0, 6);+ }+ 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()}%';+ }+}diff --git a/mobile/test/phone_model_sheet_test.dart b/mobile/test/phone_model_sheet_test.dartnew file mode 100644index 000000000..8924f0553--- /dev/null+++ b/mobile/test/phone_model_sheet_test.dart@@ -0,0 +1,367 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/agent_model_rows.dart';+import 'package:harness_mobile/phone/agent_model_sections.dart';+import 'package:harness_mobile/phone/agent_model_sheet.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/ws/ws_conn.dart';++import 'agent_pager_fixture.dart';++/// Moving one agent onto a model, and back off it.+///+/// ⚠️ **The assertion is what reached the machine.** A retarget re-execs the+/// agent's process, so what this feature is FOR is the `agent_retarget` frame+/// and its payload — the rows above it are how a person names one.+void main() {+ /// A machine answering `grid_models_list`, remembering every request, and+ /// refusing the retarget when [refusal] is set.+ ///+ /// The refusal is thrown rather than returned, which is what [WsConn] does+ /// with a reply carrying `error` — see its `_dispatch`.+ GridConn conn({Map<String, dynamic>? models, String? refusal}) =>+ GridConn(models: models ?? _grids, refusal: refusal);++ /// The pager fixture's app, with `a` running on [gridModel] (null = its own+ /// Claude login) and [engine].+ AppNotifier app(+ GridConn connection, {+ String? gridModel,+ String engine = 'claude',+ GridWebSearch? webSearch,+ }) {+ final notifier = pagerApp(connection);+ final machine = notifier.stateOf('m')!;+ machine.agents = [+ for (final agent in machine.agents)+ if (agent.id == 'a')+ Agent(+ id: 'a',+ name: 'a',+ engine: engine,+ gridModel: gridModel,+ gridWebSearch: webSearch,+ terminalAvailable: true,+ )+ else+ agent,+ ];+ addTearDown(notifier.dispose);+ return notifier;+ }++ /// Open the sheet over a bare page — the terminal underneath is no part of+ /// what this file is about, and a page with one never settles (see+ /// [agent_pager_fixture]).+ Future<void> open(WidgetTester tester, AppNotifier notifier) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () => showAgentModelSheet(+ context,+ notifier,+ machineId: 'm',+ agentId: 'a',+ ),+ child: const Text('open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('open'));+ // The sheet's own opening animation, with the machine's answer landing+ // inside it.+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 400));+ }++ /// The payloads this phone sent for [type], in order.+ List<Map<String, dynamic>> sent(GridConn connection, String type) => [+ for (final (sentType, payload) in connection.requests)+ if (sentType == type) payload,+ ];++ /// A model's row in the open sheet.+ Finder row(String title) => find.byWidgetPredicate(+ (widget) => widget is ModelRow && widget.title == title,+ );++ testWidgets(+ 'the sheet lists the subscription, the own grid and a shared one',+ (tester) async {+ await open(tester, app(conn()));++ expect(find.text('SUBSCRIPTION'), findsOne);+ // No usage read runs under test, so the row falls back to the engine's own+ // name — which is the word the sheet uses for "its own login" anyway.+ expect(row('Claude'), findsOne);++ expect(find.text('LOCAL MODELS ON YOUR MACHINES'), findsOne);+ expect(row('qwen3-coder'), findsOne);+ // Which of the user's own computers is answering it.+ expect(find.text('mac-mini'), findsOne);++ expect(find.text('MODELS SHARED WITH YOU'), findsOne);+ expect(find.text('autonomous.ai'), findsOne);+ expect(row('DeepSeek-V4-Flash'), findsOne);+ },+ );++ testWidgets('the agent is on its own login until a model is picked', (+ tester,+ ) async {+ await open(tester, app(conn()));++ expect(tester.widget<ModelRow>(row('Claude')).selected, isTrue);+ expect(tester.widget<ModelRow>(row('qwen3-coder')).selected, isFalse);+ });++ testWidgets('picking a shared grid\'s model names the grid it came from', (+ tester,+ ) async {+ final connection = conn();+ await open(tester, app(connection));++ await tester.tap(row('DeepSeek-V4-Flash'));+ await tester.pump();++ expect(sent(connection, 'agent_retarget'), [+ {+ 'agentId': 'a',+ 'gridModel': 'DeepSeek-V4-Flash',+ // Without this the daemon would resolve the id against the account's+ // OWN grid, which does not serve it.+ 'gridName': 'autonomous.ai',+ },+ ]);+ });++ testWidgets('picking the subscription takes the agent back off the grid', (+ tester,+ ) async {+ final connection = conn();+ await open(tester, app(connection, gridModel: 'qwen3-coder'));++ expect(tester.widget<ModelRow>(row('qwen3-coder')).selected, isTrue);+ await tester.tap(row('Claude'));+ await tester.pump();++ expect(sent(connection, 'agent_retarget'), [+ {'agentId': 'a', 'clearGrid': true},+ ]);+ });++ testWidgets('picking the model already in force changes nothing', (+ tester,+ ) async {+ final connection = conn();+ await open(tester, app(connection, gridModel: 'qwen3-coder'));++ await tester.tap(row('qwen3-coder'));+ await tester.pump();++ // A retarget re-execs the agent's process — a tap on the row already+ // wearing the tick must not throw a live process away to put it back.+ expect(sent(connection, 'agent_retarget'), isEmpty);+ });++ testWidgets('a refused move says why, in the app\'s own words', (+ tester,+ ) async {+ final connection = conn(refusal: 'AGENT_BUSY');+ await open(tester, app(connection));++ await tester.tap(row('qwen3-coder'));+ // The sheet closing, then the refusal landing in the page behind it.+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 400));++ expect(+ find.textContaining('This agent is still responding'),+ findsOne,+ reason:+ 'the daemon refuses before it touches the pane, so the terminal '+ 'never says why',+ );+ });++ testWidgets('an engine with no way onto a local model is told so', (+ tester,+ ) async {+ // The daemon names the capable engines beside the list; Cursor talks only+ // to its own API and is not among them.+ await open(tester, app(conn(), engine: 'cursor'));++ expect(find.text('Cursor can only run on its own login.'), findsOne);+ expect(row('qwen3-coder'), findsNothing);+ });++ testWidgets('a machine that did not answer is not an account with no grid', (+ tester,+ ) async {+ await open(tester, app(conn(models: {})));++ expect(find.text('Could not reach this machine.'), findsOne);+ });++ testWidgets('the web-search warning rides the model the agent is on', (+ tester,+ ) async {+ await open(+ tester,+ app(+ conn(),+ gridModel: 'qwen3-coder',+ webSearch: GridWebSearch.unavailable,+ ),+ );++ expect(tester.widget<ModelRow>(row('qwen3-coder')).warning, isNotNull);+ // Nothing is known about the models the agent is NOT running.+ expect(tester.widget<ModelRow>(row('DeepSeek-V4-Flash')).warning, isNull);+ });++ testWidgets('a long model id and a long node fit a phone\'s width', (+ tester,+ ) async {+ // ⚠️ At a real phone's width, not the test binding's 800×600 default: the+ // row is a Row of three parts and the names in it are as long as a GGUF's+ // filename. An overflow fails this loudly.+ tester.view.physicalSize = const Size(390, 844);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);++ await open(tester, app(conn(models: _longNames)));++ expect(row('Qwen3.6-35B-A3B-UD-Q5_K_XL-00001-of-00002'), findsOne);+ });++ group('sections', () {+ test('the own grid keeps its heading even with nothing to offer', () {+ final sections = modelSheetSections(+ const GridModels(gridName: 'mine', models: []),+ );++ expect(sections.single.own, isTrue);+ expect(+ modelSheetEmptySentence(+ const GridModels(gridName: 'mine', models: []),+ sections.single,+ ),+ startsWith('No local models on this account yet.'),+ );+ });++ test('a shared grid serving nothing is left out altogether', () {+ final answer = GridModels(+ gridName: 'mine',+ models: const [],+ grids: const [+ GridSection(name: 'mine', own: true, models: []),+ GridSection(name: 'theirs', own: false, models: []),+ ],+ );++ expect(modelSheetSections(answer).map((s) => s.name), ['mine']);+ });++ test('a machine with no grid CLI says that before anything else', () {+ const answer = GridModels(+ gridName: 'mine',+ models: [],+ gridCli: GridCli.missing,+ );++ expect(+ modelSheetEmptySentence(answer, answer.sections.single),+ "Harness Compute isn't installed on this machine.",+ );+ });++ test('only the engines whose switching was driven get the sheet', () {+ expect(modelSheetSupports('claude'), isTrue);+ expect(modelSheetSupports('CODEX'), isTrue);+ expect(modelSheetSupports('cursor'), isFalse);+ expect(modelSheetSupports(null), isFalse);+ });+ });+}++/// One own grid serving `qwen3-coder`, and one shared grid serving+/// `DeepSeek-V4-Flash`.+const _grids = <String, dynamic>{+ 'gridName': 'mine',+ 'models': [+ {'id': 'qwen3-coder', 'node': 'mac-mini'},+ ],+ 'grids': [+ {+ 'name': 'mine',+ 'own': true,+ 'models': [+ {'id': 'qwen3-coder', 'node': 'mac-mini'},+ ],+ },+ {+ 'name': 'autonomous.ai',+ 'own': false,+ 'models': [+ {'id': 'DeepSeek-V4-Flash', 'node': 'scholes-60001'},+ ],+ },+ ],+ 'localModelEngines': ['claude', 'codex', 'opencode'],+ 'gridCli': 'managed',+};++/// One grid whose model id and node are both as long as they get in the wild.+const _longNames = <String, dynamic>{+ 'gridName': 'mine',+ 'models': [+ {+ 'id': 'Qwen3.6-35B-A3B-UD-Q5_K_XL-00001-of-00002',+ 'node': 'firmware-engineer-daniel',+ },+ ],+ 'localModelEngines': ['claude'],+ 'gridCli': 'managed',+};++/// A machine that answers the model list and remembers what it was asked.+class GridConn extends PagerConn {+ GridConn({required this.models, this.refusal});++ /// The `grid_models_list` reply. Empty stands for a machine that never+ /// answered — the RPC then times out, which is what [_load] reads as+ /// unreachable.+ final Map<String, dynamic> models;++ /// The code `agent_retarget` refuses with, or null to accept the move.+ final String? refusal;++ final List<(String, Map<String, dynamic>)> requests = [];++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ requests.add((type, payload));+ if (type == 'grid_models_list') {+ if (models.isEmpty) throw WsRequestTimeout(type);+ return models;+ }+ if (type == 'agent_retarget' && refusal != null) {+ throw WsRequestFailure(+ responseType: 'agent_retarget_result',+ code: refusal!,+ );+ }+ return {};+ }+}