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.

29.4 KB
Raw Blame
import 'dart:async';

import 'package:flutter/foundation.dart';

import '../core/harness_file_store.dart';
import '../core/local_key_value_store.dart';
import '../core/models.dart';
import '../core/project_folder.dart';
import '../core/test_run.dart';
import '../state/app_state.dart';
import '../widgets/grid_model_picker.dart' show modelPickerSupports;
import '../ws/ws_conn.dart' show WsRequestFailure;
import 'local_model.dart';
import 'api_connections_controller.dart';

const modelManagerName = 'Model Manager';

/// Shared by the toolbar, panel and picker. The daemon owns downloads and
/// engines; closing a surface never cancels work or creates a conversation.
class ModelManagerController extends ChangeNotifier {
  ModelManagerController(
    this.app, {
    LocalKeyValueStore? storage,
    this.poll = true,
    this.backgroundInventory = false,
    String? targetMachineId,
  }) : _targetMachineId =
           targetMachineId ??
           (app.viewer == null
               ? null
               : app.ownedActionMachine?.machine.machineId),
       _followsBrowserChoice = targetMachineId == null && app.viewer != null,
       _storage = storage ?? (kUnderTest ? null : HarnessFileStore.shared);
  final AppNotifier app;
  final LocalKeyValueStore? _storage;
  final bool poll;

  /// Keep a remote machine's installed-model inventory warm for the footer.
  /// Uses cached inventory reads, never forced scans, downloads or Grid setup.
  final bool backgroundInventory;

  /// A remote host uses the same inventory and lifecycle RPCs, without setting
  /// up a Model Manager harness or reading another copy of the shared catalog.
  String? _targetMachineId;
  final bool _followsBrowserChoice;
  String? get targetMachineId {
    if (_targetMachineId != null || app.viewer == null) return _targetMachineId;
    return _targetMachineId = app.ownedActionMachine?.machine.machineId;
  }

  ApiConnectionsController? _apis;
  ApiConnectionsController get apis =>
      _apis ??= ApiConnectionsController(app, machineId: targetMachineId);
  static const introKey = 'models.introduction.dismissed';
  MachineState? _machine;
  Future<void>? _preparing, _opening, _refreshing;
  Timer? _timer;
  bool _started = false, _disposed = false, _preferencesLoaded = false;
  bool _introDismissed = false, _autoPrepared = false;
  AgentCreationAttempt? _creation;
  ProjectFolderRequest? _folder;
  DateTime? _lastModelsRead, _lastLocalRead;
  DateTime? _lastInventoryAttempt;
  bool _panelVisible = false;
  int _actionRevision = 0;
  /// The daemon refused this machine's models for good (a computer shared with
  /// this account): polling again every four seconds only grows the log.
  bool _guestRefused = false;
  String? _dismissedReadyId;
  GridModels? models;
  List<LocalModel> localModels = const [];

  /// The machine's RAM. On an NVIDIA machine a model runs in the card, not in this: see [fitsInVram].
  double? memoryBytes;

  /// What the catalog fits models to (`fitBytes`) — on an NVIDIA machine the VRAM its card has for
  /// models: what is free on it and what our own running model holds, which starting another frees —
  /// and that card's VRAM in all (`gpuMemoryBytes`); null when the daemon did not say.
  double? fitBytes, gpuMemoryBytes;

  /// Models run in an NVIDIA card's VRAM here (`fitMemory: vram`): the figures to show are the card's,
  /// and "fits" is judged against [fitBytes], not the machine's RAM.
  bool fitsInVram = false;

  /// The figure a heading names this machine's memory by, and what follows it: an NVIDIA card's VRAM
  /// (`VRAM`, or `VRAM for models` where only that is known), else the machine's memory
  /// (`unit` empty).
  ({double bytes, String unit})? get headingMemory => fitsInVram
      ? gpuMemoryBytes != null
            ? (bytes: gpuMemoryBytes!, unit: 'VRAM')
            : fitBytes != null
            ? (bytes: fitBytes!, unit: 'VRAM for models')
            : null
      : memoryBytes != null
      ? (bytes: memoryBytes!, unit: '')
      : null;

