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.

fix(models): one Use starts a local model and moves the harness onto it

bitcoinbuilder54de8e702c87
diff --git a/cli/src/lib/localModels.spec.ts b/cli/src/lib/localModels.spec.ts
index 547a7271d..45952c595 100644
--- a/cli/src/lib/localModels.spec.ts
+++ b/cli/src/lib/localModels.spec.ts
@@ -1365,6 +1365,39 @@ describe('models other apps downloaded, started in their own app', () => {
expect(JSON.parse(await readFile(join(stateDir, 'app-engines.json'), 'utf8'))).toEqual([])
})
+ it('answers from the last scan while a slow one runs, and the list after it has the new one', async () => {
+ let scans = 0, release!: () => void
+ const models = new LocalModels({ stateDir, processEnv: { GRID_HOME: home }, run, request: request as typeof fetch, inventory,
+ appEngines: ops as unknown as AppEngineOps,
+ appModels: async () => {
+ if (++scans === 1) return [ollama]
+ await new Promise<void>(resolve => { release = resolve })
+ return [ollama, studio]
+ } })
+ expect((await models.list('home')).models.filter(m => m.app && m.app !== 'Grid').map(m => m.id)).toEqual([ollama.id])
+ // A forced read starts a scan that hangs (a busy llama-server answering --version late): the list
+ // answers at once from the last scan rather than waiting on it.
+ expect((await models.list('home', true)).models.filter(m => m.app && m.app !== 'Grid').map(m => m.id)).toEqual([ollama.id])
+ expect(scans).toBe(2)
+ release()
+ await vi.waitFor(async () => expect((await models.list('home', true)).models.some(m => m.id === studio.id)).toBe(true))
+ })
+
+ it('answers from the scan it saved when it starts again, and a scan that never answers is given up', async () => {
+ await appService().list('home')
+ let scans = 0
+ const appIds = (snapshot: Awaited<ReturnType<LocalModels['list']>>) => snapshot.models.filter(m => m.app && m.app !== 'Grid').map(m => m.id)
+ // Started again, with every scan hanging: the saved one answers at once, nothing waits on a scan.
+ const restarted = new LocalModels({ stateDir, processEnv: { GRID_HOME: home }, run, request: request as typeof fetch, inventory,
+ appEngines: ops as unknown as AppEngineOps, appScanMs: 50,
+ appModels: () => { scans++; return new Promise<AppModel[]>(() => {}) } })
+ expect(appIds(await restarted.list('home'))).toEqual([ollama.id, studio.id])
+ // That scan is given up at its deadline, the saved answer kept, and the next read starts another.
+ await new Promise(resolve => setTimeout(resolve, 80))
+ expect(appIds(await restarted.list('home', true))).toEqual([ollama.id, studio.id])
+ expect(scans).toBe(2)
+ })
+
it('takes it down again, and says so, when the app loaded it with less than 64K', async () => {
window = 16384
const models = appService()
diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.ts
index 70de8683c..9c8bce2c7 100644
--- a/cli/src/lib/localModels.ts
+++ b/cli/src/lib/localModels.ts
@@ -58,6 +58,8 @@ function freePort(): Promise<number> {
}
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
+/** The longest a scan of other apps' models is waited for (`fleet models` alone has a 60s deadline). */
+export const APP_SCAN_MS = 90_000
/** What llama.cpp answers once its GPU backend has failed an allocation — every request after. */
const OUT_OF_MEMORY = /compute error|out of memory|insufficient memory|failed to allocate/i
@@ -130,6 +132,8 @@ interface Options {
/** Models other apps downloaded here ([scanAppModels]), and the engines that start them. Absent: none. */
appModels?: () => Promise<AppModel[]>
appEngines?: AppEngineOps
+ /** How long a scan is waited for ([APP_SCAN_MS]); a test shortens it. */
+ appScanMs?: number
}
/** One concrete, machine-fitted version per model. Non-chat and unprobed offline
@@ -556,15 +560,50 @@ export class LocalModels {
await rename(temp, file)
}
- /** Models other apps downloaded here, read at most every 30s (a read walks their folders) unless [force]. */
+ /**
+ * Models other apps downloaded here, from the last scan: a scan walks their folders and asks every
+ * engine its version, which a llama-server busy serving answered in 11s [run], so nothing waits on
+ * one but the very first. Past 30s, or [force]d, a new scan starts and the list after it has it.
+ */
private async apps(force = false): Promise<AppModel[]> {
- const read = this.options.appModels
- if (!read) return []
- if (!force && this.appsRead && Date.now() - this.appsRead.at < 30_000) return this.appsRead.value
- return this.appsPending ??= read().catch(() => [] as AppModel[]).then(value => {
- this.appsRead = { at: Date.now(), value }
- return value
- }).finally(() => { this.appsPending = undefined })
+ if (!this.options.appModels) return []
+ // A daemon just started answers from the scan it saved last time: a first scan while a llama-server
+ // was busy kept the picker without these models, and held a Stop two minutes [run].
+ this.appsRead ??= await this.savedApps()
+ if (force || !this.appsRead || Date.now() - this.appsRead.at >= 30_000) void this.scanApps()
+ return this.appsRead?.value ?? this.scanApps()
+ }
+
+ /** One scan at a time, and never one without an end: a scan that does not answer in [APP_SCAN_MS] is
+ * given up and the last answer kept, so the next read starts afresh rather than waiting on it forever. */
+ private scanApps(): Promise<AppModel[]> {
+ return this.appsPending ??= Promise.race([this.options.appModels!(),
+ new Promise<never>((_, reject) => setTimeout(() => reject(new Error('scan timed out')), this.options.appScanMs ?? APP_SCAN_MS).unref())])
+ .then(async value => {
+ this.appsRead = { at: Date.now(), value }
+ await this.saveApps(value).catch(() => {})
+ return value
+ }, () => this.appsRead?.value ?? [])
+ .finally(() => { this.appsPending = undefined })
+ }
+
+ private get appsFile(): string { return join(this.options.stateDir, 'app-models.json') }
+
+ /** The last scan, as saved: read as stale, so the next read scans again. */
+ private async savedApps(): Promise<{ at: number; value: AppModel[] } | undefined> {
+ try {
+ const value = rows(JSON.parse(await readFile(this.appsFile, 'utf8'))).filter(a =>
+ str(a.id).startsWith('app:') && str(a.name) && ['ollama', 'lm-studio', 'llama.cpp'].includes(a.app) &&
+ ['ollama', 'lm-studio', 'llama.cpp', 'grid'].includes(a.engine) && str(a.ref)) as AppModel[]
+ return { at: 0, value }
+ } catch { return undefined }
+ }
+
+ private async saveApps(value: AppModel[]): Promise<void> {
+ await mkdir(this.options.stateDir, { recursive: true, mode: 0o700 })
+ const temp = `${this.appsFile}.${randomUUID()}.tmp`
+ await writeFile(temp, JSON.stringify(value), { mode: 0o600 })
+ await rename(temp, this.appsFile)
}
/** An app's model that Grid's llama.cpp serves (its app is not installed here), as a candidate whose
@@ -734,7 +773,9 @@ export class LocalModels {
// account's existing grids before resolving ownership or joining again.
await must(['--remote', 'sync'], 'Models could not be checked. Try again.')
}
- const apps = operation.modelId.startsWith('app:') ? await this.apps(true) : []
+ // The last scan has every model a person could have clicked; a model it lacks waits for a new one.
+ let apps = operation.modelId.startsWith('app:') ? await this.apps() : []
+ if (operation.modelId.startsWith('app:') && !apps.some(a => a.id === operation.modelId)) apps = await this.scanApps()
const app = apps.find(a => a.id === operation.modelId)
const started = (await readAppRecords(this.appRecordsFile)).some(r => r.modelId === operation.modelId && r.grid === grid)
if (operation.modelId.startsWith('app:') && (started || app?.engine !== 'grid')) {
diff --git a/desktop/lib/models/model_manager_controller.dart b/desktop/lib/models/model_manager_controller.dart
index f5e7989b1..b92d291a1 100644
--- a/desktop/lib/models/model_manager_controller.dart
+++ b/desktop/lib/models/model_manager_controller.dart
@@ -429,11 +429,15 @@ class ModelManagerController extends ChangeNotifier {
_panelVisible = visible;
}
- Future<void> refresh({bool force = false}) {
+ /// [local] false reads only the grid's models — what a harness can be moved onto — and not this
+ /// machine's own list, which a forced read rebuilds from every app's folders (16s once [run]).
+ Future<void> refresh({bool force = false, bool local = true}) {
final owner = machine;
- return _refreshing ??= _refresh(force: force).whenComplete(() {
- if (identical(machine, owner)) _refreshing = null;
- });
+ return _refreshing ??= _refresh(force: force, local: local).whenComplete(
+ () {
+ if (identical(machine, owner)) _refreshing = null;
+ },
+ );
}
/// Sets grid up on this machine — `grid` installed, signed in with this Harness account (its token:
@@ -476,7 +480,11 @@ class ModelManagerController extends ChangeNotifier {
}
}
- Future<void> _refresh({required bool force, bool setup = false}) async {
+ Future<void> _refresh({
+ required bool force,
+ bool setup = false,
+ bool local = true,
+ }) async {
final owner = machine;
if (owner == null ||
owner.connectionStatus != ConnectionStatus.connected ||
@@ -510,6 +518,7 @@ class ModelManagerController extends ChangeNotifier {
}
}),
(() async {
+ if (!local) return;
final revision = _actionRevision;
try {
final answer = await app.localModels(
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 8065fa71f..b02eb2460 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -287,6 +287,11 @@ class SwarmSearchController extends ChangeNotifier {
operation?.failed == true) {
return catalog.localStatusWord(local, controller: owner);
}
+ // Use under way: running is not yet the harness on it. Until it moves, the row keeps saying so —
+ // a row that turned to Use there read as a second click to make.
+ if (usingModelId == row.modelId) {
+ return local.downloaded ? 'Starting' : 'Downloading';
+ }
return modelRowAction(row) ??
(local.running
? 'Running'
@@ -760,7 +765,10 @@ class SwarmSearchController extends ChangeNotifier {
return null;
}
if (started?.running == true && operation?.active != true) {
- await models!.manager.refresh(force: true);
+ // The grid's models only: the harness moves onto one of them, and this machine's own list
+ // already says the model runs. A full forced read held the move 16s past "running" [run],
+ // with the row saying Use — and a second Use looked needed.
+ await models!.manager.refresh(force: true, local: false);
if (!current()) return null;
final machineId = _modelSelectionMachineId;
if (machineId != null) {
diff --git a/desktop/test/local_model_picker_test.dart b/desktop/test/local_model_picker_test.dart
index 99741b8d6..814a0a08e 100644
--- a/desktop/test/local_model_picker_test.dart
+++ b/desktop/test/local_model_picker_test.dart
@@ -96,6 +96,25 @@ class _LocalApp extends ModelManagerTestApp {
/// Downloads and starts finish at once, as a fast machine's would; left false, they stay under way.
bool completeDownloads = false, completeStarts = false;
+
+ /// A started model runs at once but the grid lists it only on [listHeld]: the gap between running
+ /// here and being a model a harness can move onto, which a busy machine took 16s to close.
+ bool holdListing = false;
+ String? _heldListing;
+
+ void listHeld() {
+ final name = _heldListing;
+ if (name == null) return;
+ inventory = GridModels(
+ gridName: 'home',
+ models: [
+ ...inventory.models,
+ GridModel(id: name, node: 'This Mac'),
+ ],
+ );
+ _heldListing = null;
+ }
+
final selections = <({String agent, String model})>[];
Map<String, dynamic> _with(
@@ -161,13 +180,17 @@ class _LocalApp extends ModelManagerTestApp {
};
}),
);
- inventory = GridModels(
- gridName: 'home',
- models: [
- ...inventory.models,
- GridModel(id: name, node: 'This Mac'),
- ],
- );
+ if (holdListing) {
+ _heldListing = name;
+ } else {
+ inventory = GridModels(
+ gridName: 'home',
+ models: [
+ ...inventory.models,
+ GridModel(id: name, node: 'This Mac'),
+ ],
+ );
+ }
return {
'operation': {
...answer['operation'] as Map<String, dynamic>,
@@ -511,4 +534,35 @@ void main() {
}
},
);
+
+ testWidgets(
+ 'one Use: the row says Starting until the harness is on the model, then it moves',
+ (tester) async {
+ final app = (await _localFixture())
+ ..completeStarts = true
+ ..holdListing = true;
+ try {
+ final picker = await _open(tester, app);
+ final gemma = _row(picker, 'gemma-4-12B');
+ picker.move(picker.rows.indexOf(gemma) - picker.cursor);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(seconds: 3));
+ // Running here, not yet a model the harness can move onto: never Use, which read as a second
+ // click to make.
+ expect(app.actions, [(machine: 'm', model: 'gemma', start: true)]);
+ expect(_status(tester, gemma), 'Starting');
+ expect(app.selections, isEmpty);
+ app.listHeld();
+ await tester.pump(const Duration(seconds: 3));
+ await tester.pumpAndSettle();
+ expect(app.selections, [(agent: 'a69', model: 'gemma-4-12B')]);
+ // The one start, and nothing a second time.
+ expect(app.actions, [(machine: 'm', model: 'gemma', start: true)]);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ }
+ },
+ );
}