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.

Local model manager opens on a chosen machine (local, not pushed)

Timb196f980d02e
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 3ca8dc5a4..0c2aadc60 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -470,7 +470,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
// plenty for a list that changes when someone starts or stops serving a model.
final now = DateTime.now();
final last = _localModelsAt;
- if (last != null && now.difference(last) < const Duration(seconds: 10)) return;
+ if (last != null && now.difference(last) < const Duration(seconds: 10))
+ return;
_localModelsAt = now;
final preferred = machines.firstWhere(
(m) => app.stateOf(m.machineId)?.isLocalMachine == true,
@@ -478,9 +479,12 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
final answer = await app.gridModels(preferred.machineId);
if (!mounted) return;
- final same = answer.models.length == _localModels.length &&
- [for (var i = 0; i < answer.models.length; i++)
- answer.models[i].id == _localModels[i].id].every((x) => x);
+ final same =
+ answer.models.length == _localModels.length &&
+ [
+ for (var i = 0; i < answer.models.length; i++)
+ answer.models[i].id == _localModels[i].id,
+ ].every((x) => x);
if (same) return;
_localModels = answer.models;
_syncModels();
@@ -616,8 +620,17 @@ class _SwarmScreenState extends State<SwarmScreen> {
case 'runLocalModel':
// The native Models menu's one command. Wrapped like Link Machine…
// because the notifier may open its dialog here, and the pane it then
- // creates takes focus the same way a New Agent does.
- await _dialog(() => app.runLocalModel(context));
+ // creates takes focus the same way a New Agent does. With more than one
+ // machine linked the menu lists them and names the chosen one here;
+ // with one, or none, the notifier picks.
+ await _dialog(
+ () => app.runLocalModel(
+ context,
+ machineId: args['machineId'] is String
+ ? args['machineId'] as String
+ : null,
+ ),
+ );
case 'splitRight':
unawaited(_splitAgent(PaneResizeAxis.x));
case 'splitDown':
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 3459f7872..ce1bf210f 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -3418,18 +3418,31 @@ class AppNotifier extends ChangeNotifier {
///
/// Takes the caller's [context] because the dialog needs one and this
/// notifier holds none — the same shape as every other dialog a door opens.
- Future<void> runLocalModel(BuildContext context) async {
- final machine = _localModelMachine();
+ ///
+ /// [machineId] is the computer the manager opens on — the pane's own machine
+ /// from a pane's picker, the one chosen from the Models menu's list. Absent
+ /// (a menu with one machine, or none named), it is this computer's own when
+ /// the app has one, else whatever the person is looking at. Never guessed
+ /// past a named machine: a picker on a remote pane that opened the manager
+ /// on this computer was the bug this argument exists to end.
+ Future<void> runLocalModel(BuildContext context, {String? machineId}) async {
+ final machine = machineId != null
+ ? machineStates[machineId]
+ : _localModelMachine();
if (machine == null) {
- _lastError = 'Connect a machine before starting a local model.';
+ _lastError = machineId != null
+ ? 'That machine is no longer linked.'
+ : 'Connect a machine before starting a local model.';
_lastErrorRetryable = false;
notifyListeners();
return;
}
- final machineId = machine.machine.machineId;
+ machineId = machine.machine.machineId;
if (_store?.runLocalModelSkipDialog != true) {
final decision = await showRunLocalModelDialog(context, this, machineId);
if (decision == null) return;
+ // The dialog lists the machines and the person may have moved the choice.
+ machineId = decision.machineId;
if (decision.skipNextTime) {
try {
await _store?.saveRunLocalModelSkipDialog(true);
@@ -3471,13 +3484,27 @@ class AppNotifier extends ChangeNotifier {
if (home == null) {
return 'Could not find the home folder on ${machine.machine.displayName}.';
}
- return createAgent(
+ final error = await createAgent(
machineId,
engine: 'opencode',
folder: home,
agent: localModelAgent,
name: localModelAgentName,
);
+ if (error != null) return error;
+ // A daemon that predates `agent`/`name` does not refuse them — it ignores
+ // them, opens a plain opencode pane and names it itself. The pane exists,
+ // so the person is told what it is rather than left to notice that the
+ // manager never introduces itself: the name coming back is the tell.
+ final created = machine.agents
+ .where((a) => a.name == localModelAgentName)
+ .isNotEmpty;
+ if (!created) {
+ return 'Harness on ${machine.machine.displayName} is too old to open '
+ 'Local model manager: it opened a plain opencode pane instead. '
+ 'Update Harness there and try again.';
+ }
+ return null;
}
/// The user's home on [machine]. This computer's is in the environment; a
diff --git a/desktop/lib/widgets/grid_model_picker.dart b/desktop/lib/widgets/grid_model_picker.dart
index 8871b6031..39c236602 100644
--- a/desktop/lib/widgets/grid_model_picker.dart
+++ b/desktop/lib/widgets/grid_model_picker.dart
@@ -7,7 +7,7 @@ import '../state/app_state.dart';
import '../theme/app_theme.dart';
import '../usage/models_menu_controller.dart';
import 'engine_identity.dart';
-import 'transient_menus.dart';
+import 'pane_menu.dart';
/// The pane header's model picker, in two sections: **Subscription** and **Local**.
///
@@ -194,10 +194,10 @@ class _GridModelPickerState extends State<GridModelPicker> {
final chosen = await _showMenu(
position: position,
children: (close) => [
- _header('Subscription'),
- _item(
+ paneMenuHeader('Subscription'),
+ paneMenuItem(
onTap: () => close(const _Choice.ownLogin()),
- child: _Row(
+ child: PaneMenuRow(
selected: widget.currentModel == null,
engine: widget.engineLabel,
title:
@@ -210,13 +210,13 @@ class _GridModelPickerState extends State<GridModelPicker> {
),
),
Divider(height: 9, thickness: 1, color: AppColors.border),
- _header('Local'),
+ paneMenuHeader('Local'),
// An engine with no way onto a Local model (Cursor talks only to its own API; the daemon
// refuses the move) is told so here, instead of being offered rows whose click would do
// nothing. The daemon names the capable engines beside the list; an older daemon names
// none, and then every row is offered as before.
if (!_shown!.canRunLocally(widget.engineLabel))
- _empty(
+ paneMenuEmpty(
'${engineIdentity(widget.engineLabel).label} can only run on its own login.',
)
// Two different facts, two sentences. "We could not ask" and "this account has no grid"
@@ -225,12 +225,12 @@ class _GridModelPickerState extends State<GridModelPicker> {
// the "Talk to Local model manager" row that ends this section is the answer, and a line saying the
// list is empty above an empty list is noise.
else if (_shown!.models.isEmpty && _emptySentence(_shown!) != null)
- _empty(_emptySentence(_shown!)!),
+ paneMenuEmpty(_emptySentence(_shown!)!),
if (_shown!.canRunLocally(widget.engineLabel))
for (final model in _shown!.models)
- _item(
+ paneMenuItem(
onTap: () => close(_Choice.model(model)),
- child: _Row(
+ child: PaneMenuRow(
selected: widget.currentModel == model.id,
title: model.id,
// Which of the user's machines answers it — the part that makes a private grid
@@ -243,9 +243,12 @@ class _GridModelPickerState extends State<GridModelPicker> {
// model they want is not there yet, so it belongs in the same list, not in a section of its
// own. Never filled — the fill means "the agent is here", and this row starts something.
// Offered whatever THIS pane's engine can do: it opens a new pane, on an engine that can.
- _item(
+ paneMenuItem(
onTap: () => close(const _Choice.runLocalModel()),
- child: const _Row(selected: false, title: 'Talk to Local model manager'),
+ child: const PaneMenuRow(
+ selected: false,
+ title: 'Talk to Local model manager',
+ ),
),
],
);
@@ -276,91 +279,26 @@ class _GridModelPickerState extends State<GridModelPicker> {
return null;
}
- /// Show the menu in an OVERLAY rather than as a modal route.
- ///
- /// `showMenu` puts a full-screen modal barrier under its menu, and that barrier EATS the click
- /// that dismisses it: closing the menu and then clicking what you meant to click took two clicks,
- /// with the first one going nowhere. A menu is not a decision you have to finish before the app
- /// will listen again.
- ///
- /// So the dismisser is a translucent [Listener] instead. Translucent hit-test behaviour means it
- /// receives the pointer AND reports no hit, so the overlay below it — the app — is hit-tested next
- /// and gets the same event. One click closes the menu and lands where it was aimed.
+ /// The pane menu ([showPaneMenu]), with this picker's two hooks: the entry, so a refresh that
+ /// lands while the menu is open can redraw it, and the closer, so a pane going away under an
+ /// open menu can take the menu with it.
Future<_Choice?> _showMenu({
required RelativeRect position,
required List<Widget> Function(void Function(_Choice?) close) children,
- }) {
- final overlayState = Overlay.of(context);
- final completer = Completer<_Choice?>();
- late final OverlayEntry entry;
- late final void Function() deregister;
- var closed = false;
- void close(_Choice? choice) {
- // Guarded: a pointer-down outside and a row tap can both arrive for one gesture, and removing
- // an entry twice throws.
- if (closed) return;
- closed = true;
- deregister();
- entry.remove();
+ }) => showPaneMenu<_Choice>(
+ context: context,
+ position: position,
+ children: children,
+ onOpen: (entry, close) {
+ _entry = entry;
+ _close = close;
+ },
+ onClose: () {
_entry = null;
_shown = null;
- if (!completer.isCompleted) completer.complete(choice);
- }
-
- // A click on the window's NATIVE tab strip is not a pointer event Flutter ever sees, so the
- // dismisser below cannot fire for it — the menu was left floating over a tab it no longer
- // belonged to. The titlebar reports its own clicks instead; see [dismissTransientMenus].
- deregister = registerTransientMenu(() => close(null));
- _close = () => close(null);
-
- entry = OverlayEntry(
- builder: (context) => Stack(
- children: [
- Positioned.fill(
- child: Listener(
- behavior: HitTestBehavior.translucent,
- onPointerDown: (_) => close(null),
- child: const SizedBox.expand(),
- ),
- ),
- Positioned(
- // Right-aligned to the control, which sits at the right end of a pane header — anchoring
- // the left edge would push a wide menu off-screen.
- right: position.right,
- top: position.top,
- child: ConstrainedBox(
- // Wide enough that a status can sit right-aligned against a model id without the two
- // meeting, and for a full GGUF-style model id beside its node without either cut.
- constraints: const BoxConstraints(minWidth: 340, maxWidth: 540),
- // ⚠️ IntrinsicWidth, or the menu is ALWAYS 540 wide. `Positioned` hands down unbounded
- // width, the ConstrainedBox turns that into "up to 540", and a stretching Column takes
- // all of it — so a two-line menu wore the width of the longest model id it could ever
- // hold. This measures the rows and the clamp then applies to what they actually need.
- child: IntrinsicWidth(
- child: Material(
- color: AppColors.surface,
- elevation: 8,
- borderRadius: BorderRadius.circular(8),
- clipBehavior: Clip.antiAlias,
- child: Padding(
- padding: const EdgeInsets.symmetric(vertical: 6),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: children(close),
- ),
- ),
- ),
- ),
- ),
- ),
- ],
- ),
- );
- _entry = entry;
- overlayState.insert(entry);
- return completer.future.whenComplete(() => _close = null);
- }
+ _close = null;
+ },
+ );
/// Redraw the open menu from the fresh memo, if the list changed under it. Nothing to do when
/// no menu is open, or when the refresh said what the menu already shows — a rebuild for an
@@ -386,55 +324,6 @@ class _GridModelPickerState extends State<GridModelPicker> {
return true;
}
- /// One selectable row.
- ///
- /// The hover is the SAME rectangle as the selected fill — inset by [_menuInset] and rounded the
- /// same — so a row looks like one thing whether the pointer is on it or the agent is. An InkWell
- /// around the whole item painted edge to edge and square, over a selected fill that was neither,
- /// and the two reading as different shapes made the current row look like the odd one out.
- Widget _item({required VoidCallback onTap, required Widget child}) => Padding(
- padding: const EdgeInsets.symmetric(horizontal: _menuInset),
- child: InkWell(
- onTap: onTap,
- borderRadius: BorderRadius.circular(_rowRadius),
- child: child,
- ),
- );
-
- /// A line that states something rather than offering it — no hover, no tap.
- Widget _empty(String text) => Padding(
- padding: const EdgeInsets.fromLTRB(
- _menuInset + _rowPadding,
- 5,
- _menuInset + _rowPadding,
- 6,
- ),
- child: Text(
- text,
- style: TextStyle(fontSize: 11, color: AppColors.textSoft),
- ),
- );
-
- /// A section label. Non-interactive and short, so the two groups read as groups rather than as
- /// entries someone failed to make clickable.
- Widget _header(String label) => Padding(
- padding: const EdgeInsets.only(top: 3, bottom: 3),
- child: Padding(
- // The row's margin plus its internal padding, so a header sits directly above the text it
- // heads rather than a few pixels to either side of it.
- padding: const EdgeInsets.only(left: _menuInset + _rowPadding),
- child: Text(
- label,
- style: TextStyle(
- fontSize: 10.5,
- fontWeight: FontWeight.w600,
- letterSpacing: .3,
- color: AppColors.mutedStrong,
- ),
- ),
- ),
- );
-
@override
Widget build(BuildContext context) {
final sentence = _webSearchSentence;
@@ -491,111 +380,6 @@ class _GridModelPickerState extends State<GridModelPicker> {
}
}
-/// One menu row: optional engine mark, title, a quiet detail beside it, and a right-aligned
-/// status — filled when it is the current one. The same column order in both sections, so the eye
-/// can run straight down the menu. A [subtitle], when there is one, sits under the title inside
-/// the same fill.
-class _Row extends StatelessWidget {
- final bool selected;
- final String? engine;
- final String title;
- final String detail;
- final String? status;
- final String? subtitle;
-
- const _Row({
- required this.selected,
- required this.title,
- this.engine,
- this.detail = '',
- this.status,
- this.subtitle,
- });
-
- @override
- Widget build(BuildContext context) {
- final row = Row(
- children: [
- if (engine != null) ...[
- EngineMark(engine: engine, size: 14),
- const SizedBox(width: 7),
- ],
- // ⚠️ Expanded on the TITLE, not on the status. The status is a handful of characters and
- // wants only what it needs; giving it the flexible half truncated
- // `Qwen3.6-35B-A3B-UD-Q5_K_XL` to `Qwen3.6-35B-A3B-UD-Q5_K…` while empty space sat beside
- // it. The long string here is the model id, so the model id is what gets the room.
- Expanded(
- child: Text(
- title,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: 12.5,
- // Stated rather than inherited: a PopupMenuItem's default text style is heavier than
- // this menu wants, which read as every row being emphasised.
- fontWeight: FontWeight.w400,
- color: AppColors.text,
- ),
- ),
- ),
- if (detail.isNotEmpty) ...[
- const SizedBox(width: 6),
- Text(
- detail,
- style: TextStyle(fontSize: 11, color: AppColors.mutedStrong),
- ),
- ],
- if (status != null) ...[
- const SizedBox(width: 14),
- Text(
- status!,
- style: TextStyle(fontSize: 11, color: AppColors.mutedStrong),
- ),
- ],
- ],
- );
- return Container(
- // No margin of its own: the inset is the item's (see `_item`), so that the hover the item
- // paints and the fill this row paints are one and the same rectangle.
- padding: const EdgeInsets.symmetric(horizontal: _rowPadding, vertical: 5),
- decoration: selected
- // Subtle on purpose: one row in the menu is already the current one, and a mark loud
- // enough to announce that would compete with the thing a person opened the menu to read.
- ? BoxDecoration(
- color: AppColors.selected,
- borderRadius: BorderRadius.circular(_rowRadius),
- )
- : null,
- // The subtitle sits INSIDE the fill, under the title: it is about this row, and a sentence
- // hanging below the highlight would read as belonging to the next one.
- child: subtitle == null
- ? row
- : Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- row,
- Padding(
- padding: const EdgeInsets.only(top: 2),
- child: Text(
- subtitle!,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(fontSize: 10.5, color: AppColors.textSoft),
- ),
- ),
- ],
- ),
- );
- }
-}
-
-/// The row's own inset from the menu edge, and the padding inside its highlight. A section header
-/// carries their SUM as a left inset, so header text sits exactly above the row text it heads.
-const double _menuInset = 6;
-const double _rowPadding = 8;
-
-/// One radius for the hover and the selected fill: they are the same shape.
-const double _rowRadius = 5;
-
/// One row's meaning: a grid model, the engine's own login, or the action that starts a local
/// model. A sealed set rather than a nullable `GridModel`, because `null` already means "the menu
/// was dismissed" in `showMenu`'s own result — and the action is neither a model nor a login, so
diff --git a/desktop/lib/widgets/pane_menu.dart b/desktop/lib/widgets/pane_menu.dart
new file mode 100644
index 000000000..a55e8f6f8
--- /dev/null
+++ b/desktop/lib/widgets/pane_menu.dart
@@ -0,0 +1,264 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../theme/app_theme.dart';
+import 'engine_identity.dart';
+import 'transient_menus.dart';
+
+/// The pane header's menu, as one shape for every list that wants to look like it.
+///
+/// Born in the model picker and shared from here so a second list (the machine chooser in the
+/// Local model manager dialog) is the same menu rather than a second drawing of it: the same
+/// overlay, the same rows, the same quiet fill on the current row instead of a tick.
+///
+/// Shown in an OVERLAY rather than as a modal route. `showMenu` puts a full-screen modal barrier
+/// under its menu, and that barrier EATS the click that dismisses it: closing the menu and then
+/// clicking what you meant to click took two clicks, with the first one going nowhere. A menu is
+/// not a decision you have to finish before the app will listen again. So the dismisser is a
+/// translucent [Listener] instead: it receives the pointer AND reports no hit, so the overlay
+/// below it — the app — is hit-tested next and gets the same event. One click closes the menu and
+/// lands where it was aimed.
+///
+/// [onOpen] hands the caller the entry and its closer, for a menu that wants to redraw itself
+/// while open or to be closed from outside; [onClose] runs once, however the menu ended.
+Future<T?> showPaneMenu<T>({
+ required BuildContext context,
+ required RelativeRect position,
+ required List<Widget> Function(void Function(T?) close) children,
+ void Function(OverlayEntry entry, void Function() close)? onOpen,
+ VoidCallback? onClose,
+ double minWidth = 340,
+ double maxWidth = 540,
+}) {
+ final overlayState = Overlay.of(context);
+ final completer = Completer<T?>();
+ late final OverlayEntry entry;
+ late final void Function() deregister;
+ var closed = false;
+ void close(T? choice) {
+ // Guarded: a pointer-down outside and a row tap can both arrive for one gesture, and removing
+ // an entry twice throws.
+ if (closed) return;
+ closed = true;
+ deregister();
+ entry.remove();
+ onClose?.call();
+ if (!completer.isCompleted) completer.complete(choice);
+ }
+
+ // A click on the window's NATIVE tab strip is not a pointer event Flutter ever sees, so the
+ // dismisser below cannot fire for it — the menu was left floating over a tab it no longer
+ // belonged to. The titlebar reports its own clicks instead; see [dismissTransientMenus].
+ deregister = registerTransientMenu(() => close(null));
+
+ entry = OverlayEntry(
+ builder: (context) => Stack(
+ children: [
+ Positioned.fill(
+ child: Listener(
+ behavior: HitTestBehavior.translucent,
+ onPointerDown: (_) => close(null),
+ child: const SizedBox.expand(),
+ ),
+ ),
+ Positioned(
+ // Right-aligned to the control, which sits at the right end of a pane header — anchoring
+ // the left edge would push a wide menu off-screen.
+ right: position.right,
+ top: position.top,
+ child: ConstrainedBox(
+ // Wide enough that a status can sit right-aligned against a model id without the two
+ // meeting, and for a full GGUF-style model id beside its node without either cut.
+ constraints: BoxConstraints(minWidth: minWidth, maxWidth: maxWidth),
+ // ⚠️ IntrinsicWidth, or the menu is ALWAYS [maxWidth] wide. `Positioned` hands down
+ // unbounded width, the ConstrainedBox turns that into "up to maxWidth", and a
+ // stretching Column takes all of it — so a two-line menu wore the width of the longest
+ // model id it could ever hold. This measures the rows and the clamp then applies to
+ // what they actually need.
+ child: IntrinsicWidth(
+ child: Material(
+ color: AppColors.surface,
+ elevation: 8,
+ borderRadius: BorderRadius.circular(8),
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 6),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: children(close),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ onOpen?.call(entry, () => close(null));
+ overlayState.insert(entry);
+ return completer.future;
+}
+
+/// One selectable row of a pane menu.
+///
+/// The hover is the SAME rectangle as the selected fill — inset by [kPaneMenuInset] and rounded
+/// the same — so a row looks like one thing whether the pointer is on it or the choice is. An
+/// InkWell around the whole item painted edge to edge and square, over a selected fill that was
+/// neither, and the two reading as different shapes made the current row look like the odd one
+/// out.
+Widget paneMenuItem({required VoidCallback onTap, required Widget child}) =>
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: kPaneMenuInset),
+ child: InkWell(
+ onTap: onTap,
+ borderRadius: BorderRadius.circular(kPaneMenuRowRadius),
+ child: child,
+ ),
+ );
+
+/// A line that states something rather than offering it — no hover, no tap.
+Widget paneMenuEmpty(String text) => Padding(
+ padding: const EdgeInsets.fromLTRB(
+ kPaneMenuInset + kPaneMenuRowPadding,
+ 5,
+ kPaneMenuInset + kPaneMenuRowPadding,
+ 6,
+ ),
+ child: Text(text, style: TextStyle(fontSize: 11, color: AppColors.textSoft)),
+);
+
+/// A section label. Non-interactive and short, so the groups read as groups rather than as
+/// entries someone failed to make clickable.
+Widget paneMenuHeader(String label) => Padding(
+ padding: const EdgeInsets.only(top: 3, bottom: 3),
+ child: Padding(
+ // The row's margin plus its internal padding, so a header sits directly above the text it
+ // heads rather than a few pixels to either side of it.
+ padding: const EdgeInsets.only(left: kPaneMenuInset + kPaneMenuRowPadding),
+ child: Text(
+ label,
+ style: TextStyle(
+ fontSize: 10.5,
+ fontWeight: FontWeight.w600,
+ letterSpacing: .3,
+ color: AppColors.mutedStrong,
+ ),
+ ),
+ ),
+);
+
+/// One row of a pane menu: a title, an optional mark before it ([engine]'s mark or any
+/// [leading]), a short [detail] after it, a right-aligned [status], and a [subtitle] under it
+/// inside the same fill. The current row carries a quiet fill — subtle on purpose: one row in the
+/// menu is already the current one, and a mark loud enough to announce that would compete with
+/// the thing a person opened the menu to read.
+class PaneMenuRow extends StatelessWidget {
+ final bool selected;
+ final String? engine;
+ final Widget? leading;
+ final String title;
+ final String detail;
+ final String? status;
+ final String? subtitle;
+
+ const PaneMenuRow({
+ super.key,
+ required this.selected,
+ required this.title,
+ this.engine,
+ this.leading,
+ this.detail = '',
+ this.status,
+ this.subtitle,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final row = Row(
+ children: [
+ if (engine != null) ...[
+ EngineMark(engine: engine, size: 14),
+ const SizedBox(width: 7),
+ ] else if (leading != null) ...[
+ leading!,
+ const SizedBox(width: 7),
+ ],
+ // ⚠️ Expanded on the TITLE, not on the status. The status is a handful of characters and
+ // wants only what it needs; giving it the flexible half truncated
+ // `Qwen3.6-35B-A3B-UD-Q5_K_XL` to `Qwen3.6-35B-A3B-UD-Q5_K…` while empty space sat beside
+ // it. The long string here is the model id, so the model id is what gets the room.
+ Expanded(
+ child: Text(
+ title,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ fontSize: 12.5,
+ // Stated rather than inherited: a PopupMenuItem's default text style is heavier than
+ // this menu wants, which read as every row being emphasised.
+ fontWeight: FontWeight.w400,
+ color: AppColors.text,
+ ),
+ ),
+ ),
+ if (detail.isNotEmpty) ...[
+ const SizedBox(width: 6),
+ Text(
+ detail,
+ style: TextStyle(fontSize: 11, color: AppColors.mutedStrong),
+ ),
+ ],
+ if (status != null) ...[
+ const SizedBox(width: 14),
+ Text(
+ status!,
+ style: TextStyle(fontSize: 11, color: AppColors.mutedStrong),
+ ),
+ ],
+ ],
+ );
+ return Container(
+ // No margin of its own: the inset is the item's (see [paneMenuItem]), so that the hover the
+ // item paints and the fill this row paints are one and the same rectangle.
+ padding: const EdgeInsets.symmetric(
+ horizontal: kPaneMenuRowPadding,
+ vertical: 5,
+ ),
+ decoration: selected
+ ? BoxDecoration(
+ color: AppColors.selected,
+ borderRadius: BorderRadius.circular(kPaneMenuRowRadius),
+ )
+ : null,
+ // The subtitle sits INSIDE the fill, under the title: it is about this row, and a sentence
+ // hanging below the highlight would read as belonging to the next one.
+ child: subtitle == null
+ ? row
+ : Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ row,
+ Padding(
+ padding: const EdgeInsets.only(top: 2),
+ child: Text(
+ subtitle!,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(fontSize: 10.5, color: AppColors.textSoft),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// The row's own inset from the menu edge, and the padding inside its highlight. A section header
+/// carries their SUM as a left inset, so header text sits exactly above the row text it heads.
+const double kPaneMenuInset = 6;
+const double kPaneMenuRowPadding = 8;
+
+/// One radius for the hover and the selected fill: they are the same shape.
+const double kPaneMenuRowRadius = 5;
diff --git a/desktop/lib/widgets/run_local_model_dialog.dart b/desktop/lib/widgets/run_local_model_dialog.dart
index 2d75d68ee..c56865778 100644
--- a/desktop/lib/widgets/run_local_model_dialog.dart
+++ b/desktop/lib/widgets/run_local_model_dialog.dart
@@ -1,11 +1,14 @@
import 'dart:async';
import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_checkbox.dart';
import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
+import '../theme/app_theme.dart';
+import 'pane_menu.dart';
/// The one place the "Run a local model" flow is explained.
///
@@ -15,14 +18,20 @@ import '../state/app_state.dart';
/// person decided, and the notifier does the rest, so the two doors cannot
/// drift into two definitions of what Start means.
///
-/// Null is Not now (or Escape, or a click outside). A record is Start, with
-/// whether the person asked not to see this again — persisted by the caller,
-/// not here, because the store belongs to the notifier.
-Future<({bool skipNextTime})?> showRunLocalModelDialog(
+/// Null is Not now (or Escape, or a click outside). A record is Start: the
+/// machine the manager opens on, and whether the person asked not to see this
+/// again — persisted by the caller, not here, because the store belongs to the
+/// notifier.
+///
+/// [machineId] is the door's own answer to "which computer" — the pane's
+/// machine, or the one the menu named — and is what the dialog starts on. With
+/// more than one machine linked the dialog shows them and lets the person move
+/// the choice; with one, there is nothing to choose and nothing is shown.
+Future<({String machineId, bool skipNextTime})?> showRunLocalModelDialog(
BuildContext context,
AppNotifier notifier,
String machineId,
-) => showAppDialog<({bool skipNextTime})>(
+) => showAppDialog<({String machineId, bool skipNextTime})>(
context: context,
// Lighter than the app's default veil: this is a two-second yes/no in front
// of the swarm the person was just looking at, not a screen of its own, and
@@ -33,11 +42,15 @@ Future<({bool skipNextTime})?> showRunLocalModelDialog(
_RunLocalModelDialog(notifier: notifier, machineId: machineId),
);
-/// Prerequisites are said only when one is missing, as one sentence in the
-/// machine line's place, with Start disabled. Present and satisfied, nothing
-/// is said — a checklist of green ticks would make a two-second decision look
-/// like a setup screen.
-enum _Prerequisite { opencode, grid }
+/// Two prerequisites, said only when one is missing, as one sentence with
+/// Start disabled: the machine is reachable (a pane cannot open on a computer
+/// that is not answering — Start used to fail afterwards with "could not find
+/// the home folder", which is the same fact said too late), and it has
+/// opencode, because the manager IS an opencode pane. Whether the account has
+/// local models set up is NOT checked here — the manager itself says so, in
+/// conversation, if it finds nothing; the dialog's job is to let the person
+/// pick a machine and go.
+enum _Prerequisite { unlinked, offline, opencode }
class _RunLocalModelDialog extends StatefulWidget {
const _RunLocalModelDialog({required this.notifier, required this.machineId});
@@ -50,10 +63,9 @@ class _RunLocalModelDialog extends StatefulWidget {
}
class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {
- /// Whether the machine has a private grid to serve on. Null until the
- /// machine answers; the sentence is only earned by an answer, the same rule
- /// New Agent keeps for a missing engine.
- bool? _hasGrid;
+ /// The machine the manager will open on. Starts as the door's answer and
+ /// moves when the person picks another; every read below is about THIS one.
+ late String _machineId = widget.machineId;
bool _skipNextTime = false;
bool _skipHovered = false;
@@ -61,36 +73,242 @@ class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {
@override
void initState() {
super.initState();
- // Two reads, fired on open and not waited for: the dialog is readable at
- // once, and a missing prerequisite appears as it is found. Deferred a frame
- // so a probe's first notifyListeners() does not land mid-build. `force` on
- // the engine probe for the reason New Agent gives — opencode arrives and
- // leaves through a terminal this app never sees, and a stored answer is
- // worth nothing here.
+ // One read, fired on open and not waited for: the dialog is readable at
+ // once, and a missing opencode appears as it is found. Deferred a frame
+ // so a probe's first notifyListeners() does not land mid-build. `force`
+ // for the reason New Agent gives — opencode arrives and leaves through a
+ // terminal this app never sees, and a stored answer is worth nothing here.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
- unawaited(widget.notifier.probeEngines(widget.machineId, force: true));
- unawaited(_readGrid());
+ _read(_machineId);
+ });
+ }
+
+ void _read(String machineId) =>
+ unawaited(widget.notifier.probeEngines(machineId, force: true));
+
+ void _pickMachine(String machineId) {
+ if (machineId == _machineId) return;
+ setState(() => _machineId = machineId);
+ _read(machineId);
+ }
+
+ /// The machines the manager could open on: this computer first, then the
+ /// online ones, then the rest — New Agent's order, for the same tiles.
+ List<MachineState> get _machines {
+ final all = widget.notifier.machines
+ .map((m) => widget.notifier.stateOf(m.machineId))
+ .whereType<MachineState>()
+ .toList();
+ int rank(MachineState m) => m.isLocalMachine
+ ? 0
+ : _online(m)
+ ? 1
+ : 2;
+ final index = {for (var i = 0; i < all.length; i++) all[i]: i};
+ all.sort((a, b) {
+ final byRank = rank(a).compareTo(rank(b));
+ return byRank != 0 ? byRank : index[a]!.compareTo(index[b]!);
});
+ return all;
+ }
+
+ bool _online(MachineState m) =>
+ m.isLocalMachine || (m.nodeOnline == true && !m.needsLink);
+
+ Widget _machineMark(MachineState m, {double size = 14}) => Icon(
+ _online(m)
+ ? (m.isLocalMachine ? LucideIcons.laptop : LucideIcons.monitor)
+ : LucideIcons.monitorOff,
+ size: size,
+ color: _online(m)
+ ? grid.AppPalette.textSecondary
+ : grid.AppPalette.textFaint,
+ semanticLabel: _online(m) ? 'Online' : 'Offline',
+ );
+
+ /// The machine, as one slim two-line row: the mark on the left spanning both
+ /// lines, the name above, what it is below ("This machine", or online /
+ /// offline for another). The row is the select's own trigger when there is
+ /// more than one machine — same row, plus a chevron — and plain otherwise.
+ Widget _machineRow(MachineState m, {required bool opens}) => Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _machineMark(m, size: 22),
+ const SizedBox(width: 10),
+ Flexible(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ m.machine.displayName,
+ key: const Key('run-local-model-machine'),
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ fontFamily: grid.AppFont.sans,
+ fontSize: 12.5,
+ height: 1.2,
+ color: grid.AppPalette.textPrimary,
+ ),
+ ),
+ Text(
+ _kind(m),
+ style: TextStyle(
+ fontFamily: grid.AppFont.sans,
+ fontSize: 11.5,
+ height: 1.2,
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (opens) ...[
+ const SizedBox(width: 6),
+ Icon(
+ LucideIcons.chevronDown,
+ size: 12,
+ color: grid.AppPalette.textSecondary,
+ ),
+ ],
+ ],
+ );
+
+ /// What a machine is, in two words, beside its name.
+ String _kind(MachineState m) => m.isLocalMachine
+ ? 'This machine'
+ : _online(m)
+ ? 'Online'
+ : 'Offline';
+
+ /// One machine: the slim row, nothing to choose. More: a row of small chips
+ /// — up to three, this computer first, the chosen one filled — and a "…"
+ /// that opens the pane menu (the same menu the pane's model picker draws,
+ /// the current row filled rather than ticked) with every machine. One row
+ /// whatever the count; the chosen machine always among the visible chips.
+ Widget _machineLine(List<MachineState> machines) {
+ final current = widget.notifier.stateOf(_machineId) ?? machines.firstOrNull;
+ if (current == null) return const SizedBox.shrink();
+ if (machines.length < 2) return _machineRow(current, opens: false);
+ final visible = machines.take(3).toList();
+ if (!visible.any((m) => m.machine.machineId == _machineId)) {
+ visible[visible.length - 1] = current;
+ }
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Text(
+ 'Pick the machine it should work on.',
+ style: TextStyle(
+ fontFamily: grid.AppFont.sans,
+ fontSize: 12.5,
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ _chips(visible, machines),
+ ],
+ );
+ }
+
+ Widget _chips(List<MachineState> visible, List<MachineState> machines) => Row(
+ children: [
+ for (final m in visible) ...[
+ Flexible(child: _chip(m)),
+ const SizedBox(width: 8),
+ ],
+ if (machines.length > visible.length)
+ _MoreMachines(
+ key: const Key('run-local-model-machine-more'),
+ onOpen: (context, position) =>
+ _openMachineMenu(context, position, machines),
+ ),
+ ],
+ );
+
+ Widget _chip(MachineState m) {
+ final selected = m.machine.machineId == _machineId;
+ return InkWell(
+ key: ValueKey('run-local-model-machine-${m.machine.machineId}'),
+ onTap: () => _pickMachine(m.machine.machineId),
+ borderRadius: BorderRadius.circular(6),
+ child: Container(
+ height: 30,
+ padding: const EdgeInsets.symmetric(horizontal: 10),
+ decoration: BoxDecoration(
+ color: selected ? AppColors.selected : grid.AppSurface.recess,
+ borderRadius: BorderRadius.circular(6),
+ border: Border.all(
+ color: selected ? AppColors.accent : Colors.transparent,
+ ),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _machineMark(m),
+ const SizedBox(width: 6),
+ Flexible(
+ child: Text(
+ m.machine.displayName,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ fontFamily: grid.AppFont.sans,
+ fontSize: 12.5,
+ color: grid.AppPalette.textPrimary,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
}
- Future<void> _readGrid() async {
- final models = await widget.notifier.gridModels(widget.machineId);
- if (!mounted) return;
- setState(() => _hasGrid = models.gridName != null);
+ Future<void> _openMachineMenu(
+ BuildContext anchor,
+ RelativeRect position,
+ List<MachineState> machines,
+ ) async {
+ final picked = await showPaneMenu<String>(
+ context: anchor,
+ position: position,
+ minWidth: 260,
+ children: (close) => [
+ paneMenuHeader('Machines'),
+ for (final m in machines)
+ paneMenuItem(
+ onTap: () => close(m.machine.machineId),
+ child: PaneMenuRow(
+ selected: m.machine.machineId == _machineId,
+ leading: _machineMark(m),
+ title: m.machine.displayName,
+ status: _kind(m),
+ ),
+ ),
+ ],
+ );
+ if (picked != null && mounted) _pickMachine(picked);
}
/// The first missing prerequisite, or null when nothing has been found
/// missing — which includes "not answered yet".
_Prerequisite? get _missing {
- final machine = widget.notifier.stateOf(widget.machineId);
+ final machine = widget.notifier.stateOf(_machineId);
+ // Two different facts, two sentences: a machine this computer has no
+ // link to is refused by the relay however alive it is, and "offline"
+ // would send the person to wake a computer that is already awake.
+ if (machine != null && machine.needsLink) return _Prerequisite.unlinked;
+ if (machine != null && !_online(machine)) return _Prerequisite.offline;
if (machine != null && machine.engines.loaded) {
final opencode = machine.engines['opencode'];
if (opencode != null && !opencode.installed) {
return _Prerequisite.opencode;
}
}
- if (_hasGrid == false) return _Prerequisite.grid;
return null;
}
@@ -104,15 +322,25 @@ class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {
final missing = _missing;
// Said only when something is missing. Satisfied, the dialog says
// nothing about the machine: the body is the whole message.
+ final name =
+ widget.notifier.stateOf(_machineId)?.machine.displayName ??
+ 'That machine';
final status = switch (missing) {
+ _Prerequisite.unlinked =>
+ '$name isn’t linked to this computer yet. Link it from the '
+ 'Machines menu, then come back.',
+ _Prerequisite.offline =>
+ '$name is offline right now. Wake it up, or pick another machine.',
_Prerequisite.opencode => 'Needs opencode on this machine first.',
- _Prerequisite.grid => 'Sign in to Harness again to set this up.',
null => null,
};
+ final machines = _machines;
return AlertDialog(
title: const Text('Models that live on your machine'),
content: SizedBox(
- width: 440,
+ // Wider than the app's small dialogs: the machine row below wants
+ // three names across before it folds the rest behind "…".
+ width: 520,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
@@ -153,7 +381,16 @@ class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {
),
),
],
- const SizedBox(height: 16),
+ const SizedBox(height: 18),
+ // Which computer, as one slim row at the foot of the message:
+ // the manager looks after ONE machine's models, so the machine
+ // is always named, and never as a control unless there is a
+ // choice. With one machine linked it is a mark and two lines;
+ // with more, the same row opens a list, this computer first —
+ // one row whatever the count, so a long list never spreads
+ // through the dialog.
+ _machineLine(machines),
+ const SizedBox(height: 12),
_SkipCheck(
value: _skipNextTime,
hovered: _skipHovered,
@@ -172,8 +409,9 @@ class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {
FilledButton(
key: const Key('run-local-model-start'),
onPressed: missing == null
- ? () =>
- Navigator.of(context).pop((skipNextTime: _skipNextTime))
+ ? () => Navigator.of(
+ context,
+ ).pop((machineId: _machineId, skipNextTime: _skipNextTime))
: null,
child: const Text('Start'),
),
@@ -232,3 +470,49 @@ class _SkipCheck extends StatelessWidget {
);
}
}
+
+/// The "…" beside the chips: a small recessed square that opens the machine menu anchored under
+/// itself. Its own widget so it has a context to measure from — the menu is positioned from the
+/// button's box, exactly as the pane's picker positions from its control.
+class _MoreMachines extends StatelessWidget {
+ const _MoreMachines({super.key, required this.onOpen});
+
+ final void Function(BuildContext context, RelativeRect position) onOpen;
+
+ @override
+ Widget build(BuildContext context) => Tooltip(
+ message: 'More machines',
+ child: InkWell(
+ onTap: () {
+ final box = context.findRenderObject() as RenderBox?;
+ final overlay =
+ Overlay.of(context).context.findRenderObject() as RenderBox?;
+ if (box == null || overlay == null) return;
+ final origin = box.localToGlobal(Offset.zero, ancestor: overlay);
+ onOpen(
+ context,
+ RelativeRect.fromLTRB(
+ origin.dx,
+ origin.dy + box.size.height + 6,
+ overlay.size.width - origin.dx - box.size.width,
+ 0,
+ ),
+ );
+ },
+ borderRadius: BorderRadius.circular(6),
+ child: Container(
+ width: 30,
+ height: 30,
+ decoration: BoxDecoration(
+ color: grid.AppSurface.recess,
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Icon(
+ Icons.more_horiz,
+ size: 18,
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index f7cc3c3eb..4063417ae 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -1638,12 +1638,20 @@ class _TerminalHeader extends StatelessWidget {
),
),
onUseOwnLogin: () => unawaited(
- notifier.clearAgentGrid(session.machineId, session.agentId),
+ notifier.clearAgentGrid(
+ session.machineId,
+ session.agentId,
+ ),
),
// The pane's own context, because the flow opens a dialog before it opens a
- // pane. Which machine it runs on is the notifier's call, not this pane's: a
- // local model is about the computer the app is on, whatever this agent is on.
- onRunLocalModel: () => unawaited(notifier.runLocalModel(context)),
+ // pane — and the pane's own MACHINE, because a picker on a remote agent's pane
+ // is asking about the models that computer can serve, not this one's.
+ onRunLocalModel: () => unawaited(
+ notifier.runLocalModel(
+ context,
+ machineId: session.machineId,
+ ),
+ ),
),
],
const SizedBox(width: 8),
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 71e3f684c..592bd1eb9 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -292,6 +292,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
guard entries != machines else { return }
machines = entries
rebuildMachinesMenu()
+ // The Models menu's last row lists these too (see `rebuildModelsMenu`), so it is rebuilt on
+ // the same change rather than waiting for the next models push to catch up.
+ rebuildModelsMenu()
}
private func rebuildMachinesMenu() {
@@ -458,10 +461,28 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
// they want is not there yet, so it sits in the same list rather than in a section of its own.
// It replaces the `Add Model` placeholder that dispatched nothing, and is wired like Link
// Machine…, through the guarded channel handler. Present whether or not anything is served.
- let run = NSMenuItem(title: "Talk to Local model manager", action: #selector(menuAction(_:)), keyEquivalent: "")
- run.target = self
- run.representedObject = "runLocalModel"
+ //
+ // The manager opens ON a machine — the one whose models it will manage — and with more than one
+ // linked, this row is the only place the menu can say which. So it becomes a submenu of the
+ // machines, one row each, this computer marked as such; every child dispatches the same command
+ // with the machine's id. With one machine, or none, it stays a plain row and the app picks.
+ let run = NSMenuItem(title: "Talk to Local model manager", action: nil, keyEquivalent: "")
run.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "runLocalModel")
+ if machines.count > 1 {
+ let pick = NSMenu(title: run.title)
+ for machine in machines {
+ let item = NSMenuItem(title: machine.local ? "\(machine.name) (this computer)" : machine.name,
+ action: #selector(runLocalModelAction(_:)), keyEquivalent: "")
+ item.target = self
+ item.representedObject = machine.id
+ pick.addItem(item)
+ }
+ run.submenu = pick
+ } else {
+ run.target = self
+ run.action = #selector(menuAction(_:))
+ run.representedObject = "runLocalModel"
+ }
modelsMenu.addItem(run)
}
@@ -580,6 +601,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
if menuItem.action == #selector(machineDeleteAction(_:)) {
return actionsEnabled && machines.contains(where: { $0.id == action && !$0.local })
}
+ if menuItem.action == #selector(runLocalModelAction(_:)) {
+ return actionsEnabled && machines.contains(where: { $0.id == action })
+ }
if menuItem.action == #selector(historyAction(_:)) {
return actionsEnabled && history.contains(where: { $0.id == action })
}
@@ -602,6 +626,11 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
sendTabAction("machineDestination", arguments: ["id": id])
}
+ @objc private func runLocalModelAction(_ sender: NSMenuItem) {
+ guard validateMenuItem(sender), let id = sender.representedObject as? String else { return }
+ sendTabAction("runLocalModel", arguments: ["machineId": id])
+ }
+
@objc private func machineDeleteAction(_ sender: NSMenuItem) {
guard validateMenuItem(sender), let id = sender.representedObject as? String else { return }
sendTabAction("deleteMachine", arguments: ["id": id])
diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dart
index 6f8409392..a3189d38f 100644
--- a/desktop/test/models_menu_test.dart
+++ b/desktop/test/models_menu_test.dart
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/swarm_catalog.dart';
@@ -20,11 +21,11 @@ import 'swarm_state_test.dart' show createApp;
/// opens, say) is left pending, which is what a machine that has not answered
/// yet looks like — the same shape as the dialog's own test.
class _LocalModelConn extends WsConn {
- _LocalModelConn()
+ _LocalModelConn([String machineId = 'm'])
: super(
wsBaseUrl: 'ws://fixture.invalid',
autonomousEnv: 'test',
- machineId: 'm',
+ machineId: machineId,
accessTokenProvider: (_, _) async => '',
onAuthFailure: (_) {},
onEvent: (_) {},
@@ -376,4 +377,66 @@ void main() {
projects.dispose();
},
);
+
+ testWidgets('native runLocalModel with a machineId opens on THAT machine', (
+ tester,
+ ) async {
+ // With two machines linked the native menu lists them and names the chosen
+ // one. The create — and the dialog's own reads — must go to that machine's
+ // connection, not to this computer's: the manager manages the models of
+ // the computer it runs on.
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ const channel = MethodChannel('harness/swarm_tabs');
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(channel, (call) async => true);
+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
+ final conns = {
+ 'm': _LocalModelConn('m'),
+ 'other': _LocalModelConn('other'),
+ };
+ final app = createApp(connectionForTest: (id) => conns[id]!);
+ const other = Machine(
+ machineId: 'other',
+ authMode: MachineAuthMode.remote,
+ name: 'Studio',
+ );
+ app.machines = [...app.machines, other];
+ app.machineStates['other'] = MachineState(other)
+ ..nodeOnline = true
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ app.machineStates['m']!.nodeOnline = true;
+ final projects = SwarmProjectStore();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ final reply = Completer<void>();
+ messenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('runLocalModel', {'machineId': 'other'}),
+ ),
+ (_) => reply.complete(),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('run-local-model-start')));
+ await tester.pumpAndSettle();
+ await reply.future;
+
+ expect(conns['m']!.creates, isEmpty);
+ final create = conns['other']!.creates.single;
+ expect(create['agent'], AppNotifier.localModelAgent);
+ expect(app.panes.single.machineId, 'other');
+
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ projects.dispose();
+ });
}
diff --git a/desktop/test/run_local_model_dialog_test.dart b/desktop/test/run_local_model_dialog_test.dart
index a544688b1..a9c438183 100644
--- a/desktop/test/run_local_model_dialog_test.dart
+++ b/desktop/test/run_local_model_dialog_test.dart
@@ -11,6 +11,7 @@ import 'package:harness/core/local_key_value_store.dart';
import 'package:harness/core/models.dart';
import 'package:harness/settings/config_store.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/pane_menu.dart';
import 'package:harness/ws/ws_conn.dart';
class _MemoryStore implements LocalKeyValueStore {
@@ -47,6 +48,10 @@ class _Conn extends WsConn {
final List<Map<String, Object?>> engines;
final String? gridName;
+ /// What the daemon names the created agent. A daemon that knows `name` echoes it; one that
+ /// predates the field names the pane itself — the shape of an old Harness on that machine.
+ String replyName = 'Local model manager';
+
/// Every `agent_create` payload, verbatim — the wire is what the plan specifies.
final creates = <Map<String, dynamic>>[];
@@ -72,11 +77,7 @@ class _Conn extends WsConn {
return Future.value({
'creationId': payload['creationId'],
'state': 'created',
- 'agent': {
- 'id': 'lm1',
- 'name': 'Local model manager',
- 'engine': 'opencode',
- },
+ 'agent': {'id': 'lm1', 'name': replyName, 'engine': 'opencode'},
});
default:
return Completer<Map<String, dynamic>>().future;
@@ -113,6 +114,8 @@ void main() {
notifier.machines = [machine];
notifier.machineStates['local'] = MachineState(machine)
..localOnly = local
+ // A remote fixture is answering: the dialog now refuses an offline machine before Start.
+ ..nodeOnline = true
..agentLoadStatus = AgentLoadStatus.loaded;
if (!local) notifier.selectedMachineId = 'local';
}
@@ -176,8 +179,21 @@ void main() {
// No dashes of any kind in the copy: the owner's rule for this dialog.
expect(find.textContaining('—'), findsNothing);
expect(find.textContaining('–'), findsNothing);
- // Nothing about the machine when nothing is missing: the body is the whole message.
+ // Nothing about prerequisites when nothing is missing — but WHICH machine is always said,
+ // this computer marked as such, so nobody has to guess where the manager will open.
expect(status, findsNothing);
+ // One slim row, not a control: with one machine there is nothing to choose.
+ expect(find.byKey(const Key('run-local-model-machine')), findsOneWidget);
+ expect(find.text('studio-7'), findsOneWidget);
+ expect(find.text('This machine'), findsOneWidget);
+ // No chips, no "…", no prompt to pick: one machine is a statement, not a choice.
+ expect(find.text('Pick the machine it should work on.'), findsNothing);
+ expect(
+ find.byKey(const ValueKey('run-local-model-machine-local')),
+ findsNothing,
+ );
+ expect(find.byKey(const Key('run-local-model-machine-more')), findsNothing);
+ expect(find.textContaining('(this computer)'), findsNothing);
});
testWidgets('missing opencode is said, and disables Start', (tester) async {
@@ -189,7 +205,8 @@ void main() {
await open(tester);
expect(statusText(tester), 'Needs opencode on this machine first.');
- expect(find.textContaining('studio-7'), findsNothing);
+ // The machine is still named: the sentence is about it.
+ expect(find.text('studio-7'), findsOneWidget);
expect(startEnabled(tester), isFalse);
await tester.tap(start, warnIfMissed: false);
await tester.pumpAndSettle();
@@ -197,17 +214,121 @@ void main() {
expect(conn.creates, isEmpty);
});
- testWidgets('no private grid yet sends the person back to sign in', (
- tester,
- ) async {
- // `gridName: null` is the daemon saying the backend has not minted one, which a new sign-in
- // fixes; the sentence says that and, like the picker, never says "grid".
+ testWidgets('no private grid is NOT the dialog\'s business', (tester) async {
+ // `gridName: null` used to disable Start with a sentence about the account. The dialog now
+ // only picks a machine and goes; whether local models are set up there is the manager's own
+ // first finding, said in conversation. A connected person is never stopped here.
build(gridName: null);
await open(tester);
- expect(statusText(tester), 'Sign in to Harness again to set this up.');
+ expect(status, findsNothing);
+ expect(startEnabled(tester), isTrue);
expect(find.textContaining('grid'), findsNothing);
+ expect(find.textContaining('set up'), findsNothing);
+ });
+
+ testWidgets('an offline machine is said before Start, not after', (
+ tester,
+ ) async {
+ // A remote machine whose daemon is not answering. Start used to go ahead and fail on the
+ // home-folder read — the same fact, discovered after the click. Now the dialog says it and
+ // Start waits, and picking a machine that IS online clears it.
+ final conns = {
+ 'local': _Conn(engines: _installed, gridName: 'someone-7f3a91c4'),
+ 'studio': _Conn(engines: _installed, gridName: 'someone-7f3a91c4'),
+ };
+ notifier.dispose();
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (id) => conns[id]!,
+ )..hasNavigationRail = false;
+ const local = Machine(
+ machineId: 'local',
+ authMode: MachineAuthMode.remote,
+ name: 'this one',
+ );
+ const studio = Machine(
+ machineId: 'studio',
+ authMode: MachineAuthMode.remote,
+ name: 'studio-7',
+ );
+ notifier.machines = [local, studio];
+ notifier.machineStates['local'] = MachineState(local)
+ ..localOnly = true
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ notifier.machineStates['studio'] = MachineState(studio)
+ ..nodeOnline = false
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ key: const Key('door'),
+ onPressed: () =>
+ notifier.runLocalModel(context, machineId: 'studio'),
+ child: const Text('door'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.byKey(const Key('door')));
+ await tester.pumpAndSettle();
+
+ expect(
+ statusText(tester),
+ 'studio-7 is offline right now. Wake it up, or pick another machine.',
+ );
expect(startEnabled(tester), isFalse);
+
+ // A machine that is up but not LINKED to this computer is a different sentence: the relay
+ // refuses it (4404), and telling the person to wake it would send them to a computer that is
+ // already awake.
+ notifier.machineStates['studio']!
+ ..nodeOnline = true
+ ..needsLink = true;
+ notifier.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(
+ statusText(tester),
+ 'studio-7 isn’t linked to this computer yet. Link it from the Machines menu, then come back.',
+ );
+ expect(startEnabled(tester), isFalse);
+ notifier.machineStates['studio']!.needsLink = false;
+
+ await tester.tap(
+ find.byKey(const ValueKey('run-local-model-machine-local')),
+ );
+ await tester.pumpAndSettle();
+ expect(status, findsNothing);
+ expect(startEnabled(tester), isTrue);
+ });
+
+ testWidgets('an old daemon that ignores the agent is named as the cause', (
+ tester,
+ ) async {
+ // A Harness that predates `agent`/`name` opens a plain opencode pane and names it itself.
+ // The pane exists, so the person is told what happened instead of watching a manager that
+ // never introduces itself.
+ build();
+ conn.replyName = 'harness-2';
+ await open(tester);
+ await tester.tap(start);
+ await tester.pumpAndSettle();
+
+ expect(conn.creates, hasLength(1));
+ expect(
+ notifier.lastError,
+ 'Harness on studio-7 is too old to open Local model manager: it opened a plain opencode '
+ 'pane instead. Update Harness there and try again.',
+ );
});
testWidgets('Not now creates nothing', (tester) async {
@@ -297,6 +418,241 @@ void main() {
expect(find.text('Models that live on your machine'), findsOneWidget);
});
+ testWidgets('a named machine wins over this computer\'s own', (tester) async {
+ // The pane picker names its pane's machine. This computer has a local machine of its own
+ // here, and it must NOT be preferred: a picker on a remote agent's pane is asking about the
+ // models THAT computer can serve.
+ final conns = {
+ 'local': _Conn(engines: _installed, gridName: 'someone-7f3a91c4'),
+ 'studio': _Conn(engines: _installed, gridName: 'someone-7f3a91c4'),
+ };
+ notifier.dispose();
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (id) => conns[id]!,
+ )..hasNavigationRail = false;
+ const local = Machine(
+ machineId: 'local',
+ authMode: MachineAuthMode.remote,
+ name: 'this one',
+ );
+ const studio = Machine(
+ machineId: 'studio',
+ authMode: MachineAuthMode.remote,
+ name: 'studio-7',
+ );
+ notifier.machines = [local, studio];
+ notifier.machineStates['local'] = MachineState(local)
+ ..localOnly = true
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ notifier.machineStates['studio'] = MachineState(studio)
+ ..nodeOnline = true
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ key: const Key('door'),
+ onPressed: () =>
+ notifier.runLocalModel(context, machineId: 'studio'),
+ child: const Text('door'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.byKey(const Key('door')));
+ await tester.pumpAndSettle();
+ await tester.tap(start);
+ await tester.pumpAndSettle();
+
+ expect(conns['local']!.creates, isEmpty);
+ // That machine's own home, as it reports it — never this computer's `$HOME`.
+ expect(conns['studio']!.creates.single['cwd'], '/home/remote');
+ expect(notifier.panes.single.machineId, 'studio');
+ });
+
+ testWidgets('with two machines the dialog lists them, and the pick wins', (
+ tester,
+ ) async {
+ // The door's machine is where the dialog STARTS; the person can move it. Two machines, the
+ // door names the remote one, the person picks this computer: the create lands here.
+ final conns = {
+ 'local': _Conn(engines: _installed, gridName: 'someone-7f3a91c4'),
+ 'studio': _Conn(engines: _installed, gridName: 'someone-7f3a91c4'),
+ };
+ notifier.dispose();
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (id) => conns[id]!,
+ )..hasNavigationRail = false;
+ const local = Machine(
+ machineId: 'local',
+ authMode: MachineAuthMode.remote,
+ name: 'this one',
+ );
+ const studio = Machine(
+ machineId: 'studio',
+ authMode: MachineAuthMode.remote,
+ name: 'studio-7',
+ );
+ notifier.machines = [local, studio];
+ notifier.machineStates['local'] = MachineState(local)
+ ..localOnly = true
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ notifier.machineStates['studio'] = MachineState(studio)
+ ..nodeOnline = true
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ key: const Key('door'),
+ onPressed: () =>
+ notifier.runLocalModel(context, machineId: 'studio'),
+ child: const Text('door'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.byKey(const Key('door')));
+ await tester.pumpAndSettle();
+ // Both machines as chips on one row, this computer first, the door's machine chosen — and
+ // one sentence saying what the chips are for.
+ expect(find.text('Pick the machine it should work on.'), findsOneWidget);
+ final localChip = find.byKey(
+ const ValueKey('run-local-model-machine-local'),
+ );
+ final remoteChip = find.byKey(
+ const ValueKey('run-local-model-machine-studio'),
+ );
+ expect(localChip, findsOneWidget);
+ expect(remoteChip, findsOneWidget);
+ expect(
+ tester.getTopLeft(localChip).dx < tester.getTopLeft(remoteChip).dx,
+ isTrue,
+ );
+ expect(tester.getTopLeft(localChip).dy, tester.getTopLeft(remoteChip).dy);
+ // Two machines fit; nothing is folded behind "…".
+ expect(find.byKey(const Key('run-local-model-machine-more')), findsNothing);
+
+ await tester.tap(localChip);
+ await tester.pumpAndSettle();
+ await tester.tap(start);
+ await tester.pumpAndSettle();
+
+ expect(conns['studio']!.creates, isEmpty);
+ expect(conns['local']!.creates, hasLength(1));
+ expect(notifier.panes.single.machineId, 'local');
+ });
+
+ testWidgets('five machines stay on one row: three chips and a "…" list', (
+ tester,
+ ) async {
+ // The row never grows with the account. Past three, the rest fold behind the more button,
+ // which opens the full list — and a machine chosen from there takes a visible slot.
+ final ids = ['local', 'b', 'c', 'd', 'e'];
+ final conns = {
+ for (final id in ids)
+ id: _Conn(engines: _installed, gridName: 'someone-7f3a91c4'),
+ };
+ notifier.dispose();
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (id) => conns[id]!,
+ )..hasNavigationRail = false;
+ notifier.machines = [
+ for (final id in ids)
+ Machine(
+ machineId: id,
+ authMode: MachineAuthMode.remote,
+ name: 'box-$id',
+ ),
+ ];
+ for (final m in notifier.machines) {
+ notifier.machineStates[m.machineId] = MachineState(m)
+ ..localOnly = m.machineId == 'local'
+ ..nodeOnline = true
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ }
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ key: const Key('door'),
+ onPressed: () =>
+ notifier.runLocalModel(context, machineId: 'local'),
+ child: const Text('door'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.byKey(const Key('door')));
+ await tester.pumpAndSettle();
+
+ final chips = [
+ for (final id in ids) find.byKey(ValueKey('run-local-model-machine-$id')),
+ ];
+ expect(chips[0], findsOneWidget);
+ expect(chips[1], findsOneWidget);
+ expect(chips[2], findsOneWidget);
+ expect(chips[3], findsNothing);
+ expect(chips[4], findsNothing);
+ final more = find.byKey(const Key('run-local-model-machine-more'));
+ expect(more, findsOneWidget);
+ // All on one line.
+ final tops = {for (final c in chips.take(3)) tester.getTopLeft(c).dy};
+ expect(tops.length, 1);
+ // The more button is a shade shorter than a chip; same row means its
+ // center sits within the chips' height, not that its top matches.
+ final chipRect = tester.getRect(chips[0]);
+ final moreCenter = tester.getCenter(more).dy;
+ expect(moreCenter > chipRect.top && moreCenter < chipRect.bottom, isTrue);
+
+ await tester.tap(more);
+ await tester.pumpAndSettle();
+ // The pane menu, not a select: a header, rows, the current one filled — no tick anywhere.
+ expect(find.text('Machines'), findsOneWidget);
+ expect(find.byType(PaneMenuRow), findsNWidgets(5));
+ for (final tick in [Icons.check, Icons.check_rounded]) {
+ expect(
+ find.descendant(
+ of: find.byType(PaneMenuRow),
+ matching: find.byIcon(tick),
+ ),
+ findsNothing,
+ );
+ }
+ await tester.tap(find.text('box-e').last);
+ await tester.pumpAndSettle();
+ await tester.tap(start);
+ await tester.pumpAndSettle();
+ expect(conns['e']!.creates, hasLength(1));
+ expect(notifier.panes.single.machineId, 'e');
+ });
+
testWidgets(
'with no local machine the focused one is used, and its own home',
(tester) async {
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index b64caa472..fe06ea39c 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -811,6 +811,40 @@ private extension SwarmTitlebar {
try checkTitlebar(!runLocal.title.lowercased().contains("grid") && !runLocal.title.contains("Mac"),
"the command names neither the plumbing nor one vendor's computer")
+ // With more than one machine linked, the row has to say WHICH computer the manager opens on:
+ // it becomes a submenu of the machines, each child dispatching the same command with that
+ // machine's id, this computer marked. With one machine (or none) it is the plain row above.
+ _ = try messenger.receive("machinesState", arguments: ["machines": machineRows])
+ let picked = main.item(withTitle: "Models")!.submenu!.items.last!
+ // AppKit gives a submenu's parent its own `submenuAction:`; what matters is that it is no longer
+ // the guarded channel handler — nothing is dispatched until a machine is chosen.
+ try checkTitlebar(picked.title == "Talk to Local model manager" && picked.submenu != nil
+ && picked.action != #selector(menuAction(_:)) && picked.representedObject == nil,
+ "with two machines the manager row opens a submenu instead of dispatching itself")
+ try checkTitlebar(picked.identifier?.rawValue == HarnessKeymapMenu.actionPrefix + "runLocalModel",
+ "the submenu's parent keeps the keymap identifier")
+ let choices = picked.submenu!.items
+ try checkTitlebar(choices.map(\.title) == ["iMac – Office (this computer)", "iMac – Home"],
+ "one child per linked machine, in the Machines menu's order, this computer marked")
+ try checkTitlebar(choices.allSatisfy { $0.target === self && $0.action == #selector(runLocalModelAction(_:)) }
+ && choices.map { $0.representedObject as? String } == ["office", "home"],
+ "each child dispatches runLocalModel for its own machine")
+ let modelCalls = messenger.calls.count
+ runLocalModelAction(choices[1])
+ try checkTitlebar(messenger.calls.last?.method == "runLocalModel"
+ && (messenger.calls.last?.arguments as? [String: String]) == ["machineId": "home"]
+ && messenger.calls.count == modelCalls + 1,
+ "choosing a machine sends runLocalModel with that machine's id")
+ actionsEnabled = false
+ try checkTitlebar(!validateMenuItem(choices[0]), "a machine choice cannot run behind a modal")
+ actionsEnabled = true
+ try checkTitlebar(validateMenuItem(choices[0]), "and returns when the modal closes")
+ _ = try messenger.receive("machinesState", arguments: ["machines": [machineRows[0]]])
+ let single = main.item(withTitle: "Models")!.submenu!.items.last!
+ try checkTitlebar(single.submenu == nil && single.representedObject as? String == "runLocalModel",
+ "one machine linked: back to the plain row, and the app picks the machine")
+ _ = try messenger.receive("machinesState", arguments: ["machines": []])
+
// The Local section is DATA, not two hardcoded names. A menu naming a model nobody serves is
// worse than one admitting it has none, which is what the empty case above asserts.
updateModels(modelRows, local: [