  /// Free space where downloads land, or null when the daemon did not say.
  double? freeDiskBytes;
  String? hardware, error, _managerError;
  bool preparing = false, opening = false, scanning = false, loaded = false;
  bool inventoryAvailable = false, operationBusy = false;
  bool supportsDownload = false;

  /// Grid is not set up on this machine yet: no `grid`, or no sign-in. Grid is an add-on, set up the
  /// first time a person asks for a grid feature ([setUpGrid]) — never by opening the app, a picker
  /// or a list. Until then the pickers offer a Set up row in place of local and shared models.
  bool gridSetupNeeded = false;

  /// [setUpGrid] is under way.
  bool settingUpGrid = false;

  /// Why the last [setUpGrid] did not finish, in the daemon's words; null once it has.
  String? gridSetupError;

  /// Set up was pressed signed out of Harness. Grid is set up with the Harness account, so the press
  /// started the sign-in and the set-up waits for it: it runs once the account's machine is back
  /// ([_observe]) — one press, not a sign-in followed by a second trip to the picker.
  bool _setUpAfterSignIn = false;

  /// [setUpGrid] is waiting for the Harness sign-in it started.
  bool get setUpWaitsForSignIn => _setUpAfterSignIn && app.signingIn;
  LocalModelOperation? pendingOperation;
  String? pendingId;
  bool pendingStart = true;
  bool pendingDownload = false;

  MachineState? get machine => targetMachineId == null
      ? app.ownedActionMachine
      : app.stateOf(targetMachineId!);
  Agent? get manager => machine?.agents
      .where((a) => a.dsh == AppNotifier.gridHarness)
      .firstOrNull;
  List<GridSection> get sections => models?.sections ?? const [];
  bool get hasOwnModels => localModels.any((model) => model.running);
  bool get busy =>
      operationBusy || pendingId != null || pendingOperation?.active == true;
  bool get showIntroduction =>
      _preferencesLoaded &&
      !_introDismissed &&
      loaded &&
      localModels.isNotEmpty &&
      !hasOwnModels &&
      !busy &&
      app.machineStates.values.any(
        (m) => m.agents.any(
          (a) =>
              a.dsh != AppNotifier.gridHarness &&
              !a.isStopped &&
              modelPickerSupports(a.engine),
        ),
      );
  LocalModel? get readyModel => localModels
      .where(
        (m) =>
            m.running &&
            m.operation?.started == true &&
            m.operation?.id != _dismissedReadyId,
      )
      .firstOrNull;
  LocalModelOperation? operationFor(LocalModel model) =>
      pendingOperation?.modelId == model.id
      ? pendingOperation
      : model.operation;

  void dismissReady() {
    _dismissedReadyId = readyModel?.operation?.id;
    _changed();
  }

  void start() {
    if (_started || _disposed) return;
    _started = true;
    app.addListener(_observe);
    app.foreground.addListener(_foregroundChanged);
    app.gridPictures.addListener(_pictureChanged);
    if (targetMachineId == null) unawaited(_loadPreferences());
    _observe();
    if (poll) {
      _timer = Timer.periodic(const Duration(seconds: 4), (_) {
        // A minimised or background app reads nothing, busy or not: the daemon owns the operation
        // either way, and the one refresh on return ([_foregroundChanged]) catches up.
        if (!app.inForeground) return;
        if (_guestRefused) return;
        if (backgroundInventory && !_panelVisible && !busy) {
          if (machine?.connectionStatus != ConnectionStatus.connected ||
              machine?.isOffline == true) {
            return;
          }
          if (_lastInventoryAttempt != null &&
              DateTime.now().difference(_lastInventoryAttempt!) <
                  const Duration(minutes: 1)) {
            return;
          }
        }
        // Grid not set up and nobody looking: nothing to watch. While a picker is open it keeps
        // reading, so grid set up some other way — a terminal's `harness grid login` — shows at
        // once instead of leaving a Set up row that is no longer true.
        if (gridSetupNeeded && !settingUpGrid && !busy && !_panelVisible) {
          return;
        }
        if (targetMachineId != null &&
            !backgroundInventory &&
            !_panelVisible &&
            !busy) {
          return;
        }
        if (busy ||
            _panelVisible ||
            _lastLocalRead == null ||
            DateTime.now().difference(_lastLocalRead!) >
                const Duration(seconds: 60)) {
          unawaited(refresh());
        }
      });
    }
  }

