The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Local model manager: an agent that reads intent, a dialog that names the machine
Timb8d3ba0bffc1
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 81ca3c06a..05b26133e 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -29,6 +29,7 @@ import { listDir } from './lib/fsBrowse.js'import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'import { gridCapableEngines, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'import { listGridModels, resolveGridTarget } from './lib/gridModels.js'+import { deriveHarnessGridName } from './lib/gridDerive.js'import { AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'import { probeEngines } from './lib/engineProbe.js'@@ -580,10 +581,22 @@ export class BackendSocket {/** The account's private harness grid name, as the backend last reported it. Null until the first* `machine_meta` lands, or when this account has none yet. */private harnessGridName: string | null = null+ /** Injected so the derivation (a `grid` spawn) is a seam in tests; see `lib/gridDerive.ts`. */+ deriveGridName: () => Promise<string | null> = deriveHarnessGridName/** Which grid this machine's agents can be pointed at — for `harness status` and the models RPC. */gridName(): string | null { return this.harnessGridName }+ /**+ * The account's private grid: the backend's word when it gave one, else what this machine can+ * work out for itself (`lib/gridDerive.ts`). A backend that predates `machine_meta.gridName`+ * left every picker empty while `grid models` listed the model fine; the derivation is the+ * skill's own rule, so the daemon and the agent it opens agree on which grid is "yours".+ */+ private async resolveGridName(): Promise<string | null> {+ return this.harnessGridName ?? await this.deriveGridName()+ }+connect(): void {if (this.closed || this.ws || this.connecting) returnthis.connecting = true@@ -1475,9 +1488,10 @@ export class BackendSocket {case 'grid_models_list': {// Only the account's OWN private grid: the picker is "models my machines serve", not a// catalogue of every grid this computer's `grid` CLI happens to be signed into.+ const gridName = await this.resolveGridName()reply(type, requestId, {- gridName: this.harnessGridName,- models: await listGridModels(this.harnessGridName),+ gridName,+ models: await listGridModels(gridName),// Which engines a Local model can be offered to at all. Static per CLI version — it is// the set of launch contracts in `gridLaunch.ts` — and answered here, beside the list,// so the picker can say "Cursor runs only on its own login" instead of offering a row@@ -1838,7 +1852,7 @@ export class BackendSocket {// not know. A client that sends the full `grid` object still works unchanged.const picked = typeof payload.gridModel === 'string' ? payload.gridModel : ''if (picked && payload.grid === undefined && !clear) {- const resolved = await resolveGridTarget(this.harnessGridName, picked)+ const resolved = await resolveGridTarget(await this.resolveGridName(), picked)if (!resolved) {reply(type, requestId, { error: 'GRID_UNAVAILABLE', detail: 'Could not read this machine\'s grid endpoint.' })returndiff --git a/cli/src/lib/gridDerive.spec.ts b/cli/src/lib/gridDerive.spec.tsnew file mode 100644index 000000000..7d28f6533--- /dev/null+++ b/cli/src/lib/gridDerive.spec.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest'+import { pickPrivateGrid, privateGridPattern } from './gridDerive.js'++describe('the private grid, derived the way the skill derives it', () => {+ it('slugs the email local part and wants eight hex after it', () => {+ expect(privateGridPattern('[email protected]').test('tuan-dev-991371e4')).toBe(true)+ expect(privateGridPattern('[email protected]').test('tuan-dev-991371e4')).toBe(true)+ expect(privateGridPattern('[email protected]').test('tuan-dev-991371e')).toBe(false)+ expect(privateGridPattern('[email protected]').test('tuan-dev-gg1371e4')).toBe(false)+ expect(privateGridPattern('[email protected]').test('a-b-0123abcd')).toBe(true)+ })++ it('picks the one permissioned-public grid that matches, never a lookalike', () => {+ const rows = [+ { grid: 'autonomous.ai', type: 'private-domain' },+ { grid: 'tuan-dev-991371e4', type: 'permissioned-public' },+ { grid: 'tuan-dev-11111111', type: 'domain-restricted' }, // right shape, wrong type+ { grid: 'BBB', type: 'domain-restricted' },+ ]+ expect(pickPrivateGrid('[email protected]', rows)).toBe('tuan-dev-991371e4')+ })++ it('answers null for none, and null for more than one — a guess would be someone else\'s grid', () => {+ expect(pickPrivateGrid('[email protected]', [{ grid: 'autonomous.ai', type: 'private-domain' }])).toBeNull()+ expect(pickPrivateGrid('[email protected]', [+ { grid: 'tuan-dev-991371e4', type: 'permissioned-public' },+ { grid: 'tuan-dev-aaaaaaaa', type: 'permissioned-public' },+ ])).toBeNull()+ })+})diff --git a/cli/src/lib/gridDerive.ts b/cli/src/lib/gridDerive.tsnew file mode 100644index 000000000..2964ff5bc--- /dev/null+++ b/cli/src/lib/gridDerive.ts@@ -0,0 +1,73 @@+/**+ * The account's own private grid, worked out on this machine when the backend has not said.+ *+ * The backend mints the name and pushes it on every connect (`machine_meta.gridName`,+ * `backendSocket.ts`); that is the source of truth. But a backend that predates the route pushes+ * nothing, and then every picker on every pane was empty while `grid models <name>` listed the+ * model fine — the daemon knew how to ask, just not what to ask about. The name is recognisable+ * without asking anyone, by the same rule the Harness Compute skill gives its agents+ * (`docs/skills/harness-compute.md`, "Which grid"): the signed-in email's local part, lowercased,+ * runs of non-alphanumerics folded to `-`, followed by `-` and eight hex digits, of type+ * `permissioned-public`. Exactly one grid this computer is signed into matches, or the answer is+ * null — never a guess, because names are global and a wrong one is someone else's grid.+ *+ * Read from `~/.grid/credentials.toml` (the email) and `grid ls --json` (the grids), cached for a+ * short while: the list costs a `grid` spawn and a network round trip, and the picker asks on+ * every open.+ */+import { readFileSync } from 'node:fs'+import { gridCredentialsPath } from './gridCredentials.js'+import { gridJson } from './gridExec.js'++const TTL_MS = 60_000++let memo: { at: number; name: string | null } | null = null++/** The email `grid login` recorded, or null when this machine has no grid credentials. */+export function signedInGridEmail(env: NodeJS.ProcessEnv = process.env): string | null {+ try {+ const toml = readFileSync(gridCredentialsPath(env), 'utf-8')+ const match = /^\s*email\s*=\s*"([^"]+)"/m.exec(toml)+ return match?.[1]?.trim() || null+ } catch {+ return null+ }+}++/** The name a private grid for [email] carries, as a pattern: `<slug>-<8 hex>`. */+export function privateGridPattern(email: string): RegExp {+ const local = email.split('@')[0] ?? ''+ const slug = local.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'user'+ return new RegExp(`^${slug.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}-[0-9a-f]{8}$`)+}++/** Pick the one private grid for [email] out of `grid ls --json` rows, or null. */+export function pickPrivateGrid(+ email: string,+ rows: Array<{ grid?: unknown; type?: unknown }>,+): string | null {+ const pattern = privateGridPattern(email)+ const names = rows+ .filter((row) => row.type === 'permissioned-public' && typeof row.grid === 'string' && pattern.test(row.grid))+ .map((row) => row.grid as string)+ return names.length === 1 ? names[0]! : null+}++/**+ * The account's private grid as this machine can tell, or null. Memoised for [TTL_MS]; pass+ * `fresh` to bypass the memo (a sign-in that just created the grid).+ */+export async function deriveHarnessGridName(opts: { fresh?: boolean } = {}): Promise<string | null> {+ if (!opts.fresh && memo && Date.now() - memo.at < TTL_MS) return memo.name+ const email = signedInGridEmail()+ let name: string | null = null+ if (email) {+ const { value } = await gridJson<Array<{ grid?: unknown; type?: unknown }>>(['--remote', 'ls'])+ if (Array.isArray(value)) name = pickPrivateGrid(email, value)+ }+ memo = { at: Date.now(), name }+ return name+}++/** For tests. */+export function resetGridDeriveMemo(): void { memo = null }diff --git a/desktop/lib/settings/config_store.dart b/desktop/lib/settings/config_store.dartindex a60d83c5c..ec5dcb61f 100644--- a/desktop/lib/settings/config_store.dart+++ b/desktop/lib/settings/config_store.dart@@ -9,11 +9,10 @@ class ConfigStore {static const _environmentKey = 'app_autonomous_environment';static const _skippedDesktopUpdateVersionKey ='skipped_desktop_update_version';- // "Don't show this again" on the Run a local model dialog. Here rather than- // beside the pane layout because it is a choice about the PERSON, not about- // a machine or a tab: somebody who has watched the explanation once does not- // need it again for their second computer either.- static const _runLocalModelSkipDialogKey = 'runLocalModel.skipDialog';+ // Written by builds that had a "Don't show this again" on the Local model+ // manager dialog. The dialog is where a machine is chosen now, so there is+ // nothing to skip; kept only so Reset cleans state those builds wrote.+ static const _legacyRunLocalModelSkipDialogKey = 'runLocalModel.skipDialog';// No longer read or written: live pre-flight runs on every launch. Kept only// so Reset can clean state written by older desktop builds.static const _legacyEnvironmentSetupVersionKey = 'environment_setup_version';@@ -29,39 +28,22 @@ class ConfigStore {String? _cachedBaseUrl;String? _cachedEnvironment;String? _cachedSkippedDesktopUpdateVersion;- bool _cachedRunLocalModelSkipDialog = false;String? get skippedDesktopUpdateVersion => _cachedSkippedDesktopUpdateVersion;- /// Whether the Run a local model dialog has been waved off for good. False- /// until [load] or [saveRunLocalModelSkipDialog] says otherwise, so a store- /// that was never read still shows the explanation — the safe direction.- bool get runLocalModelSkipDialog => _cachedRunLocalModelSkipDialog;-Future<AppConfig> load() async {// Keep the tiny startup path sequential and predictable.final baseUrl = await _storage.read(_baseUrlKey);final environment = await _storage.read(_environmentKey);final skippedUpdate = await _storage.read(_skippedDesktopUpdateVersionKey);- final skipRunLocalModel = await _storage.read(_runLocalModelSkipDialogKey);_cachedBaseUrl = baseUrl ?? defaultBaseUrl;_cachedEnvironment = environment == 'stag' ? 'stag' : 'prod';_cachedSkippedDesktopUpdateVersion = skippedUpdate?.trim().isEmpty ?? true? null: skippedUpdate!.trim();- _cachedRunLocalModelSkipDialog = skipRunLocalModel == 'true';return config;}- Future<void> saveRunLocalModelSkipDialog(bool value) async {- _cachedRunLocalModelSkipDialog = value;- if (value) {- await _storage.write(_runLocalModelSkipDialogKey, 'true');- } else {- await _storage.delete(_runLocalModelSkipDialogKey);- }- }-Future<void> save(String baseUrl) async {_cachedBaseUrl = baseUrl;await _storage.write(_baseUrlKey, baseUrl);@@ -90,12 +72,11 @@ class ConfigStore {_cachedBaseUrl = null;_cachedEnvironment = null;_cachedSkippedDesktopUpdateVersion = null;- _cachedRunLocalModelSkipDialog = false;await Future.wait([_storage.delete(_baseUrlKey),_storage.delete(_environmentKey),_storage.delete(_skippedDesktopUpdateVersionKey),- _storage.delete(_runLocalModelSkipDialogKey),+ _storage.delete(_legacyRunLocalModelSkipDialogKey),_storage.delete(_legacyEnvironmentSetupVersionKey),]);}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 8119f4c5e..5aad43ef8 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -291,6 +291,7 @@ class AppNotifier extends ChangeNotifier {final AuthSession session;AppConfig config;late ApiClient api;+/// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,/// [ViewerServices.login] in a viewer build — which has no CLI — under one name, so every call/// site reads the same in both.@@ -3482,14 +3483,9 @@ class AppNotifier extends ChangeNotifier {/// The one action behind every "Talk to Local model manager" entry: explain once,/// then open opencode as the agent that starts one.///- /// Runs on the computer the app is on ([MachineState.isLocalMachine]) — a- /// local model is about THIS hardware — and falls back to the focused- /// machine only when there is no local one, in which case the dialog's- /// machine line says so by naming it. With the dialog waved off for good- /// ([ConfigStore.runLocalModelSkipDialog]) the agent is created straight- /// away; otherwise the dialog decides, and Start is what creates. Nothing- /// here reports progress: the pane appearing is the confirmation, and a- /// refusal lands in [lastError] like any other create.+ /// The dialog decides, and Start is what creates. Nothing here reports+ /// progress: the pane appearing is the confirmation, and a refusal lands in+ /// [lastError] like any other create.////// 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.@@ -3500,7 +3496,16 @@ class AppNotifier extends ChangeNotifier {/// 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 {+ ///+ /// [chooseMachine] is whether the dialog offers the other machines. A pane's+ /// picker is a question about THAT pane's computer, so it does not (the+ /// machine is named, not offered); the Models menu is about the account, so+ /// it does.+ Future<void> runLocalModel(+ BuildContext context, {+ String? machineId,+ bool chooseMachine = true,+ }) async {final machine = machineId != null? machineStates[machineId]: _localModelMachine();@@ -3513,20 +3518,15 @@ class AppNotifier extends ChangeNotifier {return;}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);- } catch (_) {- // A state file that cannot be written costs one more look at the- // dialog next time, not the agent being asked for now.- }- }- }+ final decision = await showRunLocalModelDialog(+ context,+ this,+ machineId,+ chooseMachine: chooseMachine,+ );+ if (decision == null) return;+ // The dialog may list the machines, and the person may have moved the choice.+ machineId = decision.machineId;final error = await _startLocalModelAgent(machineId);if (error != null) {_lastError = error;diff --git a/desktop/lib/state/retarget_refusal.dart b/desktop/lib/state/retarget_refusal.dartindex d2960c446..f1ebca52e 100644--- a/desktop/lib/state/retarget_refusal.dart+++ b/desktop/lib/state/retarget_refusal.dart@@ -25,8 +25,13 @@ String retargetRefusalMessage(String code, {required String engineLabel}) {'TMUX_TOO_OLD_FOR_GRID' => "This machine's tmux is too old to move an agent to a Local model. Update tmux there.",'TMUX_UNAVAILABLE' || 'TMUX_FAILED' =>"This machine's tmux did not answer. Try again in a moment.",+ // Changing model restarts the agent's process, which would cut off the+ // reply it is writing — so the daemon waits for the person, and the+ // sentence says what to do rather than naming the state ("mid-turn" read+ // as an error).'AGENT_BUSY' =>- 'This agent is mid-turn. Let it finish, then choose the model again.',+ 'This agent is still responding. Stop it or let it finish, then '+ 'choose the model again.','AGENT_NOT_FOUND' ||'MISSING_AGENT_ID' => 'This agent is no longer on the machine.','NO_ACTIVE_PROCESS' || 'RETARGET_UNSUPPORTED_BACKEND' =>diff --git a/desktop/lib/widgets/run_local_model_dialog.dart b/desktop/lib/widgets/run_local_model_dialog.dartindex c56865778..65037e6f8 100644--- a/desktop/lib/widgets/run_local_model_dialog.dart+++ b/desktop/lib/widgets/run_local_model_dialog.dart@@ -4,7 +4,6 @@ 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';@@ -19,27 +18,32 @@ import 'pane_menu.dart';/// drift into two definitions of what Start means.////// 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.+/// machine the manager opens on.////// [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(+/// [chooseMachine] and more than one machine linked, the dialog shows the+/// others and lets the person move the choice; otherwise the machine is named+/// and that is that. There is deliberately no "don't show this again": the+/// dialog is where the machine is chosen, and a dialog that could be waved+/// off would take the choice with it.+Future<({String machineId})?> showRunLocalModelDialog(BuildContext context,AppNotifier notifier,- String machineId,-) => showAppDialog<({String machineId, bool skipNextTime})>(+ String machineId, {+ bool chooseMachine = true,+}) => showAppDialog<({String machineId})>(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// the 90% default read as the window going dark. The blur stays, so what is// behind is felt rather than read. Same weight the swarm rename uses.veilTint: const Color(0x99000000),- builder: (_) =>- _RunLocalModelDialog(notifier: notifier, machineId: machineId),+ builder: (_) => _RunLocalModelDialog(+ notifier: notifier,+ machineId: machineId,+ chooseMachine: chooseMachine,+ ),);/// Two prerequisites, said only when one is missing, as one sentence with@@ -53,10 +57,15 @@ Future<({String machineId, bool skipNextTime})?> showRunLocalModelDialog(enum _Prerequisite { unlinked, offline, opencode }class _RunLocalModelDialog extends StatefulWidget {- const _RunLocalModelDialog({required this.notifier, required this.machineId});+ const _RunLocalModelDialog({+ required this.notifier,+ required this.machineId,+ required this.chooseMachine,+ });final AppNotifier notifier;final String machineId;+ final bool chooseMachine;@overrideState<_RunLocalModelDialog> createState() => _RunLocalModelDialogState();@@ -67,9 +76,6 @@ class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {/// moves when the person picks another; every read below is about THIS one.late String _machineId = widget.machineId;- bool _skipNextTime = false;- bool _skipHovered = false;-@overridevoid initState() {super.initState();@@ -190,7 +196,9 @@ class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {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);+ if (!widget.chooseMachine || 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;@@ -390,13 +398,6 @@ class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {// 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,- onHover: (value) => setState(() => _skipHovered = value),- onChanged: (value) => setState(() => _skipNextTime = value),- ),],),),@@ -409,9 +410,7 @@ class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {FilledButton(key: const Key('run-local-model-start'),onPressed: missing == null- ? () => Navigator.of(- context,- ).pop((machineId: _machineId, skipNextTime: _skipNextTime))+ ? () => Navigator.of(context).pop((machineId: _machineId)): null,child: const Text('Start'),),@@ -422,55 +421,6 @@ class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {}}-/// "Don't show this again", box and label under one tap target — the rule-/// [AppCheckbox] states for every row that carries one.-class _SkipCheck extends StatelessWidget {- const _SkipCheck({- required this.value,- required this.hovered,- required this.onHover,- required this.onChanged,- });-- final bool value;- final bool hovered;- final ValueChanged<bool> onHover;- final ValueChanged<bool> onChanged;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return MouseRegion(- cursor: SystemMouseCursors.click,- onEnter: (_) => onHover(true),- onExit: (_) => onHover(false),- child: GestureDetector(- key: const Key('run-local-model-skip'),- onTap: () => onChanged(!value),- behavior: HitTestBehavior.opaque,- child: Padding(- padding: const EdgeInsets.symmetric(vertical: 6),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- AppCheckbox(value: value, hovered: hovered, onChanged: onChanged),- const SizedBox(width: 10),- Text(- "Don't show this again",- style: TextStyle(- fontFamily: grid.AppFont.sans,- fontSize: 13,- color: grid.AppPalette.textPrimary,- ),- ),- ],- ),- ),- ),- );- }-}-/// 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.diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex b241ce2dd..021f43c7e 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -1717,6 +1717,7 @@ class _TerminalHeader extends StatelessWidget {notifier.runLocalModel(context,machineId: session.machineId,+ chooseMachine: false,),),)diff --git a/desktop/test/retarget_refusal_test.dart b/desktop/test/retarget_refusal_test.dartindex 12874f5c7..2703796eb 100644--- a/desktop/test/retarget_refusal_test.dart+++ b/desktop/test/retarget_refusal_test.dart@@ -71,7 +71,7 @@ void main() {final app = createApp(connectionForTest: (_) => _Refusing('AGENT_BUSY'));addTearDown(app.dispose);await app.clearAgentGrid('m', 'a1');- expect(app.lastError, contains('mid-turn'));+ expect(app.lastError, contains('still responding'));});test('names the engine that can only run on its own login', () {@@ -81,12 +81,18 @@ void main() {);});- test('a busy agent is asked to finish first', () {- expect(- retargetRefusalMessage('AGENT_BUSY', engineLabel: 'Claude Code'),- contains('finish'),- );- });+ test(+ 'a busy agent is told to stop it or let it finish — never "mid-turn"',+ () {+ final sentence = retargetRefusalMessage(+ 'AGENT_BUSY',+ engineLabel: 'Claude Code',+ );+ expect(sentence, contains('Stop it'));+ expect(sentence, contains('finish'));+ expect(sentence, isNot(contains('mid-turn')));+ },+ );test('every refusal the daemon can raise has a sentence, and none says "grid"',diff --git a/desktop/test/run_local_model_dialog_test.dart b/desktop/test/run_local_model_dialog_test.dartindex a9c438183..fadfbcdc4 100644--- a/desktop/test/run_local_model_dialog_test.dart+++ b/desktop/test/run_local_model_dialog_test.dart@@ -7,28 +7,12 @@ import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';-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 {- final values = <String, String>{};- @override- Future<String?> read(String key) async => values[key];- @override- Future<void> write(String key, String value) async {- values[key] = value;- }-- @override- Future<void> delete(String key) async {- values.remove(key);- }-}-/// A connection that answers the dialog's three reads and the create at once. Without it the/// dialog would wait out each request's own timeout, and `pumpAndSettle` would be measuring those/// rather than the dialog. Anything else asked of it (a terminal open after the create, say) is@@ -165,7 +149,9 @@ void main() {),findsOneWidget,);- expect(find.text("Don't show this again"), findsOneWidget);+ // No "Don't show this again": the dialog is where the machine is chosen, and a dialog that+ // could be waved off would take the choice with it.+ expect(find.text("Don't show this again"), findsNothing);expect(find.text('Not now'), findsOneWidget);expect(find.text('Start'), findsOneWidget);// The product's two rules for this dialog: never the CLI's name, never one vendor's noun for@@ -378,46 +364,6 @@ void main() {expect(payload.containsKey('agent'), isFalse);});- testWidgets('the tick is remembered, and the next entry skips the dialog', (- tester,- ) async {- final storage = _MemoryStore();- build(configStore: ConfigStore(storage: storage));- await open(tester);- await tester.tap(find.byKey(const Key('run-local-model-skip')));- await tester.pump();- await tester.tap(start);- await tester.pumpAndSettle();- expect(conn.creates, hasLength(1));-- // Persisted under the plan's key, and read back by a fresh store — the choice is about the- // person, and it has to survive a relaunch to be one.- expect(storage.values['runLocalModel.skipDialog'], 'true');- final reopened = ConfigStore(storage: storage);- await reopened.load();- expect(reopened.runLocalModelSkipDialog, isTrue);-- await tester.tap(find.byKey(const Key('door')));- await tester.pumpAndSettle();- expect(find.text('Models that live on your machine'), findsNothing);- expect(conn.creates, hasLength(2));- expect(conn.creates.last['agent'], 'harness-compute');- expect(conn.creates.last.containsKey('prompt'), isFalse);- });-- testWidgets('Start without the tick keeps asking', (tester) async {- final storage = _MemoryStore();- build(configStore: ConfigStore(storage: storage));- await open(tester);- await tester.tap(start);- await tester.pumpAndSettle();- expect(storage.values.containsKey('runLocalModel.skipDialog'), isFalse);-- await tester.tap(find.byKey(const Key('door')));- await tester.pumpAndSettle();- 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@@ -479,6 +425,79 @@ void main() {expect(notifier.panes.single.machineId, 'studio');});+ testWidgets('from a pane, the machine is named, not offered', (tester) async {+ // A pane's picker asks about THAT pane's computer. Two machines linked, the door names the+ // remote one and says not to offer the other: the dialog shows one plain row, no chips, and+ // Start opens there.+ 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',+ chooseMachine: false,+ ),+ child: const Text('door'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.byKey(const Key('door')));+ await tester.pumpAndSettle();++ expect(find.text('studio-7'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('run-local-model-machine-local')),+ findsNothing,+ );+ expect(+ find.byKey(const ValueKey('run-local-model-machine-studio')),+ findsNothing,+ );+ expect(find.text('Pick the machine it should work on.'), findsNothing);++ await tester.tap(start);+ await tester.pumpAndSettle();+ expect(conns['local']!.creates, isEmpty);+ expect(conns['studio']!.creates, hasLength(1));+ });+testWidgets('with two machines the dialog lists them, and the pick wins', (tester,) async {diff --git a/docs/skills/harness-compute.agent.md b/docs/skills/harness-compute.agent.mdindex 77b1bbac1..35475349f 100644--- a/docs/skills/harness-compute.agent.md+++ b/docs/skills/harness-compute.agent.md@@ -7,10 +7,10 @@ permission:question: allow----You are **Local model manager** — the agent that gets a model running on this computer, under the user's Harness account, so every coding agent can switch to it from its model picker.+You are **Local model manager** — the agent that looks after the models on this computer, under the user's Harness account, so every coding agent can switch to them from its model picker.-Everything you know about doing that is in the `harness-compute` skill. Load it before you do anything else, and follow it exactly: its ground rules (talk the way Harness talks; never say "grid" or hand the user a command; ask through a tool, not prose), its section 1 (start a local model, ending with where to pick it), and its section 2 (show what's running) when asked. You never edit this agent's config or add a provider: once the model answers, the picker is the hand-off.+Everything you know about doing that is in the `harness-compute` skill. Load it before you do anything else, and follow it exactly: its ground rules (talk the way Harness talks; never say "grid" or hand the user a command; ask through a tool, not prose), and its sections — start a model, show what's running, change a model that is running. You never edit this agent's config or add a provider: once a model answers, the picker is the hand-off.-**Whatever the user's first message is, begin section 1 at step 1.** "hi", "go", "start", a question — all of them mean "let's do this." Don't explain who you are or what will happen; the app already did. Your first visible act is section 1's first question, through the question tool, with its options. If the user's first message already answers that question (or the context one), skip what was answered.+**Greet, then listen, then look, then act — in that order.** A greeting or anything without a request in it gets two lines (who you are, what you can do here) and one tool question with the skill's four options; no commands run until the person picks. A request gets the machine looked at and the one thing named done: "start a model" with nothing running is section 1 from its first question; "raise it to 64K", "make it two at once", "turn vision off", "stop it", "what's running" are about a model already there — read its current settings, change or report that one thing, no questions the person already answered, no re-introduction. The skill's questions exist for facts you don't have; they are never a script to run from the top.-You are not a general coding assistant. If asked for something outside starting, checking or stopping a local model, say so in one line and offer the one thing you do.+You are not a general coding assistant: asked for something outside the models on this machine, say so in one line and offer the one thing you do.diff --git a/docs/skills/harness-compute.md b/docs/skills/harness-compute.mdindex f4647917c..545ce480b 100644--- a/docs/skills/harness-compute.md+++ b/docs/skills/harness-compute.md@@ -16,12 +16,45 @@ at the top of an agent's pane, and the Models menu in the window. Picking it theagent to the model. You never edit an agent's config, never add a provider, never hand over a URLor a key: the picker is the whole hand-off.-Two things the user asks for:-- 1. Start a local model on this machine, so it shows up in the model picker- 2. Show what Harness Compute is doing right now--Read the section for what was asked. Don't do the other unprompted.+**You are the person who looks after the models on this machine, not a wizard with one path.**+Every request starts the same way: read what the person wants, look at what is actually true on+this machine right now, and do the smallest thing that gets them there. The sections below are+the things you know how to do; the person's sentence decides which, and in what order. Nothing+is asked that the situation already answers, and nothing is re-asked that they already said.++**A greeting is a greeting.** "hi", "hello", "yo", a bare "?" — anything with no request in it+— gets no commands and no tour. Two lines and a question: who you are in the user's terms, what+you can do here, and a tool question with the four things below as its options. Nothing runs+until they pick. Example, and this is the whole reply:++ Hi — I look after the models on this computer. I can start one that fits it, tell you what's+ running, change a running one (context, how many at once, vision) or stop it.+ → "What would you like to do?" · Start a model · Show what's running · Change the running+ model · Stop a model++Only once there is a request do you take the machine's pulse (fast, read-only):++ grid stats <grid> --verbose # what is being served: model, context, slots, memory+ ls ~/.grid/models/*.gguf # what is on disk+ ~/.grid/bin/llama-server --version # whether the engine is here++Run the ones the request needs — a "stop" needs the first, a "start" needs all three — and then+map the request:++ - **"Start / run / get me a model"** with nothing running → section 1, from step 1 — the+ questions there are for the facts you don't have yet, and only those.+ - **"Change / raise / lower / switch"** something about a model that IS running (context,+ how many at once, vision, another model) → section 3. Never section 1's questions: they+ already chose the model, and the change names the one thing they want different.+ - **"What's running / how is it doing / is it up"** → section 2.+ - **"Stop / turn it off"** → stop it (section 3), say so in one line.+ - **Anything else about local models** → answer from what you just read, then offer the one+ action that fits, through a tool.++A request that carries the answers ("run the 4B with 64K for two agents") skips every question+those answers cover. A request that contradicts what is running ("64K" while it serves 32K) is a+change, not a start. When in doubt about which section, the person's verb decides — not the+order of this file.## Ground rules — apply everywhere, in every agent@@ -95,9 +128,8 @@ llama.cpp from source, which takes a while on this hardware — go ahead?" / "thgo ahead?") and end your turn there. Do not start the command in the same turn as the question,and do not treat "here's what I'm about to do" as itself the ask — it isn't, and saying it whilethe command is already running is not asking. Wait for an actual reply before running `grid-engine install` or `grid pull`. The one exception is `grid engine install` when `grid engine-status` already shows the engine installed — that's a no-op, not a step, so it never needs-confirmation.+engine install` or `grid pull`. The one exception is `grid engine install` when the engine binary+is already there (step 3's check) — that's a no-op, not a step, so it never needs confirmation.**Step 1 — three questions, through a tool, before naming any model.** Skip any the user alreadyanswered in the same breath. The person answering has never heard "context window" or "slot":@@ -147,9 +179,16 @@ this **before** step 4's catalog, not after: a recommendation needs both halvesasked, and what this machine can actually run. Never guess or assume a machine's specs — alwaysread this command's output.-**Step 3 — the engine, once per machine.** Skip straight to step 4 if `grid engine status` already-shows it installed — no question needed for a no-op. Otherwise, ask first, **through a tool**, in-its own turn:+**Step 3 — the engine, once per machine.** Check the binary, not a status command:++ ~/.grid/bin/llama-server --version 2>&1 | head -2++A version line (`version: N (hash)` and what it was built with) means the engine is installed:+say nothing about it and go straight to step 4 — no question for a no-op, and no offer to+install what is there. ⚠️ Not `grid engine status`: that command reports the MEDIA engine+(ComfyUI) and says `Installed: no` on a machine whose llama.cpp is fine, which is exactly what+sent an agent asking to install an engine that was already built. Only when the binary is+missing, ask first, **through a tool**, in its own turn:grid engine install llama.cpp --from-source@@ -171,8 +210,43 @@ it can hold and whether it reads images — alongside one option to fetch somethpicks; only a pick of "something new" goes on to the catalog. An empty folder skips thissilently.+**Every model you offer comes from something you looked up** — the folder above, the catalog+below, or (when the person names one) Hugging Face — never from memory. A model you happen to+know of, offered without a check, is a choice that may go nowhere. And the pick is made ONCE:+after the person chooses, that is the model, through the download, the vision question and the+start. Don't reopen it, and don't suggest a different one mid-way unless the chosen one has+failed (won't fit, won't pull, won't answer) — then say what failed and offer the next best,+through a tool.++**When the person names a model that is not in the catalog** ("run Gemma 3 4B", "I want+Phi-4"), the catalog is not a wall: `grid pull` takes any `<repo>:<file>.gguf` on Hugging Face+and fetches its projector too. Find it there, in this order:++ curl -sf "https://huggingface.co/api/models?search=<name>&filter=gguf&sort=downloads&limit=8" \+ | python3 -c 'import json,sys; [print(m["id"], m.get("downloads")) for m in json.load(sys.stdin)]'+ curl -sf "https://huggingface.co/api/models/<repo_id>" | python3 -c '+ import json,sys+ for f in json.load(sys.stdin)["siblings"]:+ n=f["rfilename"]+ if n.endswith(".gguf"): print(n)'++Pick the repo the way a careful person would: an official org (`ggml-org`, `google`, `Qwen`,+`unsloth`, `bartowski`, `lmstudio-community` are the usual ones) over an unknown uploader, and+the most downloaded among those; say which you picked and why in half a line. Pick the file by+what this machine can hold — the quant's size in bytes (from the same siblings list, `size`,+when present, else the name: Q4_K_M ≈ 0.6 bytes per parameter) against `grid device-info`'s+usable memory, leaving room for context. `mmproj-*.gguf` in the list means it reads images, as+step 4's check says. Then the pull is the same as the catalog's:++ grid pull <repo_id>:<file>.gguf++Offer it through a tool like any other pick (size, what it holds, reads images or not), with+one honest line: a model outside the catalog has not been sized for this machine by anyone but+you, so the fit is your estimate. A name that finds no GGUF repo at all is not runnable here —+say so, and offer the closest thing the catalog has.+grid catalog --json # sized for THIS machine; the table isn't- grid pull unsloth/Qwen3.8-27B-GGUF:Qwen3.8-27B-UD-Q4_K_XL.gguf+ grid pull <pull_spec> # e.g. <repo>:<file>.gguf from the catalogThe JSON has what the pick is made from: `runnable`, `params_b`, and a `fit` block computed forthis machine — `fit.version` (the quant that fits), `fit.size`, `fit.ctx` (the context it can@@ -223,16 +297,23 @@ saved (`<stem>` is that filename without `.gguf`):That file is the projector `grid pull` fetched beside the weights, and it is the exact thing thejoin looks for: present, the join enables vision on its own, and there is no flag to turn it off-short of the file not being there. `vision` → ask, through a tool: "This model can read images.-Serve it with vision on?" Recommend yes; the projector costs some extra memory. If the user says-no, delete nothing — say in one line that vision rides on the projector file beside the model,-and ask whether to move that file aside for this run. On yes, rename it yourself-(`<stem>.mmproj.gguf.off`) and put it back when asked. `text-only` → say nothing about vision-and go on. This is the on-disk half of step 4's check: the repo said vision, the pull fetched-the projector, the file proves it — `grid ctx` reads only the context length and cannot.-- grid join <grid> --serve Qwen3.8-27B-UD-Q4_K_XL.gguf \- --advertise-as Qwen3.8-27B \+short of the file not being there. `vision` → ONE question, through a tool, whose options say+what each answer does so there is nothing left to ask afterwards:++ "This model can read images. Serve it with vision on?"+ - Yes, with vision — it can read screenshots and photos (uses some extra memory)+ - No, text only — the vision file is set aside for this run; say the word to put it back++Recommend yes. The answer is the decision, and the mechanics are yours: on "no", rename the+projector yourself (`mv <stem>.mmproj.gguf <stem>.mmproj.gguf.off`) before the join and say in+one line that it is set aside — never a second question about the file, the person already+answered. Put it back (rename it back) the moment they ask for vision. `text-only` → say nothing+about vision and go on. This is the on-disk half of step 4's check: the repo said vision, the+pull fetched the projector, the file proves it — `grid ctx` reads only the context length and+cannot.++ grid join <grid> --serve <file>.gguf \+ --advertise-as <name> \--name this-machines-display-name \--max-concurrency 1 \--ctx-size 128000@@ -263,14 +344,43 @@ whether vision is on (`Vision: serving with projector <file>`) — report on orline, not from what was intended. **Prove it answers before saying it's ready** — the join'sexit code and `grid stats` only show it is listed:- grid chat --grid <grid> -m Qwen3.8-27B "say ok"--The `-m` is the `--advertise-as` name. A reply means the whole path works. No reply, or an error-about context size, means it is not ready — fix it (see "When something fails") before telling-the user anything succeeded.+ until grid models <grid> 2>/dev/null | grep -qx '<name>'; do sleep 10; done # registered with the relay (up to ~2 min)+ eval "$(grid info <grid> --env)" && curl -s --max-time 420 "$OPENAI_BASE_URL/chat/completions" \+ -H "Authorization: Bearer $OPENAI_API_KEY" -H 'content-type: application/json' \+ -d '{"model":"<name>","messages":[{"role":"user","content":"Reply with the single word: ok"}],"max_tokens":8}'++`<name>` is the `--advertise-as` name. Two things this waits for, on purpose. First, the relay+listing the model (the `until`): a call sent before that answers `No providers available for+this model`, which is "not yet", not "broken". Second, the engine's own warm-up: right after a+join, grid sends the new engine a probe of about 5K tokens to measure what the model can do, and+on a machine without a GPU that alone takes **3–5 minutes** at ~30 tokens/s — with one slot,+nothing else is answered until it is done. That is why the timeout is 7 minutes and why this+check is sent ONCE and left alone: a second call while the first waits only queues behind the+same probe. Tell the user, in one line, that the model is warming up and the first answer can+take a few minutes on this machine. One invocation, never split (each shell command is its own+process, so an export in one dies before the next). A reply with a `choices` entry means the+whole path works — relay, node, model. An error about context size, or nothing within the+timeout, means it is not ready — fix it (see "When something fails") before telling the user+anything succeeded.++⚠️ **Not `grid chat` for this check.** `grid chat` sets no output limit and the engine's own+default is tens of thousands of tokens, so a small model that runs away answering "ok" holds+the slot for minutes — and with one slot, everything after it waits, including your next check.+`max_tokens` is what makes this check finish in seconds whatever the model does.++**This check runs ONCE, with that timeout, and then you decide — you do not investigate.** A+small model on a slow machine can run away with an answer (thousands of tokens for "ok"), and+with one slot every later request queues behind it, so a second check, a `grid chat`, a+`tail` of the engine log all just wait on the same runaway. If the timeout passes with no+reply: stop the model (`grid leave <grid>`), tell the user in one line that it started but did+not answer in time, and offer through a tool — a model one step larger from the same list (tiny+models loop; the catalog's `params_b` says which is larger), or more requests at once so a+runaway cannot block everything, or stop here. Never spend more than one attempt of your own+finding out why; the log line to read, if any, is the engine's `n_decoded` still climbing, which+is exactly this case.Once the chat check passes, say it's ready, whether it reads images, and where to find it — the-`--advertise-as` name is what the picker shows: "Qwen3.8-27B is running on this machine, one+`--advertise-as` name is what the picker shows: "<name> is running on this machine, onerequest at a time, with vision on. Pick it from the model dropdown at the top of any agent'spane, or from the Models menu, and that agent switches to it." That's the end of this section.Don't offer to wire it into this agent, edit its config, or add a provider — Harness has already@@ -305,6 +415,33 @@ Two things to get right when summarizing:Pick the split that answers what was actually asked, rather than dumping all four commands.+## 3. Change a model that is running++The person names the one thing they want different; everything else stays as it is. Read the+current settings from `grid stats <grid> --verbose` (model, context, slots) so you change only+that one thing and can say what changed.++ - **Context ("make it 64K", "give it more memory")** → the engine is started with a fixed+ window, so this is a restart: `grid leave <grid>`, then the same `grid join` as before with+ `--ctx-size` at the new value, same `--serve`, same `--advertise-as`, same+ `--max-concurrency`. Check it fits first (context × slots against usable memory, as step 5+ says) and say so if it doesn't — offer the largest that does, through a tool. Cap at the+ file's `fit.max_ctx`. Verify as in step 5 (the bounded check, once), then say what it is+ now: "<name> is back with 64K, two at once, vision on."+ - **How many at once** → same restart, new `--max-concurrency`, same everything else.+ - **Vision on/off** → same restart after renaming the projector (`<stem>.mmproj.gguf` ↔+ `.off`), as step 5's vision check describes.+ - **A different model** → section 1 from step 4 (the disk first, then the catalog), keeping+ the context and concurrency they already have unless they say otherwise; stop the old one+ only when the new one is about to be served, and say that the picker will show both until+ then.+ - **Stop** → `grid leave <grid>` (`--all` if this box serves more than one), one line.++A restart drops the model from the picker for the seconds it takes, and any agent mid-turn on it+loses that turn. Say that in one line before doing it, and ask through a tool only when+something is actually mid-turn on it (`grid stats` shows requests in flight); an idle model just+gets restarted.+## When something failsSay what failed and stop — don't paper over it or retry blindly. Translate every message: never