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.

Refine Models tabs, lifecycle controls, and restart reliability (#283)

Dee9aea0332118c
diff --git a/.github/assets/models/README.md b/.github/assets/models/README.md
new file mode 100644
index 000000000..5999377f3
--- /dev/null
+++ b/.github/assets/models/README.md
@@ -0,0 +1,11 @@
+The Models screenshot uses synthetic model and account data rendered by the real Flutter panel.
+It shows pause for a running model, play for downloaded weights, and download for available models.
+
+Regenerate from `desktop/`:
+
+```sh
+HARNESS_MODELS_CAPTURE_DIR=/tmp/models-captures flutter test --no-pub test/models_panel_test.dart --plain-name 'Models ready in dark'
+cp /tmp/models-captures/dark-ready.png ../.github/assets/models/models-local.png
+```
+
+The Models desktop coverage gate is `node tool/check_models_coverage.mjs` after the focused tests run with `--coverage`.
diff --git a/.github/assets/models/models-local.png b/.github/assets/models/models-local.png
new file mode 100644
index 000000000..6c854dfb1
Binary files /dev/null and b/.github/assets/models/models-local.png differ
diff --git a/cli/src/lib/localModels.integration.spec.ts b/cli/src/lib/localModels.integration.spec.ts
index 67f2115f9..f6b7bb60e 100644
--- a/cli/src/lib/localModels.integration.spec.ts
+++ b/cli/src/lib/localModels.integration.spec.ts
@@ -43,15 +43,17 @@ import { join } from 'node:path';
const home = process.env.GRID_HOME, args = process.argv.slice(2);
const recordDir = join(home, 'run', 'engines', 'fixture-grid');
const record = join(recordDir, 'remote.json');
+const registered = join(home, 'registered');
appendFileSync(join(home, 'calls.jsonl'), JSON.stringify(args) + '\\n');
const result = value => console.log(JSON.stringify(value));
if (args[0] === 'device-info') result({ usable_bytes: 16 * 1024 ** 3, device_class: 'cpu', backend: 'cpu', memory: { total_gb: 16 } });
-else if (args.includes('ls')) result([{ grid: 'home', id: 'fixture-grid' }]);
-else if (args.includes('engines')) result(existsSync(record) ? [{ node_id: 'fixture-node', online: true, models: ['tiny.gguf'] }] : []);
+else if (args.includes('sync')) writeFileSync(registered, 'home');
+else if (args.includes('ls')) result(existsSync(registered) ? [{ grid: 'home', id: 'fixture-grid' }] : []);
+else if (args.includes('engines')) result(existsSync(record) ? [{ node_id: 'fixture-node', online: true, models: ['tiny'] }] : []);
else if (args[0] === 'pull') { mkdirSync(join(home, 'models'), { recursive: true }); process.stderr.write('42%\\r100%\\n'); writeFileSync(join(home, 'models', 'tiny.gguf'), Buffer.alloc(64)); }
else if (args[0] === 'engine') { mkdirSync(join(home, 'bin'), { recursive: true }); writeFileSync(join(home, 'bin', 'llama-server'), '#!/bin/sh\\nexit 0\\n', { mode: 0o700 }); }
-else if (args.includes('join')) { mkdirSync(recordDir, { recursive: true }); writeFileSync(record, JSON.stringify({ node_id: 'fixture-node', engines: [{ models: ['tiny.gguf'] }] })); writeFileSync(join(recordDir, 'remote.heartbeat'), ''); }
-else if (args.includes('leave')) rmSync(record);
+else if (args.includes('join')) { if (!existsSync(registered)) process.exit(1); mkdirSync(recordDir, { recursive: true }); writeFileSync(record, JSON.stringify({ node_id: 'fixture-node', engines: [{ models: ['tiny.gguf'] }] })); writeFileSync(join(recordDir, 'remote.heartbeat'), ''); }
+else if (args.includes('leave')) { rmSync(record); rmSync(registered); }
else if (args.includes('info')) console.log("export OPENAI_BASE_URL='${base}/v1'\\nexport OPENAI_API_KEY='inference-fixture'");
else process.exitCode = 2;
`, { mode: 0o700 })
@@ -72,6 +74,7 @@ else process.exitCode = 2;
expect((await service.list('home')).models[0].state).toBe('running')
const calls = (await readFile(join(gridHome, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
expect(calls.filter(args => args[0] === 'pull')).toHaveLength(1)
+ expect(calls.filter(args => args.includes('sync'))).toHaveLength(2)
expect(calls.filter(args => args[0] === 'engine')).toHaveLength(1)
expect(calls.find(args => args.includes('leave'))).toEqual(['--remote', 'leave', 'home', '--engine', 'tiny.gguf'])
expect(catalogReads).toBeGreaterThan(1)
diff --git a/cli/src/lib/localModels.spec.ts b/cli/src/lib/localModels.spec.ts
index 9e6d03a9f..89ee6500e 100644
--- a/cli/src/lib/localModels.spec.ts
+++ b/cli/src/lib/localModels.spec.ts
@@ -151,6 +151,17 @@ describe('local model discovery and lifecycle', () => {
expect((await service.list('home')).models[0].operation?.phase).toBe('done')
})
+ it('keeps a failed Grid registration refresh retryable without starting or downloading', async () => {
+ const original = run.getMockImplementation()!
+ run.mockImplementation(async (args, output) => args.includes('sync') ? { ...ok(), ok: false } : original(args, output))
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ expect((await service.list('home')).models[0].operation).toMatchObject({ phase: 'failed', stage: 'checking' })
+ expect(calls.some(args => args.includes('join') || args.includes('pull'))).toBe(false)
+ run.mockImplementation(original)
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ expect((await service.list('home')).models[0].state).toBe('running')
+ })
+
it('never offers Stop for an external endpoint or another machine', async () => {
serving = true
await writeFile(join(records, 'remote.json'), JSON.stringify({ node_id: 'local-node', engines: [{ endpoint_url: 'http://localhost:1234', models: ['Small-Q4.gguf'] }] }))
@@ -206,6 +217,30 @@ describe('local model discovery and lifecycle', () => {
expect((await fresh.list('home')).models[0].operation?.phase).toBe('done')
})
+ it.each(['current', 'legacy', 'malformed'])('preserves imported routing names across restart with %s receipts', async scenario => {
+ catalogCards = []; serving = true
+ await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(64))
+ await writeFile(join(records, 'remote.json'), JSON.stringify({ node_id: 'local-node',
+ engines: [{ models: ['Small-Q4.gguf'] }], advertise_as: ['team/my-model'] }))
+ await writeFile(join(records, 'remote.heartbeat'), '')
+ const id = (await service.list('home')).models[0].id
+ await service.act('home', id, 'stop'); await service.settled()
+ const path = join(stateDir, (await readdir(stateDir)).find(name => name.endsWith('.known.json'))!)
+ const saved = JSON.parse(await readFile(path, 'utf8'))
+ expect(saved[0].aliases).toEqual(['team/my-model'])
+ if (scenario === 'legacy') delete saved[0].aliases
+ if (scenario === 'malformed') saved[0].aliases = [42, '', '--invalid', 'invalid\nname']
+ await writeFile(path, JSON.stringify(saved))
+ const fresh = new LocalModels({ stateDir, processEnv: { GRID_HOME: home }, run, request: request as typeof fetch })
+ await fresh.act('home', id, 'start'); await fresh.settled()
+ const expectedAlias = scenario === 'current' ? 'team/my-model' : scenario === 'legacy' ? 'my-model' : null
+ const joined = calls.find(args => args.includes('join'))!
+ expect(joined.slice(11)).toEqual(expectedAlias ? ['--advertise-as', expectedAlias] : [])
+ const inference = request.mock.calls.find(([url]) => String(url).includes('chat/completions'))!
+ expect(JSON.parse(String(inference[1]?.body)).model).toBe(expectedAlias ?? 'Small-Q4.gguf')
+ expect((await fresh.list('home')).models[0].operation?.phase).toBe('done')
+ })
+
it('reuses an already downloaded fitting quant of the same model', async () => {
catalogCards[0].versions.push({ version: 'Q3', size_bytes: 48, pull_spec: 'org/Small-GGUF:Small-Q3.gguf', urls: ['https://example.test/Small-Q3.gguf'] })
await writeFile(join(home, 'models', 'Small-Q3.gguf'), Buffer.alloc(48))
@@ -228,6 +263,45 @@ describe('local model discovery and lifecycle', () => {
expect(view.models[0].requests).toBeUndefined()
})
+ it.each(['small-q4', { model: 'small-q4' }])('matches Grid’s canonical model names after start: %j', async alias => {
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ const record = JSON.parse(await readFile(join(records, 'remote.json'), 'utf8'))
+ record.meta_name = 'My laptop'
+ await writeFile(join(records, 'remote.json'), JSON.stringify(record))
+ const original = run.getMockImplementation()!
+ run.mockImplementation(async (args, output) => args.includes('engines') ? ok([{
+ name: 'My laptop', online: true, models: [alias], throughput_tok_s: 12,
+ answered: { requests: 99, window_seconds: 86400, by_model: [
+ { model: 'small-q8', requests: 95 }, { model: 'small-q4', requests: 4 },
+ ] },
+ }]) : original(args, output))
+ expect((await service.list('home')).models[0]).toMatchObject({
+ state: 'running', canStop: true, tokensPerSecond: 12, requests: 4, windowSeconds: 86400,
+ })
+ })
+
+ it('assigns an engine only to the downloaded variant when catalog filenames collide', async () => {
+ const other = card('org/Small-MTP-GGUF')
+ other.versions[0].size_bytes = 80
+ catalogCards = [other, card()]
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ const snapshot = await service.list('home')
+ expect(snapshot.models.find(m => m.id === 'org/Small-GGUF')).toMatchObject({
+ state: 'running', canStop: true, requests: 4,
+ })
+ expect(snapshot.models.find(m => m.id === other.repo_id)).toMatchObject({
+ state: 'available', canStop: false, requests: undefined, tokensPerSecond: undefined,
+ })
+ })
+
+ it('can still stop a running catalog model after its weights are removed', async () => {
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ await rm(join(home, 'models', 'Small-Q4.gguf'))
+ expect((await service.list('home')).models[0]).toMatchObject({ state: 'running', canStop: true })
+ await service.act('home', 'org/Small-GGUF', 'stop'); await service.settled()
+ expect((await service.list('home')).models[0]).toMatchObject({ state: 'available', canStop: false })
+ })
+
it('encrypts inventory and lifecycle requests and responses', () => {
for (const type of ['grid_fleet_models_list', 'grid_fleet_model_start', 'grid_fleet_model_stop']) {
expect(encryptDownFrame(type)).toBe(true); expect(encryptRpcResult(`${type}_result`)).toBe(true)
diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.ts
index 545d3f2d1..afc3cc8f1 100644
--- a/cli/src/lib/localModels.ts
+++ b/cli/src/lib/localModels.ts
@@ -15,6 +15,8 @@ const str = (v: unknown): string => typeof v === 'string' ? v : ''
const num = (v: unknown): number | undefined => typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : undefined
const key = (v: string): string => createHash('sha256').update(v).digest('hex').slice(0, 24)
const cleanName = (v: string): string => basename(v).replace(/\.gguf$/i, '').replace(/-GGUF$/i, '')
+// Grid advertises a GGUF filename as a lowercase model name without its extension.
+const modelKey = (v: string): string => v.toLowerCase().replace(/\.gguf$/, '')
const validArg = (v: string): boolean => !!v && !v.startsWith('-') && !/[\x00-\x1f]/.test(v)
export interface LocalModel {
@@ -34,6 +36,7 @@ export interface LocalModelsSnapshot {
}
interface Candidate {
id: string; name: string; pull: string; file: string; files: string[]; size: number; quant: string; context: number
+ aliases?: string[]
}
interface Owned { file: string; selector: string; aliases: string[]; nodeId: string; name: string; live: boolean; context: number; siblings: number }
interface Receipt { spec: 1; grid: string; operation?: ModelOperation }
@@ -214,7 +217,13 @@ export class LocalModels {
known = rows(JSON.parse(await readFile(path, 'utf8'))).filter(c =>
c.id === `local:${c.file}` && basename(str(c.file)) === c.file && validArg(c.file) &&
c.pull === '' && typeof c.name === 'string' && c.name.length < 256 && num(c.size) && num(c.context) && c.context <= 16384 &&
- Array.isArray(c.files) && c.files.length === 1 && c.files[0] === c.file) as Candidate[]
+ Array.isArray(c.files) && c.files.length === 1 && c.files[0] === c.file).map(c => ({
+ ...c,
+ // Older receipts kept only the displayed alias. Preserve that name
+ // when upgrading, and never forward malformed saved argv values.
+ aliases: (Array.isArray(c.aliases) ? c.aliases : [c.name])
+ .filter((alias: unknown): alias is string => typeof alias === 'string' && validArg(alias)),
+ })) as Candidate[]
} catch { known = [] }
this.knownByGrid.set(grid, known)
}
@@ -224,7 +233,8 @@ export class LocalModels {
const file = await stat(join(this.home, 'models', instance.file)).catch(() => null)
if (!file?.isFile() || !file.size) continue
known.push({ id: `local:${instance.file}`, name: cleanName(instance.aliases[0]),
- file: instance.file, files: [instance.file], pull: '', size: file.size, quant: '', context: instance.context })
+ file: instance.file, files: [instance.file], pull: '', size: file.size, quant: '', context: instance.context,
+ aliases: instance.aliases.filter(validArg) })
changed = true
}
if (changed) {
@@ -280,21 +290,28 @@ export class LocalModels {
} catch { inventoryError = 'Running models could not be checked. Try again.' }
const operation = this.active?.grid === grid ? this.active.operation : this.receipt?.grid === grid ? this.receipt.operation : undefined
const choices = [...this.candidates, ...(await this.known(grid, owned)).filter(k => !this.candidates.some(c => c.file === k.file))]
+ const downloaded = await Promise.all(choices.map(candidate => this.downloaded(candidate)))
+ // Different repositories can use the same filename for different weights.
+ // Attribute the one local engine to the complete file that is actually here.
+ // Keep a fallback so an engine can still be stopped if its file was removed.
+ const owners = new Map(owned.map(instance => [instance.file,
+ choices.find((candidate, index) => candidate.file === instance.file && downloaded[index])
+ ?? choices.find(candidate => candidate.file === instance.file)]))
const servingNode = (instance?: Owned): Record<string, any> | undefined => {
const matches = instance?.live ? nodes.filter(n => n.online === true &&
(str(n.node_id || n.id) ? str(n.node_id || n.id) === instance.nodeId :
!!instance.name && str(n.name) === instance.name) &&
instance.aliases.every(alias => (Array.isArray(n.models) ? n.models : []).some((m: unknown) =>
- str(typeof m === 'string' ? m : obj(m).model).toLowerCase() === alias.toLowerCase()))) : []
+ modelKey(str(typeof m === 'string' ? m : obj(m).model)) === modelKey(alias)))) : []
return matches.length === 1 ? matches[0] : undefined
}
- const models = await Promise.all(choices.map(async (candidate, index): Promise<LocalModel> => {
- const instance = owned.find(o => o.file === candidate.file)
+ const models = choices.map((candidate, index): LocalModel => {
+ const instance = owned.find(o => owners.get(o.file) === candidate)
const node = servingNode(instance)
const running = !!node
- const available = await this.downloaded(candidate)
+ const available = downloaded[index]
const answered = obj(node?.answered)
- const perModel = rows(answered.by_model).find(a => instance?.aliases.some(alias => alias.toLowerCase() === str(a.model).toLowerCase()))
+ const perModel = rows(answered.by_model).find(a => instance?.aliases.some(alias => modelKey(alias) === modelKey(str(a.model))))
const single = Array.isArray(node?.models) && node.models.length === 1
return { id: candidate.id, name: candidate.name, state: running ? 'running' : available ? 'downloaded' : 'available',
sizeBytes: candidate.size, quant: candidate.quant, recommended: index === 0,
@@ -304,7 +321,7 @@ export class LocalModels {
requests: running ? num(perModel?.requests) : undefined,
windowSeconds: running ? num(answered.window_seconds) : undefined,
operation: operation?.modelId === candidate.id ? operation : undefined }
- }))
+ })
for (const instance of owned.filter(o => !choices.some(c => c.file === o.file))) {
models.push({ id: `local:${instance.file}`, name: cleanName(instance.aliases[0]),
state: servingNode(instance) ? 'running' : 'available', canStart: false, canStop: !inventoryError,
@@ -345,7 +362,12 @@ export class LocalModels {
const must = async (args: string[], message: string, output?: (chunk: string) => void) => {
if (!(await this.run(args, output, 30 * 60_000)).ok) throw new ModelError(message)
}
- if (operation.action === 'start') await this.loadCatalog()
+ if (operation.action === 'start') {
+ await this.loadCatalog()
+ // Leaving the last engine removes Grid's local registration. Restore the
+ // account's existing grids before resolving ownership or joining again.
+ await must(['--remote', 'sync'], 'Models could not be checked. Try again.')
+ }
const owned = await this.owned(grid)
const candidate = [...this.candidates, ...await this.known(grid, owned)].find(c => c.id === operation.modelId)
const instance = owned.find(o => candidate ? o.file === candidate.file : operation.modelId === `local:${o.file}`)
@@ -398,11 +420,12 @@ export class LocalModels {
await must(['engine', 'install', 'llama.cpp'], 'The model engine could not start. Try again.')
}
await must(['--remote', 'join', grid, '--serve', candidate.file,
- '--max-concurrency', '1', '--ctx-size', String(candidate.context), '--reasoning-budget', '0'],
+ '--max-concurrency', '1', '--ctx-size', String(candidate.context), '--reasoning-budget', '0',
+ ...(candidate.aliases ?? []).flatMap(alias => ['--advertise-as', alias])],
'The model could not start. Try again.')
}
await change('verifying')
- await this.verify(grid, instance?.aliases[0] || candidate.file)
+ await this.verify(grid, instance?.aliases[0] || candidate.aliases?.[0] || candidate.file)
}
operation.phase = 'done'
await this.save(grid, operation)
diff --git a/desktop/lib/models/models_panel.dart b/desktop/lib/models/models_panel.dart
index dff258195..0949df2d2 100644
--- a/desktop/lib/models/models_panel.dart
+++ b/desktop/lib/models/models_panel.dart
@@ -11,6 +11,8 @@ import 'local_model.dart';
import 'model_manager_controller.dart';
import 'model_mark.dart';
+enum ModelsTab { subscriptions, local, shared }
+
class ModelsPanel extends StatefulWidget {
const ModelsPanel({
super.key,
@@ -19,21 +21,21 @@ class ModelsPanel extends StatefulWidget {
required this.onClose,
required this.onManage,
this.newModelIds = const {},
+ this.initialTab = ModelsTab.subscriptions,
});
final ModelManagerController controller;
final ModelsMenuController subscriptions;
final VoidCallback onClose, onManage;
final Set<String> newModelIds;
+ final ModelsTab initialTab;
@override
State<ModelsPanel> createState() => _ModelsPanelState();
}
-enum _Filter { all, running }
-
class _ModelsPanelState extends State<ModelsPanel> {
final _search = TextEditingController();
final _searchFocus = FocusNode(debugLabel: 'Search models');
- _Filter _filter = _Filter.all;
+ late ModelsTab _selectedTab = widget.initialTab;
ModelManagerController get controller => widget.controller;
ModelsMenuController get subscriptions => widget.subscriptions;
@override
@@ -48,15 +50,39 @@ class _ModelsPanelState extends State<ModelsPanel> {
listenable: Listenable.merge([controller, subscriptions]),
builder: (context, _) {
final query = _search.text.trim().toLowerCase();
+ final subscriptionRows = subscriptions.rows;
+ final matchingSubscriptions = subscriptionRows.where(
+ (row) => [
+ 'title',
+ 'account',
+ 'engine',
+ ].any((key) => '${row[key] ?? ''}'.toLowerCase().contains(query)),
+ );
+ final sharedSections = controller.sections.where((s) => !s.own).toList();
+ final sharedCount = sharedSections.fold(
+ 0,
+ (count, section) => count + section.models.length,
+ );
+ final matchingShared = [
+ for (final section in sharedSections)
+ (
+ name: section.name,
+ models: section.models
+ .where(
+ (model) => [
+ section.name,
+ model.id,
+ model.node,
+ ].any((text) => text.toLowerCase().contains(query)),
+ )
+ .toList(),
+ ),
+ ];
final models = controller.localModels
.where(
(m) =>
- (m.name.toLowerCase().contains(query) ||
- m.id.toLowerCase().contains(query)) &&
- switch (_filter) {
- _Filter.all => true,
- _Filter.running => m.running,
- },
+ m.name.toLowerCase().contains(query) ||
+ m.id.toLowerCase().contains(query),
)
.toList();
int rank(LocalModel m) => controller.operationFor(m)?.active == true
@@ -113,7 +139,9 @@ class _ModelsPanelState extends State<ModelsPanel> {
autofocus: true,
style: AppType.monoLabel(),
decoration: InputDecoration(
- hintText: 'Search models…',
+ hintText: _selectedTab == ModelsTab.subscriptions
+ ? 'Search subscriptions…'
+ : 'Search models…',
hintStyle: AppType.monoLabel(color: AppPalette.textFaint),
prefixIcon: Icon(
LucideIcons.search,
@@ -161,17 +189,16 @@ class _ModelsPanelState extends State<ModelsPanel> {
child: Row(
children: [
_tab(
- _Filter.all,
- 'All',
- controller.localModels.length,
+ ModelsTab.subscriptions,
+ 'Subscriptions',
+ subscriptionRows.length,
),
_tab(
- _Filter.running,
- 'Running',
- controller.localModels
- .where((m) => m.running)
- .length,
+ ModelsTab.local,
+ 'Local',
+ controller.localModels.length,
),
+ _tab(ModelsTab.shared, 'Shared', sharedCount),
],
),
),
@@ -183,6 +210,7 @@ class _ModelsPanelState extends State<ModelsPanel> {
),
Flexible(
child: SingleChildScrollView(
+ key: ValueKey(_selectedTab),
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 6,
@@ -190,133 +218,105 @@ class _ModelsPanelState extends State<ModelsPanel> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(12, 10, 12, 4),
- child: Text(
- [
- 'This computer',
- if (controller.memoryBytes case final memory?)
- '${_size(memory)} memory',
- ].join(' · '),
- style: AppType.monoMeta(
- color: AppPalette.textSecondary,
- ),
- ),
- ),
- const SizedBox(height: 4),
- if (controller.error case final error?)
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 12,
- vertical: 12,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- error,
- style: AppType.body(color: AppColors.warning),
- ),
- TextButton(
- onPressed: controller.scanning
- ? null
- : () => unawaited(
- controller.refresh(force: true),
- ),
- child: const Text('Try again'),
- ),
- ],
+ if (_selectedTab == ModelsTab.subscriptions) ...[
+ if (matchingSubscriptions.isEmpty)
+ _empty(
+ query.isEmpty
+ ? 'No subscriptions'
+ : 'No matching subscriptions',
),
- ),
- if (!controller.loaded && controller.error == null)
+ for (final row in matchingSubscriptions)
+ _subscription(row),
+ ],
+ if (_selectedTab == ModelsTab.local) ...[
Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 12,
- vertical: 28,
- ),
+ padding: const EdgeInsets.fromLTRB(12, 10, 12, 4),
child: Text(
- 'Finding models that fit…',
- style: AppType.body(color: AppColors.textSoft),
- ),
- )
- else if (models.isEmpty && controller.error == null)
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 12,
- vertical: 28,
+ [
+ 'This computer',
+ if (controller.memoryBytes case final memory?)
+ '${_size(memory)} memory',
+ ].join(' · '),
+ style: AppType.monoMeta(
+ color: AppPalette.textSecondary,
+ ),
),
- child: Text(
+ ),
+ const SizedBox(height: 4),
+ if (controller.error case final error?) _retry(error),
+ if (!controller.loaded && controller.error == null)
+ _empty('Finding models that fit…')
+ else if (models.isEmpty && controller.error == null)
+ _empty(
query.isNotEmpty
? 'No matching models'
- : switch (_filter) {
- _Filter.running => 'No models running',
- _Filter.all =>
- 'No compatible models found',
- },
- style: AppType.body(color: AppColors.textSoft),
+ : 'No compatible models found',
),
- ),
- for (final model in models) _model(model),
- if (_filter == _Filter.all &&
- query.isEmpty &&
- subscriptions.rows.isNotEmpty) ...[
- _heading('Subscriptions'),
- for (final row in subscriptions.rows)
- _subscription(row),
+ for (final model in models) _model(model),
],
- if (_filter == _Filter.all)
- for (final section in controller.sections.where(
- (s) => !s.own && s.models.isNotEmpty,
- )) ...[
- if (section.models.any(
- (m) => m.id.toLowerCase().contains(query),
- ))
- _heading('Shared · ${section.name}'),
- for (final model in section.models.where(
- (m) => m.id.toLowerCase().contains(query),
- ))
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 12,
- 14,
- 6,
- 14,
- ),
- child: Row(
- children: [
- ModelMark(model: model.id),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Text(
- model.id,
- style: AppType.label(
- color: AppPalette.textPrimary,
- height: 1.3,
+ if (_selectedTab == ModelsTab.shared) ...[
+ if (controller.models?.reachable == false)
+ _retry('Shared models are unavailable.')
+ else if (controller.models == null &&
+ controller.error != null)
+ _retry(controller.error!)
+ else if (controller.models == null)
+ _empty('Finding shared models…')
+ else if (matchingShared.every(
+ (s) => s.models.isEmpty,
+ ))
+ _empty(
+ query.isEmpty
+ ? 'No shared models'
+ : 'No matching models',
+ ),
+ for (final section in matchingShared)
+ if (section.models.isNotEmpty) ...[
+ _heading(section.name),
+ for (final model in section.models)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ 12,
+ 14,
+ 6,
+ 14,
+ ),
+ child: Row(
+ children: [
+ ModelMark(model: model.id),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ children: [
+ Text(
+ model.id,
+ style: AppType.label(
+ color: AppPalette.textPrimary,
+ height: 1.3,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- const SizedBox(height: 6),
- Text(
- model.node,
- style: AppType.monoMeta(
- color: AppPalette.textSecondary,
- height: 1.3,
+ const SizedBox(height: 6),
+ Text(
+ model.node,
+ style: AppType.monoMeta(
+ color: AppPalette.textSecondary,
+ height: 1.3,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ],
+ ],
+ ),
),
- ),
- ],
+ ],
+ ),
),
- ),
- ],
+ ],
+ ],
],
),
),
@@ -363,17 +363,18 @@ class _ModelsPanelState extends State<ModelsPanel> {
},
);
- Widget _tab(_Filter filter, String title, int count) => Padding(
+ Widget _tab(ModelsTab tab, String title, int count) => Padding(
padding: const EdgeInsets.only(right: 4),
child: Semantics(
- selected: _filter == filter,
+ selected: _selectedTab == tab,
child: TextButton(
- onPressed: () => setState(() => _filter = filter),
+ key: ValueKey('models-tab-${tab.name}'),
+ onPressed: () => setState(() => _selectedTab = tab),
style: TextButton.styleFrom(
- backgroundColor: _filter == filter
+ backgroundColor: _selectedTab == tab
? AppPalette.textPrimary.withValues(alpha: .08)
: Colors.transparent,
- foregroundColor: _filter == filter
+ foregroundColor: _selectedTab == tab
? AppPalette.textPrimary
: AppPalette.textSecondary,
textStyle: AppType.monoMeta(),
@@ -386,6 +387,27 @@ class _ModelsPanelState extends State<ModelsPanel> {
),
);
+ Widget _empty(String message) => Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 28),
+ child: Text(message, style: AppType.body(color: AppColors.textSoft)),
+ );
+
+ Widget _retry(String message) => Padding(
+ padding: const EdgeInsets.all(12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(message, style: AppType.body(color: AppColors.warning)),
+ TextButton(
+ onPressed: controller.scanning
+ ? null
+ : () => unawaited(controller.refresh(force: true)),
+ child: const Text('Try again'),
+ ),
+ ],
+ ),
+ );
+
Widget _model(LocalModel model) {
final pending = controller.pendingId == model.id;
final reported = controller.operationFor(model);
@@ -410,12 +432,21 @@ class _ModelsPanelState extends State<ModelsPanel> {
when model.running && model.windowSeconds != null)
'${requests.toInt()} ${requests == 1 ? 'request' : 'requests'} / ${_window(model.windowSeconds!)}',
].join(' · ');
- final action = model.canStop ? 'Pause' : 'Start';
+ final action = model.canStop
+ ? 'Pause'
+ : model.downloaded
+ ? 'Start'
+ : 'Download and start';
+ final icon = model.canStop
+ ? LucideIcons.pause
+ : model.downloaded
+ ? LucideIcons.play
+ : LucideIcons.download;
final tooltip = active
? status
: model.canStop
? 'Pause ${model.name} and free memory. The download is kept.'
- : 'Start ${model.name}';
+ : '$action ${model.name}';
return Padding(
padding: const EdgeInsets.fromLTRB(12, 14, 6, 14),
child: Row(
@@ -510,7 +541,7 @@ class _ModelsPanelState extends State<ModelsPanel> {
? null
: () => unawaited(controller.toggle(model)),
icon: Icon(
- model.canStop ? LucideIcons.pause : LucideIcons.play,
+ icon,
size: 17,
semanticLabel: '$action ${model.name}',
),
@@ -571,7 +602,7 @@ class _ModelsPanelState extends State<ModelsPanel> {
if (account.isNotEmpty) ...[
const SizedBox(height: 6),
Text(
- 'Account ···$account',
+ 'Account $account',
style: AppType.monoMeta(
color: AppPalette.textSecondary,
height: 1.3,
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index e024fb212..c5f9d71c5 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -264,7 +264,9 @@ class _SwarmScreenState extends State<SwarmScreen>
widget.modelsMenu ?? ModelsMenuController(remote: app.readRemoteUsage);
app.modelManager.addListener(_modelManagerChanged);
_modelsRequests = app.modelsRequests.listen((_) {
- if (mounted && _modelsOverlay == null) _toggleModels();
+ if (mounted && _modelsOverlay == null) {
+ _toggleModels(initialTab: ModelsTab.local);
+ }
});
if (!kUnderTest) {
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -1123,7 +1125,7 @@ class _SwarmScreenState extends State<SwarmScreen>
case 'restartAgent':
unawaited(_restartAgent());
case 'runLocalModel':
- _toggleModels();
+ _toggleModels(initialTab: ModelsTab.local);
case 'splitRight':
unawaited(_splitAgent(PaneResizeAxis.x));
case 'splitDown':
@@ -2153,7 +2155,7 @@ class _SwarmScreenState extends State<SwarmScreen>
}
}
- void _toggleModels() {
+ void _toggleModels({ModelsTab initialTab = ModelsTab.subscriptions}) {
if (_modelsOverlay != null) {
_closeModels();
return;
@@ -2190,7 +2192,7 @@ class _SwarmScreenState extends State<SwarmScreen>
(constraints.maxHeight -
(_native ? 0 : _tabBarHeight) -
20)
- .clamp(0, 620),
+ .clamp(0, 820),
),
child: DecoratedBox(
decoration: BoxDecoration(
@@ -2207,6 +2209,7 @@ class _SwarmScreenState extends State<SwarmScreen>
newModelIds: _toolbarNotices.newModelIds,
controller: app.modelManager,
subscriptions: _modelsMenu!,
+ initialTab: initialTab,
onClose: _closeModels,
onManage: () => unawaited(_openModelManager()),
),
@@ -3596,7 +3599,8 @@ class _SwarmScreenState extends State<SwarmScreen>
if (!_commandBarOpen && _newHarness == null)
LocalModelInvitation(
controller: app.modelManager,
- onOpen: _toggleModels,
+ onOpen: () =>
+ _toggleModels(initialTab: ModelsTab.local),
),
AgentAlertBanners(notifier: app),
],
diff --git a/desktop/test/grid_model_picker_test.dart b/desktop/test/grid_model_picker_test.dart
index ae1e7db35..3a42f446f 100644
--- a/desktop/test/grid_model_picker_test.dart
+++ b/desktop/test/grid_model_picker_test.dart
@@ -214,31 +214,21 @@ void main() {
testWidgets(
'rows can be reached and activated from the keyboard',
(tester) async {
- // ⚠️ KNOWN REGRESSION, and this test is the record of it.
- //
- // The old menu focused its first ROW as it opened, so Enter picked it. The panel focuses its
- // SEARCH field instead — which is right for typing and wrong for everything else: a text
- // field consumes up and down for its own cursor, so the rows became unreachable by keyboard
- // and Enter submitted nothing. Handing the arrows back with a `Shortcuts` override at the
- // field was tried and is in the widget; it is not enough on its own, and the remaining cause
- // has not been found. Left failing-and-named rather than deleted, because deleting it would
- // turn a regression into an absence nobody would notice.
+ // Start on a local model: choosing an already selected subscription intentionally does
+ // nothing. Down must leave search and Enter must switch to the subscription row.
var ownLogin = 0;
build(
models: const [
{'id': 'Qwen-Test', 'node': 'macbook'},
],
);
- await open(tester, onOwnLogin: () => ownLogin++);
+ await open(tester, currentModel: 'Qwen-Test', onOwnLogin: () => ownLogin++);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(ownLogin, 1);
},
- // `skip` takes a bool here; the reason is the comment above, which is where a
- // person looking at a skipped test will actually read it.
- skip: true,
);
// THREE situations, two sentences and one silence, one test each — a single test cannot cover
diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dart
index cdec80734..d29051796 100644
--- a/desktop/test/models_menu_test.dart
+++ b/desktop/test/models_menu_test.dart
@@ -460,6 +460,7 @@ void main() {
expect(app.activeSwarm.isStore, isFalse);
expect(app.allPanes, isEmpty);
expect(find.byType(ModelsPanel), findsOneWidget);
+ expect(find.text('Search models…'), findsOneWidget);
expect(app.sent, isEmpty);
await tester.pumpWidget(const SizedBox());
app.dispose();
@@ -474,7 +475,7 @@ void main() {
final app = ModelManagerTestApp(connection);
await openGridDoor(tester, app, command: 'models');
expect(find.byType(ModelsPanel), findsOneWidget);
- expect(find.text('Search models…'), findsOneWidget);
+ expect(find.text('Search subscriptions…'), findsOneWidget);
expect(connection.creations, isEmpty);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
diff --git a/desktop/test/models_panel_test.dart b/desktop/test/models_panel_test.dart
index 7e93a1e73..1a43ec4b6 100644
--- a/desktop/test/models_panel_test.dart
+++ b/desktop/test/models_panel_test.dart
@@ -37,16 +37,20 @@ class _Subscription implements UsageSource {
}
class _SubscriptionRows extends ModelsMenuController {
+ _SubscriptionRows([
+ this.entries = const [
+ {
+ 'title': 'OpenAI',
+ 'account': 'abc123',
+ 'status': '0% remaining',
+ 'remainingPercent': 0.0,
+ },
+ {'title': 'OpenAI', 'account': 'def456', 'status': 'Usage unavailable'},
+ ],
+ ]);
+ final List<Map<String, Object?>> entries;
@override
- List<Map<String, Object?>> get rows => const [
- {
- 'title': 'OpenAI',
- 'account': 'abc123',
- 'status': '0% remaining',
- 'remainingPercent': 0.0,
- },
- {'title': 'OpenAI', 'account': 'def456', 'status': 'Usage unavailable'},
- ];
+ List<Map<String, Object?>> get rows => entries;
@override
Future<void> refresh() async {}
}
@@ -64,7 +68,7 @@ void main() {
});
testWidgets(
- 'discovery, empty filters, shared models and retry all have clear states',
+ 'source tabs isolate rows, search each source, and keep counts on refresh',
(tester) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(700, 800);
@@ -87,6 +91,7 @@ void main() {
child: ModelsPanel(
controller: controller,
subscriptions: subscriptions,
+ newModelIds: const {'qwen'},
onClose: () => closed++,
onManage: () {},
),
@@ -95,17 +100,49 @@ void main() {
),
),
);
+ expect(find.text('Subscriptions 2'), findsOneWidget);
+ expect(find.text('Local 0'), findsOneWidget);
+ expect(find.text('Shared 0'), findsOneWidget);
+ expect(find.textContaining('All '), findsNothing);
+ expect(find.textContaining('Running '), findsNothing);
+ expect(find.text('Account abc123'), findsOneWidget);
+ expect(find.text('Account def456'), findsOneWidget);
+ expect(find.text('0% left'), findsOneWidget);
+ expect(find.text('This computer'), findsNothing);
+ final search = find.byKey(const ValueKey('models-search'));
+ await tester.enterText(search, 'ABC123');
+ await tester.pump();
+ expect(find.text('Account abc123'), findsOneWidget);
+ expect(find.text('Account def456'), findsNothing);
+ expect(find.text('Subscriptions 2'), findsOneWidget);
+ await tester.enterText(search, 'missing');
+ await tester.pump();
+ expect(find.text('No matching subscriptions'), findsOneWidget);
+ await tester.tap(find.byTooltip('Clear search'));
+ await tester.tap(find.text('Shared 0'));
+ await tester.pump();
+ expect(find.text('Finding shared models…'), findsOneWidget);
+ await tester.tap(find.text('Local 0'));
+ await tester.pump();
expect(find.text('Finding models that fit…'), findsOneWidget);
- app.localInventory = {'models': [], 'busy': false};
+ await tester.tap(find.text('Shared 0'));
+ app.stateOf('m')!.connectionStatus = ConnectionStatus.disconnected;
await controller.refresh();
await tester.pump();
- expect(find.text('No compatible models found'), findsOneWidget);
- expect(find.text('Account ···abc123'), findsOneWidget);
- expect(find.text('Account ···def456'), findsOneWidget);
- expect(find.text('0% left'), findsOneWidget);
- await tester.tap(find.text('Running 0'));
+ expect(
+ find.text('Connect this computer to see its models.'),
+ findsOneWidget,
+ );
+ expect(find.text('No shared models'), findsNothing);
+ app.stateOf('m')!.connectionStatus = ConnectionStatus.connected;
+ app.localInventory = {'models': [], 'busy': false};
+ await tester.tap(find.text('Try again'));
+ await tester.pump();
+ expect(find.text('No shared models'), findsOneWidget);
+ await tester.tap(find.text('Local 0'));
await tester.pump();
- expect(find.text('No models running'), findsOneWidget);
+ expect(find.text('No compatible models found'), findsOneWidget);
+ expect(find.text('Account abc123'), findsNothing);
expect(find.textContaining('Downloaded'), findsNothing);
await tester.enterText(
find.byKey(const ValueKey('models-search')),
@@ -128,7 +165,9 @@ void main() {
expect(find.byTooltip('Clear search'), findsNothing);
expect(find.text('No matching models'), findsNothing);
expect(field.focusNode!.hasFocus, isTrue);
- await tester.tap(find.text('All 0'));
+ await tester.tap(find.text('Shared 0'));
+ await tester.pump();
+ expect(find.text('No shared models'), findsOneWidget);
app.inventory = const GridModels(
gridName: 'home',
models: [],
@@ -143,21 +182,30 @@ void main() {
app.localInventory = modelInventory();
await controller.refresh(force: true);
await tester.pump();
+ expect(find.text('Local 5'), findsOneWidget);
+ expect(find.text('Shared 1'), findsOneWidget);
+ expect(find.text('Team'), findsOneWidget);
+ expect(find.text('Shared Qwen'), findsOneWidget);
+ expect(find.text('Team computer'), findsOneWidget);
+ expect(find.text('New'), findsNothing);
+ expect(find.text('Qwen3.8-27B'), findsNothing);
+ await tester.enterText(search, 'TEAM COMPUTER');
+ await tester.pump();
+ expect(find.text('Shared Qwen'), findsOneWidget);
+ await tester.enterText(search, 'missing');
+ await tester.pump();
+ expect(find.text('No matching models'), findsOneWidget);
+ await tester.tap(find.byTooltip('Clear search'));
+ await tester.tap(find.text('Local 5'));
+ await tester.pump();
expect(find.text('gemma-4-12B'), findsOneWidget);
expect(find.text('Qwen3.8-27B'), findsOneWidget);
+ expect(find.text('New'), findsOneWidget);
expect(find.text('7.3 GB'), findsOneWidget);
expect(find.text('16.2 GB'), findsOneWidget);
expect(find.textContaining(' on disk'), findsNothing);
expect(find.textContaining(' download'), findsNothing);
- await tester.enterText(
- find.byKey(const ValueKey('models-search')),
- 'shared',
- );
- await tester.pump();
- expect(find.text('Shared · Team'), findsOneWidget);
- expect(find.text('Shared Qwen'), findsOneWidget);
- expect(find.text('Team computer'), findsOneWidget);
- await tester.enterText(find.byKey(const ValueKey('models-search')), '');
+ expect(find.text('Shared Qwen'), findsNothing);
app.localReadFails = true;
await controller.refresh();
await tester.pump();
@@ -174,6 +222,16 @@ void main() {
await tester.tap(find.text('Try again'));
await tester.pump();
expect(find.text('Models are unavailable. Try again.'), findsNothing);
+ app.inventory = const GridModels.unreachable();
+ await controller.refresh(force: true);
+ await tester.tap(find.byKey(const ValueKey('models-tab-shared')));
+ await tester.pump();
+ expect(find.text('Shared models are unavailable.'), findsOneWidget);
+ expect(find.text('No shared models'), findsNothing);
+ app.inventory = const GridModels(gridName: 'home', models: []);
+ await tester.tap(find.text('Try again'));
+ await tester.pump();
+ expect(find.text('No shared models'), findsOneWidget);
await tester.tap(find.byTooltip('Close Models'));
expect(closed, 1);
expect(tester.takeException(), isNull);
@@ -182,7 +240,7 @@ void main() {
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
- testWidgets('play and pause show pending status before the acknowledgement', (
+ testWidgets('download, play and pause reflect file and engine state', (
tester,
) async {
tester.view.devicePixelRatio = 1;
@@ -196,10 +254,12 @@ void main() {
subscriptions.dispose();
app.dispose();
});
- for (final running in [false, true]) {
+ for (final state in ['available', 'downloaded', 'running']) {
+ final running = state == 'running';
app.localInventory = modelInventory(
scenario: running ? 'ready' : 'first',
);
+ (app.localInventory['models'] as List).first['state'] = state;
await controller.refresh();
app.actionReply = Completer<Map<String, dynamic>>();
await tester.pumpWidget(
@@ -219,11 +279,17 @@ void main() {
),
),
);
+ await tester.tap(find.text('Local 5'));
+ await tester.pump();
final control = find.byKey(const ValueKey('model-action-qwen'));
expect(
find.descendant(
of: control,
- matching: find.byIcon(running ? LucideIcons.pause : LucideIcons.play),
+ matching: find.byIcon(switch (state) {
+ 'running' => LucideIcons.pause,
+ 'downloaded' => LucideIcons.play,
+ _ => LucideIcons.download,
+ }),
),
findsOneWidget,
);
@@ -232,10 +298,20 @@ void main() {
find.byTooltip(
running
? 'Pause Qwen3.8-27B and free memory. The download is kept.'
- : 'Start Qwen3.8-27B',
+ : state == 'downloaded'
+ ? 'Start Qwen3.8-27B'
+ : 'Download and start Qwen3.8-27B',
),
findsOneWidget,
);
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('model-action-gemma')),
+ matching: find.byIcon(LucideIcons.play),
+ ),
+ findsOneWidget,
+ );
+ expect(find.byTooltip('Start gemma-4-12B'), findsOneWidget);
await tester.tap(control);
await tester.pump();
expect(find.text(running ? 'Stopping' : 'Starting'), findsOneWidget);
@@ -272,6 +348,57 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
+ testWidgets('source changes preserve downloads and open at the top', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(700, 420);
+ addTearDown(tester.view.reset);
+ final app = ModelManagerTestApp(ModelManagerConnection());
+ final controller = ModelManagerController(app, poll: false);
+ final subscriptions = _SubscriptionRows([]);
+ addTearDown(() {
+ controller.dispose();
+ subscriptions.dispose();
+ app.dispose();
+ });
+ await controller.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ModelsPanel(
+ controller: controller,
+ subscriptions: subscriptions,
+ initialTab: ModelsTab.local,
+ onClose: () {},
+ onManage: () {},
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.byKey(const ValueKey('model-action-qwen')));
+ await tester.pump();
+ expect(find.text('Downloading · 42%'), findsOneWidget);
+ await tester.drag(
+ find.byKey(const ValueKey(ModelsTab.local)),
+ const Offset(0, -500),
+ );
+ await tester.pump(const Duration(seconds: 1));
+ expect(find.text('Downloading · 42%').hitTestable(), findsNothing);
+ await tester.tap(find.text('Subscriptions 0'));
+ await tester.pump();
+ expect(find.text('No subscriptions').hitTestable(), findsOneWidget);
+ expect(find.text('Downloading · 42%'), findsNothing);
+ await tester.tap(find.text('Local 5'));
+ await tester.pump();
+ expect(find.text('Downloading · 42%').hitTestable(), findsOneWidget);
+ expect(app.actions, hasLength(1));
+ expect(controller.busy, isTrue);
+ expect(find.byType(CircularProgressIndicator), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
testWidgets(
'the one-time invitation leads to discovery and verified readiness explains selection',
(tester) async {
@@ -387,6 +514,9 @@ void main() {
),
),
);
+ await tester.ensureVisible(find.text('Local 5'));
+ await tester.tap(find.text('Local 5'));
+ await tester.pump();
await tester.runAsync(() async {
for (final asset in [
'assets/model-icons/qwen.png',
@@ -412,12 +542,11 @@ void main() {
if (scenario == 'downloading') {
expect(find.text('Downloading · 42%'), findsOneWidget);
expect(
- tester
- .widget<LinearProgressIndicator>(
- find.byType(LinearProgressIndicator).first,
- )
- .value,
- .42,
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is LinearProgressIndicator && widget.value == .42,
+ ),
+ findsOneWidget,
);
}
if (scenario == 'ready') {
@@ -465,9 +594,11 @@ void main() {
expect(find.text('Qwen3.8-27B'), findsNothing);
}
if (scenario == 'ready') {
- await tester.tap(find.text('Running 1'));
+ await tester.tap(find.text('Subscriptions 1'));
await tester.pump();
- expect(find.text('Qwen3.8-27B'), findsOneWidget);
+ expect(find.text('OpenAI'), findsOneWidget);
+ expect(find.text('76% left'), findsOneWidget);
+ expect(find.text('Qwen3.8-27B'), findsNothing);
expect(find.text('gemma-4-12B'), findsNothing);
}
await tester.tap(find.text('Manage models'));
@@ -499,6 +630,17 @@ void main() {
app.stateOf('m')!.agents = [
const Agent(id: 'work', name: 'Build the next thing', engine: 'codex'),
];
+ app.localInventory['models'] = [
+ ...app.localInventory['models'] as List,
+ for (var i = 0; i < 8; i++)
+ {
+ 'id': 'extra-$i',
+ 'name': 'Additional model $i',
+ 'state': 'available',
+ 'sizeBytes': 4 * 1024 * 1024 * 1024,
+ 'canStart': true,
+ },
+ ];
final session = terminal('work', [])..agentName = 'Build the next thing';
session.terminal.write(
' Ready when you are.\r\n\r\n'
@@ -509,11 +651,12 @@ void main() {
final projects = SwarmProjectStore();
final usage = UsageController(sources: [_Subscription()], autoStart: false);
final subscriptions = ModelsMenuController(usage: usage);
+ var appDisposed = false;
addTearDown(() {
subscriptions.dispose();
usage.dispose();
projects.dispose();
- app.dispose();
+ if (!appDisposed) app.dispose();
});
final boundary = GlobalKey();
await tester.pumpWidget(
@@ -534,6 +677,25 @@ void main() {
final tab = app.activeSwarmId;
final panes = app.panes.map((pane) => pane.id).toList();
final button = find.byKey(const ValueKey('swarm-models-button'));
+ app.modelManager.start();
+ await app.modelManager.refresh();
+ await tester.pump();
+ expect(find.text('Explore models'), findsOneWidget);
+ await tester.tap(find.text('Explore models'));
+ await tester.pump();
+ expect(find.text('Qwen3.8-27B'), findsOneWidget);
+ expect(find.text('Search models…'), findsOneWidget);
+ expect(tester.getSize(find.byType(ModelsPanel)).height, greaterThan(620));
+ expect(tester.getRect(find.byType(ModelsPanel)).bottom, lessThan(760));
+ tester.view.physicalSize = const Size(1200, 480);
+ await tester.pump();
+ expect(tester.getRect(find.byType(ModelsPanel)).bottom, lessThan(480));
+ expect(find.text('Manage models').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ tester.view.physicalSize = const Size(1200, 760);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
await tester.tap(button);
await tester.pump();
await tester.runAsync(() async {
@@ -562,6 +724,7 @@ void main() {
lessThan(tester.getRect(find.byTooltip('Harnesses')).left),
);
expect(find.byType(Dialog), findsNothing);
+ expect(find.text('Search subscriptions…'), findsOneWidget);
expect(find.text('Run AI on this computer'), findsNothing);
expect(app.activeSwarmId, tab);
expect(app.panes.map((pane) => pane.id), panes);
@@ -591,5 +754,7 @@ void main() {
expect(app.activeSwarmId, tab);
expect(app.panes.map((pane) => pane.id), panes);
await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ appDisposed = true;
});
}
diff --git a/desktop/tool/check_models_coverage.mjs b/desktop/tool/check_models_coverage.mjs
new file mode 100644
index 000000000..60b65fcd3
--- /dev/null
+++ b/desktop/tool/check_models_coverage.mjs
@@ -0,0 +1,23 @@
+// Run the Models tests with --coverage, then check the feature's four modules.
+import { readFileSync } from 'node:fs'
+
+const expected = new Set([
+ 'local_model.dart',
+ 'model_manager_controller.dart',
+ 'model_mark.dart',
+ 'models_panel.dart',
+])
+let covered = 0, total = 0
+for (const record of readFileSync(process.argv[2] ?? 'coverage/lcov.info', 'utf8').split('end_of_record')) {
+ const path = record.match(/SF:(.*)/)?.[1]
+ if (!path?.includes('/models/')) continue
+ const name = path.split('/').at(-1)
+ if (!expected.delete(name)) continue
+ const found = Number(record.match(/LF:(\d+)/)?.[1])
+ const hit = Number(record.match(/LH:(\d+)/)?.[1])
+ if (!found || hit !== found) throw new Error(`${name}: ${hit}/${found} lines; expected 100%`)
+ total += found
+ covered += hit
+}
+if (expected.size) throw new Error(`Missing Models coverage: ${[...expected].join(', ')}`)
+console.log(`Models desktop: ${covered}/${total} lines (100%) across four feature modules.`)