  Future<void> _loadPreferences() async {
    try {
      _introDismissed = await _storage?.read(introKey) == 'true';
    } catch (_) {}
    _preferencesLoaded = true;
    _changed();
  }

  void _observe() {
    if (_disposed) return;
    final current = machine;
    if (!identical(current, _machine)) {
      _machine = current;
      _autoPrepared = false;
      _creation = null;
      _folder = null;
      _preparing = null;
      _opening = null;
      _refreshing = null;
      _lastModelsRead = null;
      _lastLocalRead = null;
      _lastInventoryAttempt = null;
      preparing = false;
      opening = false;
      scanning = false;
      loaded = false;
      inventoryAvailable = false;
      supportsDownload = false;
      gridSetupNeeded = false;
      settingUpGrid = false;
      gridSetupError = null;
      operationBusy = false;
      pendingOperation = null;
      pendingId = null;
      _dismissedReadyId = null;
      _guestRefused = false;
      models = null;
      localModels = const [];
      memoryBytes = null;
      fitBytes = null;
      gpuMemoryBytes = null;
      fitsInVram = false;
      freeDiskBytes = null;
      hardware = null;
      error = null;
      _managerError = null;
    }
    if (current?.connectionStatus != ConnectionStatus.connected ||
        current?.needsLink == true ||
        (targetMachineId != null && current?.isOffline == true)) {
      inventoryAvailable = false;
    }
    if (current != null &&
        current.connectionStatus == ConnectionStatus.connected &&
        (targetMachineId != null ||
            current.agentLoadStatus == AgentLoadStatus.loaded) &&
        !_autoPrepared) {
      _autoPrepared = true;
      // The Model Manager is NOT prepared here: it is a grid feature, made ready when it is opened
      // ([open]), never by the app starting on a machine that may not use grid at all.
      // In the background the first read waits for the app to come back ([_foregroundChanged]).
      if (app.inForeground &&
          (targetMachineId == null || backgroundInventory || _panelVisible)) {
        unawaited(refresh());
      }
    }
    // Set up pressed while signed out: once the sign-in it started has landed and this machine is
    // connected on the account, the set-up it was for runs — whether the sign-in moved the app onto
    // the account's machine or left it where it was.
    if (_setUpAfterSignIn &&
        !app.isGuest &&
        !app.signingIn &&
        targetMachineId == null &&
        current != null &&
        current.connectionStatus == ConnectionStatus.connected &&
        current.agentLoadStatus == AgentLoadStatus.loaded) {
      _setUpAfterSignIn = false;
      unawaited(setUpGrid());
    }
    _changed();
  }

  /// Back in front of the person: exactly one refresh, whatever the background skipped.
  void _foregroundChanged() {
    if (_disposed || !app.inForeground) return;
    if (targetMachineId != null &&
        !backgroundInventory &&
        !_panelVisible &&
        !busy) {
      return;
    }
    final owner = machine;
    if (owner == null || owner.connectionStatus != ConnectionStatus.connected) {
      return;
    }
    unawaited(refresh());
  }

  /// Another surface's read, or the daemon's `grid_models_changed` push, changed the app's picture
  /// of this machine's grids: take it, with no read of our own.
  void _pictureChanged() {
    if (targetMachineId != null) return;
    final owner = machine;
    if (_disposed || owner == null) return;
    final picture = app.gridPictures[owner.machine.machineId];
    if (picture == null || identical(picture, models)) return;
    models = picture;
    _changed();
  }

  bool _current(MachineState owner) => !_disposed && identical(machine, owner);
  void _changed() {
    if (!_disposed) notifyListeners();
  }

  Future<void> dismissIntroduction() async {
    _introDismissed = true;
    _changed();
    try {
      await _storage?.write(introKey, 'true');
    } catch (_) {}
  }

  Future<void> prepare() {
    final owner = machine;
    return _preparing ??= _prepare().whenComplete(() {
      if (identical(machine, owner)) _preparing = null;
    });
  }

  Future<void> _prepare() async {
    final owner = machine;
    if (owner == null || manager != null) return;
    preparing = true;
    _managerError = null;
    _changed();
    try {
      final id = owner.machine.machineId;
      await app.probeDsh(id);
      if (!_current(owner)) return;
      if (owner.dsh[AppNotifier.gridHarness]?.installed != true) {
        final failure = await app.installDsh(id, AppNotifier.gridHarness);
        if (!_current(owner)) return;
        if (failure != null) {
          _managerError = failure;
          return;
        }
      }
      if (manager != null) return;
      _creation ??= AgentCreationAttempt(background: true);
      _folder ??= ProjectFolderRequest.generated(
        label: 'model-manager',
        at: DateTime.now(),
      );
      final failure = await app.createAgent(
        id,
        engine: 'codex',
        folder: null,
        projectFolder: _folder,
        dsh: AppNotifier.gridHarness,
        name: modelManagerName,
        attempt: _creation,
      );
      if (_current(owner)) _managerError = failure;
    } catch (_) {
      if (_current(owner)) {
        _managerError = 'Model Manager could not open. Try again.';
      }
    } finally {
      if (_current(owner)) {
        preparing = false;
        _changed();
      }
    }
  }

  Future<void> open() {
    final owner = machine;
    return _opening ??= _open().whenComplete(() {
      if (identical(machine, owner)) _opening = null;
    });
  }

  Future<void> _open() async {
    final owner = machine;
    if (owner == null) {
      error = 'Connect this computer to open Model Manager.';
      _changed();
      return;
    }
    opening = true;
    error = null;
    _changed();
    try {
      // Opening the Model Manager is a grid feature in use: grid is set up first, if it is not yet.
      if (gridSetupNeeded && !await setUpGrid()) {
        error =
            gridSetupError ??
            'Grid could not be set up on this computer. Try again.';
        return;
      }
      if (_creation?.agentId == null &&
          _creation?.awaitingConfirmation == false &&
          !preparing) {
        _creation = null;
      }
      await prepare();
      if (!_current(owner)) return;
      final agent = manager;
      if (agent == null) {
        error =
            _managerError ??
            'Model Manager is still starting. Try again in a moment.';
        return;
      }
      if (agent.isStopped) {
        final result = await app.resumeAgent(owner.machine.machineId, agent.id);
        if (!_current(owner)) return;
        if (result.error != null) {
          error = result.error;
          return;
        }
      }
      await _showAgent(owner, agent.id, modelManagerName);
    } catch (_) {
      if (_current(owner)) error = 'Could not open Model Manager. Try again.';
    } finally {
      if (_current(owner)) {
        opening = false;
        _changed();
      }
    }
  }

  Future<void> _showAgent(
    MachineState owner,
    String agentId,
    String title,
  ) async {
    // paneOfAgent searches only the selected tab. Opening from another session
    // must reveal the existing manager, including one still attaching.
    final tab = app.swarms
        .where(
          (swarm) => swarm.panes.any(
            (pane) =>
                pane.machineId == owner.machine.machineId &&
                pane.agentId == agentId,
          ),
        )
        .firstOrNull;
    if (tab != null) {
      app.selectSwarm(tab.id);
      await app.selectAgent(owner.machine.machineId, agentId);
      return;
    }
    app.newSwarm(name: title);
    await app.assignAgentToPane(null, owner.machine.machineId, agentId);
  }

  void setPanelVisible(bool visible) {
    if (visible &&
        !_panelVisible &&
        _followsBrowserChoice &&
        !busy &&
        !(_apis?.saving ?? false)) {
      final next = app.ownedActionMachine?.machine.machineId;
      if (next != null && next != targetMachineId) {
        _targetMachineId = next;
        _apis?.useMachine(next);
        _observe();
      }
    }
    _panelVisible = visible;
  }

  /// [local] false reads only the grid's models — what a harness can be moved onto — and not this
  /// machine's own list, which a forced read rebuilds from every app's folders (16s once [run]).
  Future<void> refresh({bool force = false, bool local = true}) {
    final owner = machine;
    return _refreshing ??= _refresh(force: force, local: local).whenComplete(
      () {
        if (identical(machine, owner)) _refreshing = null;
      },
    );
  }

  /// Sets grid up on this machine — `grid` installed, signed in with this Harness account (its token:
  /// no second browser), the account's grid made — then reads the lists it unlocks. The one door to
  /// grid for a person who has not used it: the pickers' Set up row, or opening the Model Manager.
  /// True when grid is set up afterwards.
  Future<bool> setUpGrid() async {
    if (settingUpGrid || app.signingIn) return !gridSetupNeeded;
    // Grid is set up with the Harness account, so signed out, Set up starts with signing in — the
    // app's own sign-in, in the browser — and finishes itself once that lands (see [_observe]).
    // Failing the set-up instead ("Not signed in") left a person with nowhere to go but a terminal.
    if (app.isGuest) {
      _setUpAfterSignIn = true;
      gridSetupError = null;
      _changed();
      await app.login();
      // Cancelled or refused: nothing is left waiting to set Grid up behind a later sign-in.
      if (app.isGuest) _setUpAfterSignIn = false;
      _changed();
      return false;
    }
    final owner = machine;
    if (owner == null) return !gridSetupNeeded;
    settingUpGrid = true;
    gridSetupError = null;
    _changed();
    try {
      // After any read already under way, so its stale answer cannot land over this one.
      await _refreshing;
      if (!_current(owner)) return false;
      await (_refreshing = _refresh(force: true, setup: true).whenComplete(() {
        if (identical(machine, owner)) _refreshing = null;
      }));
      return _current(owner) && !gridSetupNeeded;
    } finally {
      if (_current(owner)) {
        settingUpGrid = false;
        _changed();
      }
    }
  }

  Future<void> _refresh({
    required bool force,
    bool setup = false,
    bool local = true,
  }) async {
    // Refused for good on a computer shared with this account: nothing but a forced read (Try again)
    // asks again, so a four-second poll cannot grow the log with the same refusal.
    if (_guestRefused && !force) return;
    final owner = machine;
    if (owner == null ||
        owner.connectionStatus != ConnectionStatus.connected ||
        owner.needsLink ||
        (targetMachineId != null && owner.isOffline)) {
      inventoryAvailable = false;
      error = targetMachineId == null
          ? 'Connect this computer to see its models.'
          : 'Connect to ${owner?.machine.displayName ?? 'this machine'} to manage its models.';
      _changed();
      return;
    }
    scanning = true;
    _lastInventoryAttempt = DateTime.now();
    _changed();
    final readShared =
        force ||
        _lastModelsRead == null ||
        DateTime.now().difference(_lastModelsRead!) >
            const Duration(seconds: 20);
    await Future.wait([
      if (readShared && targetMachineId == null)
        app.refreshGridModels(owner.machine.machineId).then((answer) {
          if (_current(owner)) {
            // The panel says so when ITS read could not reach the machine ("Shared models are
            // unavailable." with Try again) — that failure is kept out of the shared picture, so no
            // other surface blanks. Answered, it shows the picture: a push that landed meanwhile is newer.
            models = answer.reachable
                ? app.gridPictures[owner.machine.machineId] ?? answer
                : answer;
            _lastModelsRead = DateTime.now();
          }
        }),
      (() async {
        if (!local) return;
        final revision = _actionRevision;
        try {
          final answer = await app.localModels(
            owner.machine.machineId,
            refresh: force,
            setup: setup,
          );
          if (!_current(owner) || revision != _actionRevision) return;
          // `notice` is a sentence BESIDE the list. A reply carrying `error` never reaches here:
          // the RPC layer fails it whole and keeps nothing, which is how a daemon that sent its
          // warning in `error` once emptied this list. `error` is still read for a daemon too old
          // to send models at all.
          //
          // Not while Grid is not set up here: then the note is only that ("Sign in to find models
          // for this computer."), which the pickers' Set up row already says — as a line on every
          // preview it read as something wrong with whatever row was selected.
          gridSetupNeeded = answer['gridSetupNeeded'] == true;
          error = gridSetupNeeded
              ? null
              : (answer['notice'] ?? answer['error']) as String?;
          if (answer['models'] is! List) {
            inventoryAvailable = false;
            error ??= 'Models are unavailable. Try again.';
            return;
          }
          localModels = (answer['models'] as List)
              .whereType<Map<String, dynamic>>()
              .map(LocalModel.fromJson)
              .where((m) => m.id.isNotEmpty)
              .toList();
          double? positive(Object? value) =>
              value is num && value.isFinite && value > 0
              ? value.toDouble()
              : null;
          memoryBytes = positive(answer['memoryBytes']);
          fitBytes = positive(answer['fitBytes']);
          gpuMemoryBytes = positive(answer['gpuMemoryBytes']);
          fitsInVram = answer['fitMemory'] == 'vram';
          final disk = answer['freeDiskBytes'];
          freeDiskBytes = disk is num && disk.isFinite && disk >= 0
              ? disk.toDouble()
              : null;
          hardware = answer['hardware'] as String?;
          operationBusy = answer['busy'] == true;
          supportsDownload = answer['supportsDownload'] == true;
          final setupError = answer['gridSetupError'];
          gridSetupError =
              setup && setupError is String && setupError.isNotEmpty
              ? setupError
              : null;
          inventoryAvailable = true;
          loaded = true;
          _lastLocalRead = DateTime.now();
          // A daemon receipt supersedes our acknowledgement, including a completed
          // operation after a dropped connection. Never replay an uncertain click.
          if (pendingOperation != null &&
              (!operationBusy ||
                  localModels.any(
                    (m) => m.operation?.id == pendingOperation?.id,
                  ))) {
            pendingOperation = null;
          }
        } on WsRequestFailure catch (failure) {
          if (_current(owner) && revision == _actionRevision) {
            inventoryAvailable = false;
            // A computer shared with this account never offers its models, and asking again will
            // not change that: say so once and stop the four-second poll.
            if (failure.code == 'GUEST_NOT_ALLOWED') {
              _guestRefused = true;
              error = 'Models are not available on a computer shared with you.';
            } else {
              error = 'Models are unavailable. Try again.';
            }
          }
        } catch (_) {
          if (_current(owner) && revision == _actionRevision) {
            inventoryAvailable = false;
            error = 'Models are unavailable. Try again.';
          }
        }
      })(),
    ]);
    if (_current(owner)) {
      scanning = false;
      _changed();
    }
  }

  /// "Show models" on a resting shared section: ask this computer's daemon to wake [sectionName]
  /// (see [AppNotifier.wakeGridModels]) and show its answer — the section starting up — at once.
  /// What follows lands through the app's picture, as every other change does.
  Future<void> wake(String sectionName) async {
    final owner = machine;
    if (owner == null || owner.connectionStatus != ConnectionStatus.connected) {
      return;
    }
    final answer = await app.wakeGridModels(
      owner.machine.machineId,
      sectionName,
    );
    if (!_current(owner) || !answer.reachable) return;
    models = app.gridPictures[owner.machine.machineId] ?? answer;
    _changed();
  }

  Future<void> toggle(LocalModel model) =>
      control(model, model.canStop ? 'stop' : 'start');

  /// Whether [model]'s download is under way here: what [cancelDownload] stops. Every other action
  /// waits while it runs, so a download that hung (its connection stalled after a full disk) once left
  /// nothing to press.
  bool downloading(LocalModel model) {
    final operation = operationFor(model);
    return operation?.active == true && operation?.stage == 'downloading';
  }

  /// [model]'s download cancelled: the daemon's stop of a model that is downloading ends the download
  /// and deletes what it downloaded, and the model can be got again.
  Future<void> cancelDownload(LocalModel model) async {
    final owner = machine;
    if (owner == null ||
        owner.connectionStatus != ConnectionStatus.connected ||
        owner.needsLink ||
        owner.machine.isShared ||
        pendingId != null ||
        !downloading(model)) {
      return;
    }
    pendingId = model.id;
    _actionRevision++;
    error = null;
    _changed();
    try {
      final answer = await app.controlLocalModel(
        owner.machine.machineId,
        model.id,
        start: false,
      );
      if (!_current(owner)) return;
      error = answer['error'] as String?;
    } catch (_) {
      if (_current(owner)) {
        error =
            'Checking the model operation. Your click will not be repeated.';
      }
    } finally {
      if (_current(owner)) {
        pendingId = null;
        _changed();
        await _refreshing;
        if (_current(owner)) await refresh();
      }
    }
  }

  /// [grid]: start or stop it on that Swarm's grid instead of the account's own (docs/plans/2026-10-23-swarm-local-models.md).
  /// Answers why the request was refused, or null. The answer is kept for the caller: the list read that follows
  /// clears [error], and a refused Run for Swarm said nothing (2026-10-26: "Free plan allows 5 networks").
  Future<String?> control(
    LocalModel model,
    String action, {
    String? grid,
  }) async {
    final owner = machine;
    if (owner == null ||
        owner.connectionStatus != ConnectionStatus.connected ||
        owner.needsLink ||
        (targetMachineId != null && owner.isOffline) ||
        owner.machine.isShared ||
        busy ||
        !inventoryAvailable) {
      return null;
    }
    final current = localModels
        .where((entry) => entry.id == model.id)
        .firstOrNull;
    if (current == null) return null;
    final download = action == 'download';
    final startModel = action == 'start';
    if (download) {
      if (!supportsDownload || current.downloaded || !current.canStart) {
        return null;
      }
    } else if (startModel) {
      if (!current.canStart) return null;
    } else if (action != 'stop' ||
        !(grid == null ? current.canStop : current.servedOn(grid))) {
      return null;
    }
    String? refused;
    pendingId = model.id;
    _actionRevision++;
    inventoryAvailable = false;
    pendingStart = startModel;
    pendingDownload = download;
    error = null;
    if (targetMachineId == null) unawaited(dismissIntroduction());
    _changed();
    try {
      final answer = download
          ? await app.downloadLocalModel(owner.machine.machineId, model.id)
          : await app.controlLocalModel(
              owner.machine.machineId,
              model.id,
              start: startModel,
              grid: grid,
            );
      if (!_current(owner)) return null;
      error = refused = answer['error'] as String?;
      pendingOperation = LocalModelOperation.parse(answer['operation']);
      operationBusy = pendingOperation?.active == true;
    } on WsRequestFailure catch (failure) {
      // The CLI refused it, in its own words (grid's plan limit, a sign-in): those, not a generic retry.
      if (_current(owner)) error = refused = failure.detail ?? failure.code;
    } catch (_) {
      if (_current(owner)) {
        error =
            'Checking the model operation. Your click will not be repeated.';
      }
    } finally {
      if (_current(owner)) {
        pendingId = null;
        _changed();
        // Finish any inventory request issued before this click, then ask for
        // its receipt. A stale read must never overwrite a new acknowledgement.
        await _refreshing;
        if (_current(owner)) await refresh();
      }
    }
    return refused;
  }

  @override
  void dispose() {
    _disposed = true;
    _apis?.dispose();
    _timer?.cancel();
    if (_started) {
      app.removeListener(_observe);
      app.foreground.removeListener(_foregroundChanged);
      app.gridPictures.removeListener(_pictureChanged);
    }
    super.dispose();
  }
}