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.

Unify model and machine management in Cmd-P (#358)

Deea3504cca1b63
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 46076083d..0379f2010 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -26,7 +26,7 @@ import { STRICT_DOWN_TYPES } from './lib/e2ee/applicationFrames.js'
describe('local model lifecycle RPCs', () => {
afterEach(() => vi.restoreAllMocks())
- it.each(['grid_fleet_models_list', 'grid_fleet_model_start', 'grid_fleet_model_stop'])('dispatches %s and returns its correlated result', async type => {
+ it.each(['grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])('dispatches %s and returns its correlated result', async type => {
const socket = new BackendSocket('fixture')
socket.setHarnessGridName('home')
const frames: any[] = []
@@ -37,7 +37,7 @@ describe('local model lifecycle RPCs', () => {
await vi.waitFor(() => expect(frames.some(frame => frame.type === `${type}_result`)).toBe(true))
expect(frames.find(frame => frame.type === `${type}_result`).payload.requestId).toBe('models-rpc')
if (type === 'grid_fleet_models_list') expect(list).toHaveBeenCalledWith('home', true)
- else expect(act).toHaveBeenCalledWith('home', 'fixture/model', type.endsWith('start') ? 'start' : 'stop')
+ else expect(act).toHaveBeenCalledWith('home', 'fixture/model', type.endsWith('download') ? 'download' : type.endsWith('start') ? 'start' : 'stop')
await socket.stop()
})
@@ -62,7 +62,7 @@ describe('local model lifecycle RPCs', () => {
it('rejects unencrypted remote lifecycle requests before reaching the model service', async () => {
const socket = new BackendSocket('fixture')
const act = vi.spyOn(LocalModels.prototype, 'act')
- for (const type of ['grid_fleet_model_start', 'grid_fleet_model_stop']) {
+ for (const type of ['grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop']) {
await (socket as any).dispatchDown({ type, payload: { requestId: 'unsafe', modelId: 'fixture/model' } }, 'remote')
}
expect(act).not.toHaveBeenCalled()
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index b0a31f181..12d932652 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1660,13 +1660,14 @@ export class BackendSocket {
.catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))
return
case 'grid_fleet_models_list':
+ case 'grid_fleet_model_download':
case 'grid_fleet_model_start':
case 'grid_fleet_model_stop': {
// A daemon-owned operation survives panel closure and a lost reply.
// Keep hardware/catalog/network reads off the ordered terminal queue.
void this.resolveGridName().then(async grid => type === 'grid_fleet_models_list'
? this.localModels.list(grid, payload.refresh === true)
- : this.localModels.act(grid, payload.modelId, type === 'grid_fleet_model_start' ? 'start' : 'stop'))
+ : this.localModels.act(grid, payload.modelId, type === 'grid_fleet_model_download' ? 'download' : type === 'grid_fleet_model_start' ? 'start' : 'stop'))
.then(result => reply(type, requestId, { ...result }))
.catch(() => reply(type, requestId, { error: 'Models are unavailable. Try again.' }))
return
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index a643ded5e..a9bd0b167 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -12,7 +12,7 @@ import { SHARE_REQUEST_TYPES, SHARE_RESULT_TYPES } from '../../sharing/protocol.
import { VIEWER_DOWN_TYPES } from '../viewerWire.js'
const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'grid_fleet_cancel',
- 'grid_fleet_models_list', 'grid_fleet_model_start', 'grid_fleet_model_stop'])
+ 'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])
const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))
const MACHINE_REQUESTS = new Set(['git_project_info', 'git_pull_request', 'machine_resources', 'api_connections'])
const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
diff --git a/cli/src/lib/localModels.spec.ts b/cli/src/lib/localModels.spec.ts
index 9b820ec07..2945602ff 100644
--- a/cli/src/lib/localModels.spec.ts
+++ b/cli/src/lib/localModels.spec.ts
@@ -371,7 +371,7 @@ describe('local model discovery and lifecycle', () => {
})
it('encrypts inventory and lifecycle requests and responses', () => {
- for (const type of ['grid_fleet_models_list', 'grid_fleet_model_start', 'grid_fleet_model_stop']) {
+ for (const type of ['grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop']) {
expect(encryptDownFrame(type)).toBe(true); expect(encryptRpcResult(`${type}_result`)).toBe(true)
}
})
@@ -1090,3 +1090,46 @@ describe("a model is labelled with the machine's name as Harness shows it", () =
expect((await named.list('home', true)).models[0].operation?.phase).toBe('done')
})
})
+
+
+describe('download without starting', () => {
+ it('stores the weights without waking a grid, installing an engine, or sending a prompt', async () => {
+ gridState = 'asleep'
+ const result = await service.act('home', 'org/Small-GGUF', 'download')
+ await service.settled()
+ expect(result.operation).toMatchObject({ action: 'download', phase: 'done' })
+ expect(calls.filter(args => args[0] === 'pull')).toHaveLength(1)
+ expect(calls.some(args => args.includes('sync') || args.includes('join') || args.includes('start') || args.includes('install'))).toBe(false)
+ expect(request.mock.calls.some(([url]) => String(url).includes('chat/completions'))).toBe(false)
+ expect(gridState).toBe('asleep')
+ expect((await service.list('home')).models[0]).toMatchObject({ state: 'downloaded', canStart: true, canStop: false })
+ expect((await service.list('home')).supportsDownload).toBe(true)
+ })
+
+ it('a download request for a running model never runs another reply test', async () => {
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ calls.length = 0; request.mockClear()
+ const result = await service.act('home', 'org/Small-GGUF', 'download'); await service.settled()
+ expect(result.operation?.phase).toBe('done')
+ expect(serving).toBe(true)
+ expect(calls.some(args => args.includes('join') || args.includes('pull') || args.includes('sync'))).toBe(false)
+ expect(request.mock.calls.some(([url]) => String(url).includes('chat/completions'))).toBe(false)
+ })
+
+ it('keeps failed downloads retryable and starts only after a separate Start', async () => {
+ downloadFails = true
+ const first = await service.act('home', 'org/Small-GGUF', 'download')
+ await service.settled()
+ expect(first.operation?.phase).toBe('failed')
+ expect(serving).toBe(false)
+ downloadFails = false
+ await service.act('home', 'org/Small-GGUF', 'download')
+ await service.settled()
+ expect(serving).toBe(false)
+ const pulls = calls.filter(args => args[0] === 'pull').length
+ await service.act('home', 'org/Small-GGUF', 'start')
+ await service.settled()
+ expect(serving).toBe(true)
+ expect(calls.filter(args => args[0] === 'pull')).toHaveLength(pulls)
+ })
+})
diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.ts
index 1f9f0bd2e..3d11cd02e 100644
--- a/cli/src/lib/localModels.ts
+++ b/cli/src/lib/localModels.ts
@@ -69,7 +69,7 @@ export interface LocalModel {
gridAsleep?: boolean
}
export interface ModelOperation {
- id: string; modelId: string; action: 'start' | 'stop'; phase: 'running' | 'done' | 'failed'
+ id: string; modelId: string; action: 'download' | 'start' | 'stop'; phase: 'running' | 'done' | 'failed'
stage: 'checking' | 'downloading' | 'starting' | 'verifying' | 'stopping'
progress?: number; error?: string; updatedAt: string
}
@@ -80,6 +80,7 @@ export interface LocalModelsSnapshot {
* with a warning in `error` arrived as no list at all and the Local tab read 0. */
notice?: string
observedAt: string; busy: boolean
+ supportsDownload?: boolean
}
interface Candidate {
id: string; name: string; pull: string; file: string; files: string[]; size: number; quant: string
@@ -484,7 +485,7 @@ export class LocalModels {
}
const value: LocalModelsSnapshot = { models, memoryBytes: num(obj(this.device.memory).total_gb) === undefined ? undefined : this.device.memory.total_gb * GiB,
hardware: str(obj(this.device.machine).model || obj(this.device.cpu).brand), notice: inventoryError || this.catalogError,
- observedAt: new Date().toISOString(), busy: !!this.active }
+ observedAt: new Date().toISOString(), busy: !!this.active, supportsDownload: true }
this.cached = { grid, at: Date.now(), value }
this.runningAtLastRead.set(grid, new Set(models.filter(model => model.state === 'running').map(model => model.id)))
return value
@@ -497,11 +498,11 @@ export class LocalModels {
/** A repeated click or lost RPC acknowledgement joins the same operation.
* A different model waits: starts/stops must not race on the machine's budget. */
- async act(grid: string | null, modelId: unknown, action: 'start' | 'stop'): Promise<{ operation?: ModelOperation; error?: string }> {
+ async act(grid: string | null, modelId: unknown, action: 'download' | 'start' | 'stop'): Promise<{ operation?: ModelOperation; error?: string }> {
if (!grid || typeof modelId !== 'string') return { error: 'The model is unavailable. Refresh and try again.' }
if (this.active) return this.active.grid === grid && this.active.operation.modelId === modelId && this.active.operation.action === action
- ? { operation: this.active.operation } : { error: 'Wait for the current model to finish starting or stopping.' }
- const operation: ModelOperation = { id: randomUUID(), modelId, action, stage: action === 'start' ? 'checking' : 'stopping', phase: 'running', updatedAt: new Date().toISOString() }
+ ? { operation: this.active.operation } : { error: 'Wait for the current model operation to finish.' }
+ const operation: ModelOperation = { id: randomUUID(), modelId, action, stage: action === 'stop' ? 'stopping' : 'checking', phase: 'running', updatedAt: new Date().toISOString() }
// Reserve before any await; independent RPCs may arrive on separate connections.
const active = { grid, operation, done: Promise.resolve() }
this.active = active
@@ -523,8 +524,8 @@ 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 !== 'stop') 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.')
@@ -543,16 +544,18 @@ export class LocalModels {
if (!instance) {
// The pinned Grid runtime respawns its union when adding --serve.
// Do not interrupt existing engines as a side effect of a simple Start.
- if (this.blockers.has(grid)) throw new ModelError(this.blockers.get(grid)!)
- // Recheck the machine immediately before downloading or allocating.
- const currentDevice = obj(await this.json(['device-info', '--json']))
- const budget = num(currentDevice.usable_bytes) ?? 0
- if (candidate.pull) {
- const current = compatibleModels(await this.catalog({ ...currentDevice, usable_bytes: Math.max(0, budget) })).find(c => c.id === candidate.id)
- if (!current || current.size < candidate.size) throw new ModelError('Stop a running model to make room, then try again.')
- candidate.context = Math.min(candidate.context ?? Infinity, current.context ?? Infinity)
- } else if (candidate.size * 1.25 + 2 * GiB > budget) {
- throw new ModelError('Stop a running model to make room, then try again.')
+ if (operation.action === 'start') {
+ if (this.blockers.has(grid)) throw new ModelError(this.blockers.get(grid)!)
+ // Recheck the machine immediately before downloading or allocating.
+ const currentDevice = obj(await this.json(['device-info', '--json']))
+ const budget = num(currentDevice.usable_bytes) ?? 0
+ if (candidate.pull) {
+ const current = compatibleModels(await this.catalog({ ...currentDevice, usable_bytes: Math.max(0, budget) })).find(c => c.id === candidate.id)
+ if (!current || current.size < candidate.size) throw new ModelError('Stop a running model to make room, then try again.')
+ candidate.context = Math.min(candidate.context ?? Infinity, current.context ?? Infinity)
+ } else if (candidate.size * 1.25 + 2 * GiB > budget) {
+ throw new ModelError('Stop a running model to make room, then try again.')
+ }
}
if (!await this.downloaded(candidate)) {
if (!candidate.pull) throw new ModelError('The downloaded file is no longer available. Open Model Manager to restore it.')
@@ -572,6 +575,14 @@ export class LocalModels {
await progressWrites
if (!await this.downloaded(candidate)) throw new ModelError('The download is incomplete. Start again to resume.')
}
+ // A download only stores the weights. It must never start/wake a grid,
+ // install an engine, allocate model memory, or send a test message.
+ if (operation.action === 'download') {
+ operation.phase = 'done'
+ delete operation.progress
+ await this.save(grid, operation)
+ return
+ }
await change('starting')
// A grid that is down refuses a join outright ("The model could not start"), and `sync`
// above restores its registration, not its process. Bring it up the way its own refusal
@@ -618,7 +629,7 @@ export class LocalModels {
? `This computer does not have the memory to run ${candidate.name} with a 64K context. Close some apps, or choose a smaller model.`
: 'The model could not start. Try again.')
}
- } else if (this.runningAtLastRead.get(grid)?.has(operation.modelId)) {
+ } else if (operation.action === 'download' || this.runningAtLastRead.get(grid)?.has(operation.modelId)) {
// Already serving when last read, and nothing was started: nothing to check. The reply test is an
// inference THROUGH the grid (so is the served-window read) — on a sleeping grid it would start it,
// and the platform then holds it up for hours, for a stray click (grid-reads-without-waking 03).
diff --git a/desktop/design/images/terminal-api-inline.png b/desktop/design/images/terminal-api-inline.png
new file mode 100644
index 000000000..5c2d62274
Binary files /dev/null and b/desktop/design/images/terminal-api-inline.png differ
diff --git a/desktop/design/images/terminal-machine-connect-inline.png b/desktop/design/images/terminal-machine-connect-inline.png
new file mode 100644
index 000000000..8889eebc2
Binary files /dev/null and b/desktop/design/images/terminal-machine-connect-inline.png differ
diff --git a/desktop/design/images/terminal-model-management.png b/desktop/design/images/terminal-model-management.png
new file mode 100644
index 000000000..d21a6f8ec
Binary files /dev/null and b/desktop/design/images/terminal-model-management.png differ
diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.md
index 62827b96e..e13c91ec7 100644
--- a/desktop/design/new-harness-entry-rules.md
+++ b/desktop/design/new-harness-entry-rules.md
@@ -19,6 +19,8 @@ Up/Down moves between fields and automatically reveals that field's chooser to
the right, without moving the form. Right, typing, or Enter moves keyboard focus
into the chooser. Enter accepts a value and returns focus to New Harness; a
second Enter launches. Escape discards the search and returns to the form.
+Tab and Shift-Tab switch between the form and its chooser without applying a
+choice; Up/Down navigates the active pane, matching Cmd-P and Cmd-I.
There is no summary pane. Agent combines coding agents and specialized
harnesses in one list. Choosing Blender opens a compatible coding-agent list
in the chooser. Project
@@ -50,18 +52,18 @@ The Store and orchestration tabs cannot host a terminal pane. Generic creation
from either uses a new tab. Command-bar requests keep the workspace context and
apply any agent or machine explicitly named by the request.
-The unified picker has search and results on the left, with a read-only preview
-on the right. It has no action strip or keyboard footer. Enter opens a result;
-machines and projects drill into their session lists. Cmd-P never offers New
+The unified picker has search and results on the left, with details and inline
+management controls on the right. Enter opens a harness, uses or gets a model,
+or focuses a machine's controls. Projects drill into their session lists. Cmd-P never offers New
Harness, including when no sessions match or a scoped list is empty. Cmd-N opens
creation explicitly. Cmd-Shift-P searches named
commands for the selected resource and returns to the same search after an action
or cancellation. Each item action names its target, which is revalidated before
execution. Filters and sorting are explicit commands, with no More menu.
-Workspace panes remain terminals, with viewers as the only exception. Do not add
-model or API details tabs: status stays in the picker preview, Model Manager opens
-as a terminal session, and API configuration uses the existing edit dialog.
+Workspace panes remain terminals, with viewers as the only exception. Model,
+machine, and API management stays inside the picker. Tab switches panes;
+arrows navigate within the active pane and Enter activates the focused item.
## Harness and agent choices
diff --git a/desktop/design/terminal-dialogs.md b/desktop/design/terminal-dialogs.md
index 9835e0256..6f8aee505 100644
--- a/desktop/design/terminal-dialogs.md
+++ b/desktop/design/terminal-dialogs.md
@@ -130,8 +130,51 @@ metrics and blank-row spacing; warnings are readable text in semantic colors.
Cmd-P opens with no selected row. The preview area shows the type hints as plain,
muted text: `@ machines`, `# projects`, `: models`,
`* store`, and `> commands`.
-Typing selects the first match and replaces the hints with its preview. Arrows,
-Tab, and pointer movement can also select a row. Clearing the root search returns
+Each hint is also a plain-text button: clicking it inserts the prefix into the
+same editor and keeps typing focus there. Selected harnesses open with Enter.
+Machines use Enter to **Manage**: focus moves to their controls without invoking
+one. Models use four sections: **Subscriptions**, **APIs**, **Your local AI
+models**, and **Shared with you**. Headers are plain muted text and never take
+selection. Put **[ Add ]** within APIs. Your local AI models puts downloaded
+models first, followed by models served on the user's machines. Keep the
+undownloaded catalog collapsed behind **[ Get models ]**; Enter expands it in
+place and selects the first catalog row. **[ Hide catalog ]** collapses it.
+Explicit searches also include matching catalog models. Shared rows show only
+the model and sharing machine's label, separated by ` · `. Filtering preserves
+the groups.
+
+A plain right-aligned **Use** identifies a model the current pane can use;
+**Get** identifies a model that can be downloaded. Other model rows are dimmed,
+remain selectable for inspection, and have no action badge. Enter does nothing
+on these rows; it must never silently become Manage. Show the reason in the
+preview when it helps. Subscription names include the account label; only an
+account compatible with the current harness and available on its machine can
+say Use. Include actionable labels in accessibility text.
+
+From a live harness, both Cmd-I and Cmd-P's model scope use Enter to **Use** a
+served model, installed local model, or compatible subscription. Starting
+installed weights happens once; progress stays in the picker, and the pane
+switches only when the model is served. Closing the picker cancels the pending
+switch while startup continues on its host. **Get** prepares an undownloaded
+model on its host and stays in the picker. Pin selection to the pane that
+opened it; changing focus must never switch another pane's model.
+
+Cmd-N, Cmd-P, and Cmd-I share pane navigation: **Tab/Shift-Tab switch between
+the left and right panes**, without selecting a value or running an action.
+**Up/Down move within the active pane**: fields or choices in Cmd-N, results or
+controls in Cmd-P. **Enter activates the highlighted item**. In Cmd-N, Enter
+on a field opens its choices; Enter on a choice applies it and selects New
+Harness. Tab returns to the same field without applying a choice. In Cmd-P, Enter on a usable model
+uses it, on a Get row gets it, on a machine enters management, and on a harness
+opens it. Arrow keys walk controls while the right pane owns focus; they must
+not change the resource behind them. Left/Right retain normal cursor movement
+in text fields, and move between adjacent buttons. Enter/Space activate focused
+buttons. Escape backs out of an inline form, then returns to search while
+preserving the query and selection. Hints use the live keymap. Only the active
+pane shows a selection highlight.
+Typing selects the first match and replaces the hints with its preview. Arrows
+and pointer movement can also select a row. A pointer cannot change the resource
+while its management controls own keyboard focus. Clearing the root search returns
to the hints; live inventory updates must not choose a row for the user. Enter
does nothing until a row is selected. Keep the input and list in place throughout.
Cmd-P has no New Harness row, including in machine and project session lists.
@@ -249,3 +292,55 @@ Reuse the relevant existing checks:
When checking a native build, restart into the rebuilt app before judging the
result. An existing process does not pick up a new build automatically.
+
+## Manage machines and models inside Cmd-P
+
+Place compact facts and controls together at the top of the preview. This
+computer has `[ Password ] [ Rename ]`; remote machines have `[ Connect ]
+[ Rename ] [ Delete ]`, with Connect only when linking is needed. Password opens
+the password form alone. Delete retains the account-removal confirmation. Show
+connection state, harness count, and real CPU/RAM readings; refresh resource
+readings while the machine picker is visible and the app is in the foreground.
+Do not add a View harnesses, Linked machines, Refresh, or Actions button to this
+management pane. Keep the controls on one row, wrapping only when needed.
+
+Connect, Rename, Password, and Delete edit or confirm **inside the right pane**;
+never cover Cmd-P with a second dialog. Keep the search and machine list in
+place. Cancel/Escape returns to the selected machine's controls. Pending
+operations survive closing their editor, and errors stay beside the fields.
+Deletion and password clearing start with Cancel focused.
+
+With no machine name typed, order machines by the next useful action: online
+machines needing a connection, this computer, other connected machines, then
+offline machines. Sort names naturally within each group. A live status change
+may reorder rows but must preserve the selected machine's identity. Typed
+queries retain match relevance. Put **Add machine** after the machine rows.
+It explains installation on the other computer, sign-in to the same account,
+and setting its password. App and CLI open their setup instructions in the
+same right pane; copying CLI commands never executes them on this computer.
+
+Local models show their name with quantization once, host and model-file size,
+and measured tokens/sec and request count with its period when available.
+Include inventory from every connected, linked machine in the account. Resolve
+Grid hostnames through the hostname on the Harness machine record, then use
+that machine's own model IDs and capabilities for controls. Display its Harness
+name (for example, M2), and keep its Grid hostname (mac.lan) searchable. Unlinked,
+offline, unknown, and shared hosts must not inherit another machine's controls.
+Reuse existing operation progress/failure labels; omit redundant normal-state
+labels such as Available. Show quantization once beside the name when known,
+including quantization explicitly present in an imported GGUF filename. Do not
+guess it from the model family or file size.
+
+Local models have one contextual button: **[ Get ]** before download,
+**[ Use ]** when installed and startable, or **[ Stop ]** when an owned process
+can be stopped. A running model's list action remains Use; Stop requires
+activating its button. Unavailable actions are dim and cannot receive focus.
+On hosts that support a separate download, Get only saves the files. Older
+hosts prepare models through their existing combined download/start action;
+explain `Downloads and starts on <machine>.` before Get. Use starts installed
+weights when necessary, then selects the model for the original harness.
+
+API provider selection, credential editing, validation, saving, and deletion
+stay in the picker's right pane. Keep keys masked by default; do not return
+stored secrets to the editor. Errors and progress appear in place. Leaving a
+pending form must not let its eventual reply reopen it or change the selection.
diff --git a/desktop/design/terminal-review-checklist.md b/desktop/design/terminal-review-checklist.md
index 852589875..8b7c88607 100644
--- a/desktop/design/terminal-review-checklist.md
+++ b/desktop/design/terminal-review-checklist.md
@@ -189,9 +189,24 @@ Escape or Cmd-Shift-J closes the experimental prompt.
tabs, the selected one should remain visible. A manually renamed tab
should keep its name when panes are added.
16. **Arrange panes.** Use Cmd-H/J/K/L to focus directionally,
- Cmd-Shift-arrows to move a pane, Cmd-Enter to zoom/restore, and Cmd-; to
- return to the previous pane. Moves should preserve the other panes and
- the running sessions.
+ Cmd-Shift-arrows to move a pane, and Cmd-Enter to zoom/restore. Run Return
+ to the last pane to switch back. Moves should preserve the other panes and
+ the running sessions. Cmd-I opens Models in Cmd-P with `:` already entered.
+ Models have Subscriptions, APIs, Your local AI models, and Shared with you sections,
+ with downloaded models first in Your local AI models. Undownloaded models
+ appear when expanding [ Get models ] or searching explicitly; [ Hide catalog ]
+ collapses them. Usable rows say Use, downloadable rows Get. Other models
+ are dimmed; Enter must not switch focus or operate on them. Duplicate
+ subscriptions include their account label. Shared rows include the machine
+ name. From a live harness, Enter uses a model for that pane, starting
+ installed weights when needed; Get prepares uninstalled weights and stays
+ open. The right pane has one contextual Get/Use/Stop button. Tab switches
+ panes; arrows navigate within the active pane. Verify this in Cmd-N as well
+ as Cmd-P's model and machine scopes, including inline API and machine forms.
+ Search a host by either its Harness name (M2) or Grid hostname (mac.lan);
+ inventory and controls should be the same. Legacy Get explains when it
+ downloads and starts together. Add/edit/delete API forms stay in Cmd-P.
+
17. **Resize panes.** Run Resize panes. Use arrows, Shift-arrows for larger
changes, Tab to change divider, and Escape to finish. The temporary key
guide should explain the mode and disappear afterward.
diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.md
index 42705e2d6..18129d9c4 100644
--- a/desktop/design/terminal-workspace.md
+++ b/desktop/design/terminal-workspace.md
@@ -16,8 +16,10 @@ Use meaningful names and familiar terminal punctuation. Menu actions such as
Standalone actions can use brackets, such as `[ Customize Harness ]`, instead
of rounded buttons with pictograms. A checkbox is
`[x]` or `[ ]`. Harness search has no prefix; `#` selects projects and `>` selects
-commands as editable text. Small, established actions may use `+`,
-`@`, `:`, and `*`, with a descriptive tooltip and accessible name.
+commands as editable text. `@`, `:`, and `*` scope machines, models, and Store
+inside the same picker. The top bar keeps focused model, machine, and project links plus `+` for New
+Tab. Leave global search in Cmd-P and the app menu. Keep descriptive tooltips
+and accessible names.
There is no broadly understood ASCII pencil. Keep `[ Customize Harness ]` after
customization as well as before it. The same action should retain its name and
@@ -30,8 +32,14 @@ User content and embedded viewers retain their own visual language.
Every workspace action needs an existing command or a clear keyboard interaction.
Resolve shortcut hints from the live keymap. Cmd-N creates a harness, Cmd-O opens projects (`#`), Cmd-P searches harnesses, and Cmd-Shift-P opens
-commands (`>`) in the shared picker. Cmd-T opens a tab, Cmd-W closes a tab, and
-Cmd-Shift-W closes the focused pane view. Cmd-Q quits the app. Enter activates, Space toggles, and Escape backs out or dismisses.
+commands (`>`) in the shared picker. Cmd-I opens models with `:` already entered;
+typing Shift is unnecessary. From a live harness pane, Enter uses a served or
+downloaded model for that pane, starting installed weights when necessary; Tab
+switches between the list and controls. In Cmd-N, Tab switches between fields
+and their choices. Up/Down navigates the active pane and Enter activates.
+Cmd-P's model scope uses the same behavior. Cmd-T opens a tab, Cmd-W closes a tab, and
+Cmd-Shift-W closes the focused pane view. Cmd-Q quits the app. Enter activates,
+Space toggles, and Escape backs out or dismisses.
Closing a pane removes its view immediately, without a minimize animation.
diff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.md
index f4c6ac721..a668e3773 100644
--- a/desktop/design/workspace-status-bar.md
+++ b/desktop/design/workspace-status-bar.md
@@ -4,7 +4,7 @@ One shared status line, using compact monospace text and measured character cell
Follow the [terminal workspace design system](terminal-workspace.md).
```text
-1:api 2:web 3:blender + M2 autonomous-harness (main) > @ : *
+1:api 2:web 3:blender + M2 autonomous-harness (main)
```
## Tabs on the left
@@ -50,7 +50,7 @@ Do not show a tooltip that repeats a visible tab name (the numeric prefix does
not make it a different name). Show a different underlying name or the full
label when it is truncated. Keep action hints on symbols and status links.
-The new-tab `+` uses the same plain-text control as `>` `@` `:` `*`: no resting
+The new-tab `+` uses a plain-text control: no resting
box, with bold text on hover or keyboard
focus. Keep its New Tab tooltip and shortcut hint.
@@ -210,28 +210,21 @@ References: [Zsh prompt parameters](https://zsh.sourceforge.io/Doc/Release/Param
[Agnoster](https://github.com/agnoster/agnoster-zsh-theme), and
[Powerlevel10k](https://github.com/romkatv/powerlevel10k).
-Pane headers keep task identity and the hover-only close action. Four text symbols sit at the far
-right, after the focused context and PR: `>` Harnesses, `@` Machines, `:` Models,
-and `*` Store. Use the same compact monospace font, size, weight, and baseline as the
-status text. Each symbol is centered in an equal four-column slot (at least
-28 points wide) with an equally sized click target. In narrow windows, reduce
-all four slots together in whole columns. Keep the symbols plain at
-rest; hovering, pressing, or keyboard focus makes the text bold without changing
-the background. A hand cursor, descriptive tooltip, and accessible button
-name make each action discoverable. Do not show a help symbol for now.
-
-Harnesses opens the existing session manager with Pause and Resume. Machines
-opens its connection/password panel, Models opens its management panel with
-download/start/stop controls, and Store opens the Store tab. Cmd-O opens projects, Cmd-P opens
-harnesses, and Cmd-Shift-P opens commands in the unified picker; prefixes switch its resource type.
-
-![Harnesses controls, rendered with fixture data](images/workspace-status-harnesses.png)
-
-![Machine controls, rendered with fixture data](images/workspace-status-machines.png)
-
-Reserve the symbols' width before laying out tabs and context. Leave a window drag
-area between tabs and context and prevent overlap in narrow windows. Native
-menus and commands remain available.
+Pane headers keep task identity and the hover-only close action. The top bar
+contains tabs, New Tab, and focused model/machine/project/branch/PR context.
+Do not add a standalone Search label or category icons at the right edge.
+Context links open the corresponding scope in the unified picker. Global
+search remains available through Cmd-P and the app menu.
+
+The picker's empty preview contains clickable `@ machines`, `# projects`,
+`: models`, `* store`, and `> commands` hints. Each inserts its editable prefix
+and returns typing focus to the search input. Machine and model management,
+including API forms, stays inside the right pane. Store results open their
+Store page. Cmd-O, Cmd-M, Cmd-I, and Cmd-Shift-P remain shortcuts into the same
+picker; focused context links keep their scope.
+
+Leave a window drag area between tabs and context and prevent overlap in
+narrow windows. Native menus and commands remain available.
Data rules live in `lib/state/workspace_status.dart`; prompt formatting lives in
`lib/shared/theme/status_line_style.dart`. Flutter draws the fallback bar in
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index ad2c58127..9bccf36ca 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -20,6 +20,7 @@ const Set<String> encryptedDownTypes = {
'machine_resources',
'grid_fleet_models_list',
'grid_fleet_model_start',
+ 'grid_fleet_model_download',
'grid_fleet_model_stop',
'message',
'question_response',
diff --git a/desktop/lib/models/local_model.dart b/desktop/lib/models/local_model.dart
index d5e02a35a..2c44ee519 100644
--- a/desktop/lib/models/local_model.dart
+++ b/desktop/lib/models/local_model.dart
@@ -32,6 +32,25 @@ class LocalModel {
bool get resting => running && gridAsleep;
bool get downloaded => state == 'downloaded' || running;
+ /// Imported weights can omit `quant`, but their filename still names the
+ /// exact variant. Never infer quantization from size or model family.
+ String? get quantization {
+ if (quant?.trim().isNotEmpty == true) return quant!.trim();
+ return RegExp(
+ r'(?:^|[^a-z0-9])(IQ\d+[a-z0-9_]*|Q\d+[a-z0-9_]*|MXFP\d+(?:_[a-z0-9]+)*|BF16|FP16|F16)(?=[^a-z0-9_]|$)',
+ caseSensitive: false,
+ ).firstMatch(id)?.group(1)?.toUpperCase();
+ }
+
+ String get displayName {
+ final variant = quantization;
+ if (variant == null || variant.isEmpty) return name;
+ final present = RegExp(
+ '(^|[^a-z0-9])${RegExp.escape(variant.toLowerCase())}([^a-z0-9]|\$)',
+ ).hasMatch(name.toLowerCase());
+ return present ? name : '$name · $variant';
+ }
+
factory LocalModel.fromJson(Map<String, dynamic> data) => LocalModel(
id: data['id'] as String? ?? '',
name: data['name'] as String? ?? '',
@@ -76,7 +95,7 @@ class LocalModelOperation {
if (raw is! Map<String, dynamic> ||
raw['id'] is! String ||
raw['modelId'] is! String ||
- !['start', 'stop'].contains(raw['action']) ||
+ !['download', 'start', 'stop'].contains(raw['action']) ||
![
'checking',
'downloading',
diff --git a/desktop/lib/models/model_manager_controller.dart b/desktop/lib/models/model_manager_controller.dart
index fe46a0e92..7c4cc34e4 100644
--- a/desktop/lib/models/model_manager_controller.dart
+++ b/desktop/lib/models/model_manager_controller.dart
@@ -21,10 +21,15 @@ class ModelManagerController extends ChangeNotifier {
this.app, {
LocalKeyValueStore? storage,
this.poll = true,
+ this.targetMachineId,
}) : _storage = storage ?? (kUnderTest ? null : HarnessFileStore.shared);
final AppNotifier app;
final LocalKeyValueStore? _storage;
final bool poll;
+
+ /// A remote host uses the same inventory and lifecycle RPCs, without setting
+ /// up a Model Manager harness or reading another copy of the shared catalog.
+ final String? targetMachineId;
ApiConnectionsController? _apis;
ApiConnectionsController get apis => _apis ??= ApiConnectionsController(app);
static const introKey = 'models.introduction.dismissed';
@@ -45,11 +50,15 @@ class ModelManagerController extends ChangeNotifier {
String? hardware, error, _managerError;
bool preparing = false, opening = false, scanning = false, loaded = false;
bool inventoryAvailable = false, operationBusy = false;
+ bool supportsDownload = false;
LocalModelOperation? pendingOperation;
String? pendingId;
bool pendingStart = true;
+ bool pendingDownload = false;
- MachineState? get machine => app.localMachineState;
+ MachineState? get machine => targetMachineId == null
+ ? app.localMachineState
+ : app.stateOf(targetMachineId!);
Agent? get manager => machine?.agents
.where((a) => a.dsh == AppNotifier.gridHarness)
.firstOrNull;
@@ -96,13 +105,14 @@ class ModelManagerController extends ChangeNotifier {
app.addListener(_observe);
app.foreground.addListener(_foregroundChanged);
app.gridPictures.addListener(_pictureChanged);
- unawaited(_loadPreferences());
+ if (targetMachineId == null) unawaited(_loadPreferences());
_observe();
if (poll) {
_timer = Timer.periodic(const Duration(seconds: 4), (_) {
// A minimised or background app reads nothing, busy or not: the daemon owns the operation
// either way, and the one refresh on return ([_foregroundChanged]) catches up.
if (!app.inForeground) return;
+ if (targetMachineId != null && !_panelVisible && !busy) return;
if (busy ||
_panelVisible ||
_lastLocalRead == null ||
@@ -140,6 +150,7 @@ class ModelManagerController extends ChangeNotifier {
scanning = false;
loaded = false;
inventoryAvailable = false;
+ supportsDownload = false;
operationBusy = false;
pendingOperation = null;
pendingId = null;
@@ -151,17 +162,22 @@ class ModelManagerController extends ChangeNotifier {
error = null;
_managerError = null;
}
- if (current?.connectionStatus != ConnectionStatus.connected) {
+ if (current?.connectionStatus != ConnectionStatus.connected ||
+ current?.needsLink == true ||
+ (targetMachineId != null && current?.isOffline == true)) {
inventoryAvailable = false;
}
if (current != null &&
current.connectionStatus == ConnectionStatus.connected &&
- current.agentLoadStatus == AgentLoadStatus.loaded &&
+ (targetMachineId != null ||
+ current.agentLoadStatus == AgentLoadStatus.loaded) &&
!_autoPrepared) {
_autoPrepared = true;
- unawaited(prepare());
+ if (targetMachineId == null) unawaited(prepare());
// In the background the first read waits for the app to come back ([_foregroundChanged]).
- if (app.inForeground) unawaited(refresh());
+ if (app.inForeground && (targetMachineId == null || _panelVisible)) {
+ unawaited(refresh());
+ }
}
_changed();
}
@@ -169,6 +185,7 @@ class ModelManagerController extends ChangeNotifier {
/// Back in front of the person: exactly one refresh, whatever the background skipped.
void _foregroundChanged() {
if (_disposed || !app.inForeground) return;
+ if (targetMachineId != null && !_panelVisible && !busy) return;
final owner = machine;
if (owner == null || owner.connectionStatus != ConnectionStatus.connected) {
return;
@@ -179,6 +196,7 @@ class ModelManagerController extends ChangeNotifier {
/// Another surface's read, or the daemon's `grid_models_changed` push, changed the app's picture
/// of this machine's grids: take it, with no read of our own.
void _pictureChanged() {
+ if (targetMachineId != null) return;
final owner = machine;
if (_disposed || owner == null) return;
final picture = app.gridPictures[owner.machine.machineId];
@@ -342,9 +360,14 @@ class ModelManagerController extends ChangeNotifier {
Future<void> _refresh({required bool force}) async {
final owner = machine;
- if (owner == null || owner.connectionStatus != ConnectionStatus.connected) {
+ if (owner == null ||
+ owner.connectionStatus != ConnectionStatus.connected ||
+ owner.needsLink ||
+ (targetMachineId != null && owner.isOffline)) {
inventoryAvailable = false;
- error = 'Connect this computer to see its models.';
+ error = targetMachineId == null
+ ? 'Connect this computer to see its models.'
+ : 'Connect to ${owner?.machine.displayName ?? 'this machine'} to manage its models.';
_changed();
return;
}
@@ -356,7 +379,7 @@ class ModelManagerController extends ChangeNotifier {
DateTime.now().difference(_lastModelsRead!) >
const Duration(seconds: 20);
await Future.wait([
- if (readShared)
+ if (readShared && targetMachineId == null)
app.refreshGridModels(owner.machine.machineId).then((answer) {
if (_current(owner)) {
// The panel says so when ITS read could not reach the machine ("Shared models are
@@ -383,6 +406,7 @@ class ModelManagerController extends ChangeNotifier {
error = (answer['notice'] ?? answer['error']) as String?;
if (answer['models'] is! List) {
inventoryAvailable = false;
+ error ??= 'Models are unavailable. Try again.';
return;
}
localModels = (answer['models'] as List)
@@ -396,6 +420,7 @@ class ModelManagerController extends ChangeNotifier {
: null;
hardware = answer['hardware'] as String?;
operationBusy = answer['busy'] == true;
+ supportsDownload = answer['supportsDownload'] == true;
inventoryAvailable = true;
loaded = true;
_lastLocalRead = DateTime.now();
@@ -439,30 +464,58 @@ class ModelManagerController extends ChangeNotifier {
_changed();
}
- Future<void> toggle(LocalModel model) async {
+ Future<void> toggle(LocalModel model) =>
+ control(model, model.canStop ? 'stop' : 'start');
+
+ Future<void> control(LocalModel model, String action) async {
final owner = machine;
- if (owner == null || busy || !inventoryAvailable) return;
- final startModel = !model.canStop;
- if (startModel && !model.canStart) return;
+ if (owner == null ||
+ owner.connectionStatus != ConnectionStatus.connected ||
+ owner.needsLink ||
+ (targetMachineId != null && owner.isOffline) ||
+ owner.machine.isShared ||
+ busy ||
+ !inventoryAvailable) {
+ return;
+ }
+ final current = localModels
+ .where((entry) => entry.id == model.id)
+ .firstOrNull;
+ if (current == null) return;
+ final download = action == 'download';
+ final startModel = action == 'start';
+ if (download) {
+ if (!supportsDownload || current.downloaded || !current.canStart) return;
+ } else if (startModel) {
+ if (!current.canStart) return;
+ } else if (action != 'stop' || !current.canStop) {
+ return;
+ }
pendingId = model.id;
_actionRevision++;
inventoryAvailable = false;
pendingStart = startModel;
+ pendingDownload = download;
error = null;
- unawaited(dismissIntroduction());
+ if (targetMachineId == null) unawaited(dismissIntroduction());
_changed();
try {
- final answer = await app.controlLocalModel(
- owner.machine.machineId,
- model.id,
- start: startModel,
- );
+ final answer = download
+ ? await app.downloadLocalModel(owner.machine.machineId, model.id)
+ : await app.controlLocalModel(
+ owner.machine.machineId,
+ model.id,
+ start: startModel,
+ );
if (!_current(owner)) return;
error = answer['error'] as String?;
pendingOperation = LocalModelOperation.parse(answer['operation']);
operationBusy = pendingOperation?.active == true;
} catch (_) {
- if (_current(owner)) error = 'Checking whether the model started. Your click will not be repeated.';
+ if (_current(owner)) {
+ error =
+ 'Checking the model operation. Your click will not be repeated.';
+ }
} finally {
if (_current(owner)) {
pendingId = null;
diff --git a/desktop/lib/models/model_search_catalog.dart b/desktop/lib/models/model_search_catalog.dart
index 6ce2d6e19..667ac46b7 100644
--- a/desktop/lib/models/model_search_catalog.dart
+++ b/desktop/lib/models/model_search_catalog.dart
@@ -1,11 +1,25 @@
+import 'dart:async';
+
import 'package:flutter/foundation.dart';
+import '../core/models.dart';
import '../state/swarm_navigation.dart';
import '../usage/models_menu_controller.dart';
+import '../widgets/resting_model_words.dart';
import 'api_connections_controller.dart';
import 'local_model.dart';
import 'model_manager_controller.dart';
+enum ModelSearchSection {
+ subscriptions('Subscriptions'),
+ apis('APIs'),
+ local('Your local AI models'),
+ shared('Shared with you');
+
+ const ModelSearchSection(this.label);
+ final String label;
+}
+
/// Public model metadata shared by the picker and its preview. Filtering this
/// snapshot never scans a machine or changes a harness's selected model.
class ModelSearchEntry {
@@ -18,39 +32,217 @@ class ModelSearchEntry {
this.api,
this.subscription,
this.node,
+ this.searchAliases = const [],
+ this.controller,
+ this.own = false,
+ this.gridModel,
+ this.sharedBy,
});
final String id, name, source, status;
final String? node;
final LocalModel? local;
final ApiConnection? api;
final Map<String, Object?>? subscription;
+ final List<String> searchAliases;
+ final ModelManagerController? controller;
+ final bool own;
+ final GridModel? gridModel;
+ final String? sharedBy;
+
+ ModelSearchSection get section => subscription != null
+ ? ModelSearchSection.subscriptions
+ : api != null
+ ? ModelSearchSection.apis
+ : own
+ ? ModelSearchSection.local
+ : ModelSearchSection.shared;
+
+ bool get needsDownload =>
+ local != null &&
+ !local!.downloaded &&
+ gridModel == null &&
+ controller?.operationFor(local!)?.active != true;
+
+ // Installed weights stay above discovery-only rows and the download catalog.
+ int get localRank => local?.downloaded == true
+ ? 0
+ : gridModel != null
+ ? 1
+ : 2;
late final destination = SwarmDestination(
id: id,
modelId: id,
- title: name,
+ title: sharedBy?.isNotEmpty == true ? '$name · $sharedBy' : name,
detail: [source, node, status].whereType<String>().join(' · '),
swarmId: null,
current: false,
- searchFields: [source, node, status, local?.id, api?.host],
+ searchFields: [
+ section.label,
+ source,
+ node,
+ sharedBy,
+ status,
+ local?.id,
+ api?.host,
+ ...searchAliases,
+ ],
);
}
class ModelSearchCatalog extends ChangeNotifier {
- ModelSearchCatalog(this.manager, this.subscriptions) {
+ ModelSearchCatalog(
+ this.manager,
+ this.subscriptions, {
+ this.pollHosts = true,
+ }) {
manager.addListener(_refresh);
manager.apis.addListener(_refresh);
subscriptions.addListener(_refresh);
+ manager.app.addListener(_machinesChanged);
_refresh();
}
final ModelManagerController manager;
final ModelsMenuController subscriptions;
+ final bool pollHosts;
+ final _hosts = <String, ModelManagerController>{};
+ final _managedRowIds = <String, String>{};
+ bool _visible = false;
Map<String, ModelSearchEntry> entries = {};
List<SwarmDestination> rows = const [];
+ void setVisible(bool visible) {
+ if (_visible == visible) return;
+ _visible = visible;
+ _machinesChanged();
+ for (final controller in _hosts.values) {
+ controller.setPanelVisible(visible);
+ if (visible) unawaited(controller.refresh());
+ }
+ }
+
+ void _machinesChanged() {
+ final machines = manager.app.machineStates;
+ for (final id in _hosts.keys.toList()) {
+ final machine = machines[id];
+ if (machine == null ||
+ machine.isLocalMachine ||
+ machine.machine.isShared) {
+ _hosts.remove(id)!.dispose();
+ _managedRowIds.removeWhere((key, _) => key.startsWith('$id:'));
+ }
+ }
+ if (_visible) {
+ for (final machine in machines.values) {
+ final id = machine.machine.machineId;
+ if (machine.isLocalMachine ||
+ machine.machine.isShared ||
+ _hosts.containsKey(id)) {
+ continue;
+ }
+ final controller = ModelManagerController(
+ manager.app,
+ targetMachineId: id,
+ poll: manager.poll && pollHosts,
+ );
+ _hosts[id] = controller;
+ controller.addListener(_refresh);
+ controller.setPanelVisible(true);
+ controller.start();
+ }
+ }
+ _refresh();
+ }
+
+ Future<void> refresh({bool force = false}) async {
+ _machinesChanged();
+ await Future.wait([
+ manager.refresh(force: force),
+ for (final controller in _hosts.values) controller.refresh(force: force),
+ ]);
+ }
+
+ // Harness already stores both naming conventions on one machine record.
+ // Resolve that record first, then take model ids and capabilities from its
+ // own inventory. Duplicate names never grant control over an arbitrary host.
+ ModelManagerController? _hostFor(String node) {
+ if (node.isEmpty) return null;
+ final matching = manager.app.machineStates.values.where(
+ (state) =>
+ !state.machine.isShared &&
+ (state.machine.hostname == node || state.machine.name == node),
+ );
+ if (matching.length != 1) return null;
+ final host = matching.single;
+ return host.isLocalMachine ? manager : _hosts[host.machine.machineId];
+ }
+
+ String _managedKey(ModelManagerController owner, LocalModel model) =>
+ '${owner.machine?.machine.machineId}:${model.id}';
+
void _refresh() {
- final local = manager.localModels.toList();
- int rank(LocalModel model) => manager.operationFor(model)?.active == true
+ final discovered = <ModelSearchEntry>[];
+ final served = <String, GridModel>{};
+ for (final section in manager.sections) {
+ for (final model in section.models) {
+ final owner = section.own ? _hostFor(model.node) : null;
+ final matches =
+ owner?.localModels
+ .where(
+ (local) =>
+ (local.downloaded || local.canStop) &&
+ (local.name.toLowerCase() == model.id.toLowerCase() ||
+ local.id.toLowerCase() == model.id.toLowerCase()),
+ )
+ .toList() ??
+ const <LocalModel>[];
+ final id =
+ 'model:${section.own ? 'own' : 'shared'}:${section.name}:${model.node}:${model.id}';
+ final gridModel = GridModel(
+ id: model.id,
+ node: model.node,
+ grid: model.grid ?? section.name,
+ unavailable: model.unavailable,
+ );
+ if (owner != null && matches.length == 1) {
+ served[_managedKey(owner, matches.single)] = gridModel;
+ _managedRowIds.putIfAbsent(
+ _managedKey(owner, matches.single),
+ () => id,
+ );
+ continue;
+ }
+ final words = sectionWords(section);
+ discovered.add(
+ ModelSearchEntry(
+ id: id,
+ name: model.id,
+ source: section.own
+ ? 'On your machines'
+ : 'Shared · ${section.name}',
+ node: owner?.machine?.machine.displayName ?? model.node,
+ searchAliases: [model.node, if (section.own) 'local'],
+ own: section.own,
+ controller: owner,
+ gridModel: gridModel,
+ sharedBy: section.own ? null : model.node,
+ status:
+ offlineRowNote(model) ??
+ words.sentence ??
+ words.subtitle ??
+ (manager.models?.reachable == false
+ ? 'Unavailable'
+ : 'Available'),
+ ),
+ );
+ }
+ }
+ final local = [
+ for (final owner in [manager, ..._hosts.values])
+ for (final model in owner.localModels) (owner: owner, model: model),
+ ];
+ int rank(ModelManagerController owner, LocalModel model) =>
+ owner.operationFor(model)?.active == true
? 0
: model.running
? 1
@@ -58,34 +250,48 @@ class ModelSearchCatalog extends ChangeNotifier {
? 2
: 3;
local.sort((a, b) {
- final state = rank(a).compareTo(rank(b));
- return state != 0 ? state : a.name.compareTo(b.name);
+ final state = rank(a.owner, a.model).compareTo(rank(b.owner, b.model));
+ if (state != 0) return state;
+ final name = a.model.name.compareTo(b.model.name);
+ if (name != 0) return name;
+ final host = (a.owner.machine?.machine.displayName ?? '').compareTo(
+ b.owner.machine?.machine.displayName ?? '',
+ );
+ return host != 0
+ ? host
+ : _managedKey(
+ a.owner,
+ a.model,
+ ).compareTo(_managedKey(b.owner, b.model));
});
final all = [
- for (final model in local)
+ for (final (:owner, :model) in local)
ModelSearchEntry(
- id: 'model:local:${model.id}',
- name: model.name,
+ id: _managedRowIds.putIfAbsent(
+ _managedKey(owner, model),
+ () => (identical(owner, manager)
+ ? 'model:local:${model.id}'
+ : 'model:machine:${_managedKey(owner, model)}'),
+ ),
+ name: model.displayName,
source: 'Local',
- node: manager.machine?.machine.displayName,
- status: localStatus(model),
+ node: owner.machine?.machine.displayName,
+ status: localStatus(model, controller: owner),
local: model,
+ own: true,
+ controller: owner,
+ gridModel: served[_managedKey(owner, model)],
+ searchAliases: [?owner.machine?.machine.hostname],
),
- for (final section in manager.sections.where((section) => !section.own))
- for (final model in section.models)
- ModelSearchEntry(
- id: 'model:shared:${section.name}:${model.node}:${model.id}',
- name: model.id,
- source: 'Shared · ${section.name}',
- node: model.node,
- status: manager.models?.reachable == false
- ? 'Unavailable'
- : 'Available',
- ),
+ ...discovered.where((entry) => entry.own),
+ ...discovered.where((entry) => !entry.own),
for (final row in subscriptions.rows)
ModelSearchEntry(
id: 'model:subscription:${row['engine']}:${row['title']}:${row['account']}',
- name: '${row['title'] ?? 'Subscription'}',
+ name: [
+ '${row['title'] ?? 'Subscription'}',
+ if ('${row['account'] ?? ''}'.isNotEmpty) '${row['account']}',
+ ].join(' · '),
source: 'Subscription',
status: '${row['status'] ?? 'Usage unavailable'}',
subscription: row,
@@ -99,19 +305,31 @@ class ModelSearchCatalog extends ChangeNotifier {
api: api,
),
];
+ final order = {for (final (index, entry) in all.indexed) entry.id: index};
+ all.sort((a, b) {
+ final section = a.section.index.compareTo(b.section.index);
+ if (section != 0) return section;
+ final installed = a.localRank.compareTo(b.localRank);
+ return installed != 0 ? installed : order[a.id]!.compareTo(order[b.id]!);
+ });
entries = {for (final entry in all) entry.id: entry};
rows = [for (final entry in all) entry.destination];
notifyListeners();
}
- String localStatus(LocalModel model) {
- final operation = manager.operationFor(model);
+ String localStatus(LocalModel model, {ModelManagerController? controller}) {
+ final owner = controller ?? manager;
+ final operation = owner.operationFor(model);
if (operation?.active == true) {
final progress = operation!.progress;
return '${operation.label}${progress == null ? '' : ' ${(progress * 100).floor()}%'}';
}
- if (manager.pendingId == model.id) {
- return manager.pendingStart ? 'Starting' : 'Stopping';
+ if (owner.pendingId == model.id) {
+ return owner.pendingDownload
+ ? 'Downloading'
+ : owner.pendingStart
+ ? 'Starting'
+ : 'Stopping';
}
if (operation?.failed == true) return 'Failed · try again';
return model.running
@@ -123,6 +341,10 @@ class ModelSearchCatalog extends ChangeNotifier {
@override
void dispose() {
+ manager.app.removeListener(_machinesChanged);
+ for (final controller in _hosts.values) {
+ controller.dispose();
+ }
manager.removeListener(_refresh);
manager.apis.removeListener(_refresh);
subscriptions.removeListener(_refresh);
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 08053723c..9cb2414d0 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -19,6 +19,7 @@ import '../core/test_run.dart';
import '../logging/debug_surface.dart';
import '../models/models_panel.dart';
import '../models/model_search_catalog.dart';
+import '../widgets/resting_section.dart' show confirmSwitchAnyway;
import '../settings/settings_screen.dart';
import '../settings/settings_section.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -62,7 +63,6 @@ import '../widgets/grid_model_picker.dart';
import '../store/store_mark.dart';
import '../store/store_screen.dart';
import '../widgets/harness_start_page.dart';
-import '../widgets/link_another_machine_dialog.dart';
import '../widgets/machines_panel.dart';
import '../widgets/harness_session_manager.dart';
import '../widgets/onboarding_card.dart';
@@ -244,6 +244,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
List<Object?>? _machinesPresentation;
ModelsMenuController? _modelsMenu;
ModelSearchCatalog? _pickerModels;
+ WorkspacePaneContext? _modelSelectionTarget;
final _previewControls = SearchPreviewControls();
bool _modelSearchVisible = false;
bool _machineSearchVisible = false;
@@ -513,7 +514,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
final split = _search!.split;
final placement = _search!.placement;
final task = _search!.createTask;
- final machineId = _search!.scopedMachineId;
+ final selected = _search!.selected;
+ final machineId =
+ _search!.scopedMachineId ??
+ (selected?.isMachine == true ? selected!.machineId : null);
_closeSearch(restoreFocus: false);
unawaited(
_newAgent(
@@ -1271,7 +1275,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
return;
}
if (call.method == 'models') {
- _toggleModels();
+ _togglePaneModels();
await WidgetsBinding.instance.endOfFrame;
return;
}
@@ -2651,6 +2655,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
void _toggleModels({ModelsTab initialTab = ModelsTab.all}) {
+ _modelSelectionTarget = null;
+ _search?.setModelSelection(null, null);
_onboarding.acknowledge(OnboardingStep.models);
_openResourcePicker(':');
if (_search?.isModelMode == true && initialTab != ModelsTab.all) {
@@ -2666,6 +2672,55 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
}
+ void _togglePaneModels() => _toggleModels();
+
+ void _bindModelSelection() {
+ final focused = WorkspacePaneContext.focused(app);
+ if (focused == null ||
+ !_canSwitchFocusedModel(focused) ||
+ _modelSelectionTarget != null) {
+ return;
+ }
+ final search = _search;
+ if (search == null) return;
+ _modelSelectionTarget = focused;
+ search.setModelSelection(
+ focused.engine,
+ app.gridPictures[focused.pane.machineId],
+ machineId: focused.pane.machineId,
+ );
+ void selectCurrent() {
+ if (search.query != ':' || search.managing) return;
+ final current = focused.agent?.gridModel;
+ final index = search.rows.indexWhere((row) {
+ final entry = search.models?.entries[row.modelId];
+ return current != null
+ ? entry?.gridModel?.id.toLowerCase() == current.toLowerCase()
+ : entry?.subscription?['engine'] == focused.engine &&
+ search.canSelectModel(row);
+ });
+ if (index >= 0) search.move(index - search.cursor);
+ }
+
+ selectCurrent();
+ final initialSelection = search.selected?.id;
+ unawaited(
+ app.readGridPicture(focused.pane.machineId).then((choices) {
+ if (!mounted ||
+ !identical(_search, search) ||
+ !identical(_modelSelectionTarget, focused)) {
+ return;
+ }
+ search.setModelSelection(
+ focused.engine,
+ choices,
+ machineId: focused.pane.machineId,
+ );
+ if (search.selected?.id == initialSelection) selectCurrent();
+ }),
+ );
+ }
+
void _toggleHarnessControls() {
if (_harnessesOverlay != null) {
_closeHarnessControls();
@@ -2965,6 +3020,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (_modelSearchVisible != search.isModelMode) {
_modelSearchVisible = search.isModelMode;
app.modelManager.setPanelVisible(_modelSearchVisible);
+ _pickerModels?.setVisible(_modelSearchVisible);
+ if (_modelSearchVisible) _bindModelSelection();
if (_modelSearchVisible && !kUnderTest) {
unawaited(app.modelManager.refresh());
unawaited(app.modelManager.apis.refresh());
@@ -3009,8 +3066,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
_search!.removeListener(_syncSearch);
_search!.dispose();
_search = null;
+ _modelSelectionTarget = null;
_modelSearchVisible = false;
app.modelManager.setPanelVisible(false);
+ _pickerModels?.setVisible(false);
_searchHeaderState = null;
_searchText.clear();
_syncToolbarNotices();
@@ -3047,14 +3106,77 @@ class _SwarmScreenState extends State<SwarmScreen> {
final placement = _search?.placement;
final answering = _search?.sessionFilter == SessionFilter.needsInput;
if (target == null) return;
- if (choice.destination.isModel) {
+ if (choice.destination.isModel &&
+ _search!.canGetModel(choice.destination)) {
+ await _search!.getModel(choice.destination);
+ return;
+ }
+ if (choice.destination.isModel &&
+ _search!.canSelectModel(choice.destination)) {
+ final search = _search!;
+ if (search.usingModelId != null) return;
+ final chosenFor = _modelSelectionTarget;
+ bool current() {
+ final now = WorkspacePaneContext.focused(app);
+ return mounted &&
+ identical(_search, search) &&
+ search.isModelMode &&
+ chosenFor != null &&
+ now != null &&
+ now.pane.id == chosenFor.pane.id &&
+ now.agentId == chosenFor.agentId &&
+ now.pane.machineId == chosenFor.pane.machineId &&
+ _canSwitchFocusedModel(now);
+ }
+
+ if (!current()) return;
+ var selected = search.selectableGridModel(choice.destination);
+ if (selected == null && search.canStartModelForUse(choice.destination)) {
+ selected = await search.startModelForUse(
+ choice.destination,
+ stillCurrent: current,
+ );
+ if (!mounted || !current() || selected == null) return;
+ }
+ if (selected?.unavailable case final offline?) {
+ _pickerModalChanged(true);
+ bool proceed;
+ try {
+ proceed = await confirmSwitchAnyway(
+ context,
+ model: selected!.id,
+ offline: offline,
+ );
+ } finally {
+ _pickerModalChanged(false);
+ }
+ if (!proceed || !mounted || !current() || _search == null) return;
+ }
+ final now = WorkspacePaneContext.focused(app)!;
+ _closeSearch();
+ if (selected == null) {
+ if (now.agent?.gridModel != null) {
+ await app.clearAgentGrid(now.pane.machineId, now.agentId!);
+ }
+ } else if (selected.id != now.agent?.gridModel) {
+ await app.retargetAgentToGridModel(
+ now.pane.machineId,
+ now.agentId!,
+ selected.id,
+ gridName: selected.grid,
+ );
+ }
+ return;
+ }
+ if (choice.destination.isModel) return;
+ if (_search!.setupLayout && choice.destination.isMachine) {
final index = _search!.rows.indexWhere(
(row) => row.id == choice.destination.id,
);
if (index >= 0) _search!.move(index - _search!.cursor);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _search?.selected?.id == choice.destination.id) {
- _previewControls.invoke('picker.accept');
+ _previewControls.invoke('picker.focus_actions');
}
});
return;
@@ -3066,18 +3188,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
if (choice.destination.isCreate) {
if (_search!.isMachineMode) {
- _pickerModalChanged(true);
- try {
- await showLinkAnotherMachineDialog(context, app, keymap: _keymap);
- } finally {
- _pickerModalChanged(false);
- }
- if (mounted) _focusSearch();
+ _previewControls.invoke('picker.focus_actions');
return;
}
if (_search!.isModelMode) {
- await app.modelManager.open();
- if (app.modelManager.error == null) _closeSearch(restoreFocus: false);
+ _previewControls.invoke('picker.resource_add_api');
return;
}
// What was typed and found nothing is what the new harness starts on.
@@ -3148,10 +3263,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
onRefocus: _focusSearch,
onModalChanged: _pickerModalChanged,
onCommands: _showSearchCommands,
- onManageModels: () async {
- await app.modelManager.open();
- if (app.modelManager.error == null) _closeSearch(restoreFocus: false);
- },
);
final terminalTheme = terminalThemeFor(
grid.AppTheme.palette.value,
@@ -3596,8 +3707,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
'machine.link': _showMachinesControls,
'machines.manage': _manageMachines,
'machines.list': _openMachines,
- 'models.list': _toggleModels,
+ 'models.list': _togglePaneModels,
'harnesses.list': _toggleSessions,
+ 'harnesses.manage': _toggleHarnessControls,
+ 'machines.connections': _showMachinesControls,
+ 'models.manage': _toggleModelsControls,
'project.add': _addProject,
'keyboard.open_config': () => openKeyboardConfig(context),
'keyboard.quick_start': _startQuickStart,
@@ -4345,6 +4459,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
subscriptionModel: focused.agent?.modelName,
webSearch: focused.agent?.gridWebSearch,
engineLabel: focused.engine,
+ onOpen: () {
+ if (current()) _toggleModels();
+ },
onSelected: (model) {
if (current()) {
unawaited(
@@ -4386,19 +4503,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
for (var index = 0; index < app.swarms.length; index++)
'${index + 1}:${names[app.swarms[index].id]}',
];
- final toolColumns = math.max(
- (28 / cell.width).ceil(),
- math.min(
- 4,
- ((constraints.maxWidth - cell.width * 9) / (cell.width * 4)).floor(),
- ),
- );
- final toolWidth = cell.width * toolColumns;
final toolHeight = workspaceBarControlHeight(context);
- final contentWidth = math.max(
- 0.0,
- constraints.maxWidth - toolWidth * 4 - cell.width * 9,
- );
+ final contentWidth = math.max(0.0, constraints.maxWidth - cell.width * 7);
final tabBudget = contentWidth * .45;
_tabWidths = [
for (final label in labels)
@@ -4594,39 +4700,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
],
- SizedBox(width: cell.width * 2),
- _statusToolSymbol(
- 'harnesses',
- 'Harnesses',
- _toggleHarnessControls,
- '>',
- Size(toolWidth, toolHeight),
- theme,
- ),
- _statusToolSymbol(
- 'machines',
- 'Machines',
- () => unawaited(_showMachinesControls()),
- '@',
- Size(toolWidth, toolHeight),
- theme,
- ),
- _statusToolSymbol(
- 'models',
- 'Models',
- _toggleModelsControls,
- ':',
- Size(toolWidth, toolHeight),
- theme,
- ),
- _statusToolSymbol(
- 'store',
- 'Harness Store',
- _openStore,
- '*',
- Size(toolWidth, toolHeight),
- theme,
- ),
SizedBox(width: cell.width),
],
),
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index db7349462..611b8e553 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -242,15 +242,6 @@ const List<AppShortcut> kAppShortcuts = [
label: 'Zoom this pane, or put it back',
group: ShortcutGroup.panes,
),
- // ⌘; — tmux's `prefix ;`, spelled the same. Two agents at a time is the shape
- // most work actually has, and walking a list to get back to the other one is
- // the wrong motion for it.
- AppShortcut(
- action: ShortcutAction.lastPane,
- activator: SingleActivator(LogicalKeyboardKey.semicolon, meta: true),
- label: 'Back to the pane you were just on',
- group: ShortcutGroup.panes,
- ),
AppShortcut(
action: ShortcutAction.closePane,
activator: SingleActivator(
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 8df84160c..b7d587c1f 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -36,6 +36,14 @@ class HarnessCommand {
defaultTargetPlatform == TargetPlatform.linux) {
return const ['ctrl+p'];
}
+ if (id == 'models.list' && defaultTargetPlatform == TargetPlatform.linux) {
+ return const ['ctrl+i', 'cmd+i'];
+ }
+ if (id == 'picker.complete' &&
+ defaultTargetPlatform == TargetPlatform.linux) {
+ // Ctrl-I opens Models on Linux, including from another picker scope.
+ return const ['tab'];
+ }
return action == null ? extraKeys : _workspaceKeys[action] ?? const [];
}
@@ -410,6 +418,24 @@ final harnessCommands = <HarnessCommand>[
ShortcutGroup.actions,
nativeAction: 'addProject',
),
+ const HarnessCommand(
+ 'harnesses.manage',
+ 'Manage harnesses',
+ ShortcutGroup.actions,
+ keywords: ['running', 'paused', 'sessions'],
+ ),
+ const HarnessCommand(
+ 'machines.connections',
+ 'Machine connection settings',
+ ShortcutGroup.actions,
+ keywords: ['password', 'connect', 'link'],
+ ),
+ const HarnessCommand(
+ 'models.manage',
+ 'Manage models',
+ ShortcutGroup.actions,
+ keywords: ['download', 'start', 'stop', 'local', 'API'],
+ ),
const HarnessCommand(
'machines.refresh',
'Refresh machines and agents',
@@ -514,6 +540,29 @@ final harnessCommands = <HarnessCommand>[
context: KeymapContext.picker,
repeatable: true,
),
+ const HarnessCommand(
+ 'picker.control_next',
+ 'Next control in the resource preview',
+ ShortcutGroup.navigate,
+ extraKeys: ['right'],
+ context: KeymapContext.picker,
+ repeatable: true,
+ ),
+ for (final kind in ['app', 'cli'])
+ HarnessCommand(
+ 'picker.machine_$kind',
+ 'Show machine setup with ${kind == 'app' ? 'the app' : 'the CLI'}',
+ ShortcutGroup.actions,
+ context: KeymapContext.picker,
+ ),
+ const HarnessCommand(
+ 'picker.control_previous',
+ 'Previous control in the resource preview',
+ ShortcutGroup.navigate,
+ extraKeys: ['left'],
+ context: KeymapContext.picker,
+ repeatable: true,
+ ),
const HarnessCommand(
'picker.page_up',
'Page up in the results',
@@ -575,6 +624,13 @@ final harnessCommands = <HarnessCommand>[
context: KeymapContext.picker,
),
// Contextual resource actions leave the query and result selection in place.
+ for (final action in ['download', 'start', 'stop'])
+ HarnessCommand(
+ 'picker.model_$action',
+ '${action[0].toUpperCase()}${action.substring(1)} the selected model',
+ ShortcutGroup.actions,
+ context: KeymapContext.picker,
+ ),
for (final (name, key, label) in [
('toggle', 'ctrl+s', 'Pause or resume the selected harness or model'),
('more', 'ctrl+period', 'Search actions for the selected resource'),
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 2200cf594..6b9214b3c 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2009,8 +2009,8 @@ class AppNotifier extends ChangeNotifier {
railFocused = false;
// Remembered only on a REAL move. Re-focusing the tile you are already on
// happens constantly — see the note below about why it is announced anyway
- // — and recording it would make ⌘; a key that returns you to where you
- // already are, which is the same as a key that does nothing.
+ // — and recording it would make the previous-pane command return you to
+ // where you already are.
if (moved) _previousPaneId = focusedPaneId;
focusedPaneId = paneId;
selectedMachineId = focusedPane?.machineId;
@@ -5415,6 +5415,15 @@ class AppNotifier extends ChangeNotifier {
timeout: const Duration(seconds: 12),
);
+ Future<Map<String, dynamic>> downloadLocalModel(
+ String machineId,
+ String modelId,
+ ) => _conn(machineId).request(
+ 'grid_fleet_model_download',
+ payload: {'modelId': modelId},
+ timeout: const Duration(seconds: 12),
+ );
+
/// The session picker opens the same local Models overview as the toolbar.
Future<void> runLocalModel(
BuildContext context, {
@@ -9729,12 +9738,8 @@ class AppNotifier extends ChangeNotifier {
return best;
}
- /// ⌘; — the pane focused before this one.
- ///
- /// tmux spells it the same way, and the reason it earns a key is that two
- /// agents at a time is the shape most work actually has: a thing being built
- /// and a thing being watched. Walking a list to get back to the other one is
- /// the wrong motion, and it gets longer as the grid fills.
+ /// The pane focused before this one, used by the remappable `pane.last`
+ /// command to switch between two agents without walking the whole layout.
int? get _previousPaneId => activeSwarm.previousPaneId;
set _previousPaneId(int? value) => activeSwarm.previousPaneId = value;
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index f124f5ba8..26c44c4c2 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -1,9 +1,12 @@
+import 'dart:async';
+
import 'package:flutter/foundation.dart';
import 'package:collection/collection.dart' show compareNatural;
import '../models/model_search_catalog.dart';
import '../core/dsh_catalog.dart';
import '../core/machine_resources.dart';
+import '../core/models.dart' show ConnectionStatus, GridModels, GridModel;
import 'app_state.dart';
import 'harness_placement.dart';
@@ -72,6 +75,7 @@ class SwarmSearchController extends ChangeNotifier {
app.addListener(_refresh);
projects?.addListener(_refresh);
models?.addListener(_modelsChanged);
+ app.gridPictures.addListener(_modelChoicesChanged);
app.sessionPreviews.addListener(_previewChanged);
}
@@ -79,6 +83,97 @@ class SwarmSearchController extends ChangeNotifier {
final List<String> recent;
final SwarmProjectStore? projects;
final ModelSearchCatalog? models;
+ bool modelDownloadsVisible = false;
+ bool isModelDownloadsRow(SwarmDestination? row) =>
+ isModelMode && row?.id == 'model:downloads';
+ late final _showDownloadsRow = SwarmDestination(
+ id: 'model:downloads',
+ modelId: 'model:downloads',
+ title: '[ Get models ]',
+ detail: '',
+ swarmId: null,
+ current: false,
+ );
+ late final _hideDownloadsRow = SwarmDestination(
+ id: 'model:downloads',
+ modelId: 'model:downloads',
+ title: '[ Hide catalog ]',
+ detail: '',
+ swarmId: null,
+ current: false,
+ );
+
+ ModelSearchSection modelSection(SwarmDestination row) => row.isCreate
+ ? ModelSearchSection.apis
+ : models?.entries[row.modelId]?.section ?? ModelSearchSection.local;
+
+ String? modelRowAction(SwarmDestination row) {
+ final entry = models?.entries[row.modelId];
+ if (entry == null) return null;
+ return canSelectModel(row)
+ ? 'Use'
+ : canGetModel(row)
+ ? 'Get'
+ : null;
+ }
+
+ bool canGetModel(SwarmDestination? row) {
+ if (!isModelMode) return false;
+ final entry = models?.entries[row?.modelId];
+ final owner = entry?.controller;
+ return entry?.needsDownload == true &&
+ entry?.local?.canStart == true &&
+ owner != null &&
+ owner.inventoryAvailable &&
+ !owner.busy &&
+ owner.machine?.connectionStatus == ConnectionStatus.connected &&
+ owner.machine?.needsLink == false &&
+ (owner.targetMachineId == null || owner.machine?.isOffline == false);
+ }
+
+ Future<String?> getModel(SwarmDestination row) async {
+ if (!canGetModel(row)) return null;
+ final entry = models!.entries[row.modelId]!;
+ final owner = entry.controller!;
+ await owner.control(
+ entry.local!,
+ owner.supportsDownload ? 'download' : 'start',
+ );
+ return owner.error;
+ }
+
+ String? modelUseReason(SwarmDestination? row) {
+ final entry = models?.entries[row?.modelId];
+ if (entry == null || canSelectModel(row)) return null;
+ if (modelSelectionEngine == null) return 'No active harness';
+ if (entry.subscription case final subscription?) {
+ if (subscription['engine'] != modelSelectionEngine) {
+ return subscription['engine'] == 'claude'
+ ? 'Claude only'
+ : 'Codex only';
+ }
+ if (subscription['status'] == 'Not signed in') return 'Not signed in';
+ return 'Other account';
+ }
+ if (entry.api != null) return 'Tools only';
+ if (entry.gridModel?.unavailable != null) return 'Offline';
+ if (entry.needsDownload) return 'Download first';
+ if (entry.local case final local?) {
+ final owner = entry.controller!;
+ if (owner.operationFor(local)?.active == true) return entry.status;
+ if (owner.machine?.isOffline == true ||
+ owner.machine?.connectionStatus != ConnectionStatus.connected ||
+ owner.machine?.needsLink == true) {
+ return 'Connect host';
+ }
+ if (!local.running && !local.canStart && local.canStop) {
+ return 'Not serving';
+ }
+ if (owner.busy) return 'Host busy';
+ }
+ return 'Not available to this harness';
+ }
+
final SwarmNavigationHistory? history;
/// Availability is read from workspace state and rechecked at activation.
@@ -101,6 +196,204 @@ class SwarmSearchController extends ChangeNotifier {
final bool selectOnEmptyQuery;
// Prefixes change the catalog, never the Cmd-P dialog's layout.
bool get setupLayout => activityFirst;
+ bool managing = false;
+ String? modelSelectionEngine;
+ String? _modelSelectionMachineId;
+ GridModels? _modelChoices;
+ String? usingModelId;
+ String? modelUseErrorId, modelUseError;
+ Timer? _modelUseTimer;
+ Completer<void>? _modelUseWait;
+
+ void setModelSelection(
+ String? engine,
+ GridModels? choices, {
+ String? machineId,
+ }) {
+ modelSelectionEngine = engine;
+ _modelSelectionMachineId = machineId;
+ _modelChoices = choices;
+ notifyListeners();
+ }
+
+ void _modelChoicesChanged() {
+ if (_disposed || _modelSelectionMachineId == null) return;
+ final choices = app.gridPictures[_modelSelectionMachineId!];
+ if (choices == null || identical(choices, _modelChoices)) return;
+ _modelChoices = choices;
+ notifyListeners();
+ }
+
+ GridModel? selectableGridModel(SwarmDestination? row) {
+ if (!isModelMode ||
+ modelSelectionEngine == null ||
+ _modelChoices?.canRunLocally(modelSelectionEngine) != true) {
+ return null;
+ }
+ final entry = models?.entries[row?.modelId];
+ if (entry?.local case final local?) {
+ if (!local.running ||
+ entry!.controller?.operationFor(local)?.active == true) {
+ return null;
+ }
+ }
+ final offered = entry?.gridModel;
+ if (offered == null || offered.unavailable != null) return null;
+ for (final section in _modelChoices!.sections) {
+ if (section.name != offered.grid && !(section.own && entry!.own)) {
+ continue;
+ }
+ for (final candidate in section.models) {
+ if (candidate.id.toLowerCase() == offered.id.toLowerCase() &&
+ candidate.unavailable == null) {
+ return GridModel(
+ id: candidate.id,
+ node: candidate.node,
+ grid: section.name,
+ unavailable: candidate.unavailable,
+ );
+ }
+ }
+ }
+ return null;
+ }
+
+ bool canSelectModel(SwarmDestination? row) {
+ if (!isModelMode || modelSelectionEngine == null || row?.isModel != true) {
+ return false;
+ }
+ final entry = models?.entries[row!.modelId];
+ final subscription = entry?.subscription;
+ if (subscription != null) {
+ final machine = app.stateOf(_modelSelectionMachineId ?? '');
+ if (machine == null || subscription['engine'] != modelSelectionEngine) {
+ return false;
+ }
+ final available = models!.subscriptions.subscriptionFor(
+ modelSelectionEngine!,
+ local: machine.isLocalMachine,
+ machineName: machine.machine.displayName,
+ );
+ return available != null &&
+ available['status'] != 'Not signed in' &&
+ available['account'] == subscription['account'];
+ }
+ return selectableGridModel(row) != null || canStartModelForUse(row);
+ }
+
+ bool canStartModelForUse(SwarmDestination? row) {
+ if (!isModelMode ||
+ modelSelectionEngine == null ||
+ _modelChoices?.reachable != true ||
+ _modelChoices?.canRunLocally(modelSelectionEngine) != true) {
+ return false;
+ }
+ final entry = models?.entries[row?.modelId];
+ final owner = entry?.controller;
+ final model = entry?.local;
+ return model != null &&
+ owner != null &&
+ entry!.own &&
+ model.downloaded &&
+ !model.running &&
+ model.canStart &&
+ owner.inventoryAvailable &&
+ !owner.busy &&
+ owner.machine?.connectionStatus == ConnectionStatus.connected &&
+ owner.machine?.needsLink == false &&
+ owner.machine?.isOffline == false;
+ }
+
+ /// Explicit Enter on installed weights starts once, then waits for the host
+ /// and the pane's serving picture before selecting. Closing the picker only
+ /// cancels the pending switch; the daemon continues its start operation.
+ Future<GridModel?> startModelForUse(
+ SwarmDestination row, {
+ required bool Function() stillCurrent,
+ Duration timeout = const Duration(minutes: 3),
+ }) async {
+ if (usingModelId != null || !canStartModelForUse(row)) return null;
+ final entry = models!.entries[row.modelId]!;
+ final owner = entry.controller!;
+ final modelId = entry.local!.id;
+ final host = owner.machine;
+ final deadline = DateTime.now().add(timeout);
+ usingModelId = row.modelId;
+ modelUseErrorId = modelUseError = null;
+ notifyListeners();
+ bool current() =>
+ !_disposed && stillCurrent() && identical(owner.machine, host);
+ void fail(String message) {
+ modelUseErrorId = row.modelId;
+ modelUseError = message;
+ }
+
+ try {
+ await owner.control(entry.local!, 'start');
+ while (current()) {
+ if (host?.connectionStatus != ConnectionStatus.connected ||
+ host?.needsLink == true ||
+ host?.isOffline == true) {
+ fail('Reconnect to ${entry.node} to use this model.');
+ return null;
+ }
+ final model = owner.localModels
+ .where((model) => model.id == modelId)
+ .firstOrNull;
+ final operation = model == null ? null : owner.operationFor(model);
+ if (operation?.failed == true || (owner.error != null && !owner.busy)) {
+ fail(
+ operation?.error ??
+ owner.error ??
+ 'Could not start this model. Try again.',
+ );
+ return null;
+ }
+ if (model?.running == true && operation?.active != true) {
+ await models!.manager.refresh(force: true);
+ if (!current()) return null;
+ final machineId = _modelSelectionMachineId;
+ if (machineId != null) {
+ final picture = await app.readGridPicture(machineId);
+ if (!current()) return null;
+ _modelChoices = picture;
+ }
+ final selected = selectableGridModel(row);
+ if (selected != null) return selected;
+ }
+ if (DateTime.now().isAfter(deadline)) {
+ fail(
+ 'The model is still starting. Try Enter again when it is ready.',
+ );
+ return null;
+ }
+ _modelUseWait = Completer<void>();
+ _modelUseTimer = Timer(const Duration(seconds: 2), () {
+ if (_modelUseWait?.isCompleted == false) _modelUseWait!.complete();
+ });
+ await _modelUseWait!.future;
+ _modelUseWait = null;
+ _modelUseTimer = null;
+ if (!current()) return null;
+ await owner.refresh();
+ }
+ } catch (_) {
+ if (current()) fail('Could not use this model. Try again.');
+ } finally {
+ if (!_disposed) {
+ usingModelId = null;
+ notifyListeners();
+ }
+ }
+ return null;
+ }
+
+ void setManaging(bool value) {
+ if (_disposed || managing == value) return;
+ managing = value;
+ notifyListeners();
+ }
+
final bool commandsOnly;
SessionFilter sessionFilter = SessionFilter.all;
SessionSort sessionSort = SessionSort.recent;
@@ -213,14 +506,14 @@ class SwarmSearchController extends ChangeNotifier {
? '?'
: '';
String get createLabel => isMachineMode
- ? 'New Machine'
+ ? 'Add machine'
: isModelMode
- ? 'New Model'
+ ? '[ Add ]'
: 'New Harness';
String get createDescription => isMachineMode
- ? 'Set up or link another computer.'
+ ? 'On the other computer:\n\n1. Install the app or CLI.\n2. Sign in to the same account.\n3. Set its password.\n\nThen select it here and Connect.'
: isModelMode
- ? 'Add a local model or connect an API.'
+ ? 'Connect an API. Select a local model to download or start it.'
: 'Choose a harness, machine, and project.';
SwarmGroupScope? _groupScope;
bool get canGoBack => _groupScope != null;
@@ -507,11 +800,21 @@ class SwarmSearchController extends ChangeNotifier {
};
String actionLabel(SwarmDestination? row) => row?.isCreate == true
- ? row!.title
+ ? isModelMode
+ ? 'Add'
+ : row!.title
+ : isModelDownloadsRow(row)
+ ? modelDownloadsVisible
+ ? 'Hide catalog'
+ : 'Get models'
+ : canSelectModel(row)
+ ? 'Use'
+ : canGetModel(row)
+ ? 'Get'
: row?.isModel == true
- ? models?.entries[row!.modelId]?.api != null
- ? 'Edit connection'
- : 'Open Model Manager'
+ ? 'Unavailable'
+ : setupLayout && row?.isMachine == true
+ ? 'Manage'
: row?.isStoreEntry == true
? 'Open in Store'
: row?.pickerQuery != null
@@ -769,6 +1072,11 @@ class SwarmSearchController extends ChangeNotifier {
(query.isNotEmpty && row.agentId != null)),
)
.toList();
+ if (isModelMode && matchQuery.trim().isEmpty && !modelDownloadsVisible) {
+ candidates = candidates
+ .where((row) => models?.entries[row.modelId]?.needsDownload != true)
+ .toList();
+ }
if (scopedBranch case final branch?) {
candidates = candidates.where((row) {
final machine = app.stateOf(row.machineId ?? '');
@@ -827,6 +1135,28 @@ class SwarmSearchController extends ChangeNotifier {
return name != 0 ? name : a.id.compareTo(b.id);
});
}
+ if (isMachineMode && matchQuery.trim().isEmpty) {
+ int priority(SwarmDestination row) {
+ final machine = app.stateOf(row.machineId!);
+ if (machine == null) return 3;
+ if (machine.isLocalMachine) return 1;
+ if (machine.isOffline) return 3;
+ if (machine.needsLink) return 0;
+ return machine.connectionStatus == ConnectionStatus.disconnected
+ ? 3
+ : 2;
+ }
+
+ rows.sort((a, b) {
+ final group = priority(a).compareTo(priority(b));
+ if (group != 0) return group;
+ final name = compareNatural(
+ a.title.toLowerCase(),
+ b.title.toLowerCase(),
+ );
+ return name != 0 ? name : a.id.compareTo(b.id);
+ });
+ }
if (byActivity &&
sessionFilter != SessionFilter.needsInput &&
(sessionFilter != SessionFilter.all ||
@@ -890,13 +1220,37 @@ class SwarmSearchController extends ChangeNotifier {
];
// When creation is available, keep its row outside the result order.
rows =
- resultsFromBottom ||
- navigating ||
- placement != null ||
- query.trim().isEmpty
+ !isMachineMode &&
+ (resultsFromBottom ||
+ navigating ||
+ placement != null ||
+ query.trim().isEmpty)
? [?create, ...found]
: [...found, ?create];
}
+ if (isModelMode) {
+ if (matchQuery.trim().isEmpty &&
+ models?.entries.values.any((entry) => entry.needsDownload) == true) {
+ rows = [
+ ...rows,
+ modelDownloadsVisible ? _hideDownloadsRow : _showDownloadsRow,
+ ];
+ }
+ final order = {for (final (index, row) in rows.indexed) row.id: index};
+ rows.sort((a, b) {
+ final section = modelSection(a).index.compareTo(modelSection(b).index);
+ if (section != 0) return section;
+ if (modelSection(a) != ModelSearchSection.local) {
+ final create = (a.isCreate ? 1 : 0).compareTo(b.isCreate ? 1 : 0);
+ return create != 0 ? create : order[a.id]!.compareTo(order[b.id]!);
+ }
+ final installed = (models?.entries[a.modelId]?.localRank ?? 1)
+ .compareTo(models?.entries[b.modelId]?.localRank ?? 1);
+ return installed != 0
+ ? installed
+ : order[a.id]!.compareTo(order[b.id]!);
+ });
+ }
// The parent stays above its children visually, but Enter after a query
// still targets the best match, including an agent nested under that parent.
final preferred =
@@ -938,7 +1292,9 @@ class SwarmSearchController extends ChangeNotifier {
if (first >= 0) cursor = first;
}
_selectedId = selected?.id;
- matchCount = rows.where((row) => !row.isCreate).length;
+ matchCount = rows
+ .where((row) => !row.isCreate && !isModelDownloadsRow(row))
+ .length;
}
/// With nothing typed, the commands run lately lead, newest first; the rest
@@ -1000,6 +1356,29 @@ class SwarmSearchController extends ChangeNotifier {
SwarmSearchSelection? submit([SwarmDestination? row]) {
final destination = row ?? selected;
if (destination == null || !canSubmit(destination)) return null;
+ if (isModelDownloadsRow(destination)) {
+ modelDownloadsVisible = !modelDownloadsVisible;
+ _filter();
+ if (modelDownloadsVisible) {
+ final index = rows.indexWhere(
+ (row) => models?.entries[row.modelId]?.needsDownload == true,
+ );
+ if (index >= 0) {
+ cursor = index;
+ _selectedId = selected!.id;
+ }
+ }
+ notifyListeners();
+ return null;
+ }
+ if (destination.isModel &&
+ !canSelectModel(destination) &&
+ !canGetModel(destination)) {
+ return null;
+ }
+ if (setupLayout && (destination.isMachine || destination.isModel)) {
+ return SwarmSearchSelection(destination);
+ }
if (isGroupMode && destination.isGroup) {
final group = _catalog
.where((row) => row.id == destination.id && row.isGroup)
@@ -1052,6 +1431,8 @@ class SwarmSearchController extends ChangeNotifier {
sessionFilter == SessionFilter.needsInput &&
_unavailableAttentionIds.contains(row?.id)
? false
+ : isModelDownloadsRow(row)
+ ? true
: row?.pickerQuery != null
? isHelpMode && _commandIds.contains(row!.id)
: row?.isModel == true
@@ -1130,9 +1511,12 @@ class SwarmSearchController extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
+ _modelUseTimer?.cancel();
+ if (_modelUseWait?.isCompleted == false) _modelUseWait!.complete();
app.removeListener(_refresh);
projects?.removeListener(_refresh);
models?.removeListener(_modelsChanged);
+ app.gridPictures.removeListener(_modelChoicesChanged);
app.sessionPreviews.removeListener(_previewChanged);
_previewPage.dispose();
_previewLine.dispose();
diff --git a/desktop/lib/widgets/api_picker_form.dart b/desktop/lib/widgets/api_picker_form.dart
new file mode 100644
index 000000000..0486e0ec0
--- /dev/null
+++ b/desktop/lib/widgets/api_picker_form.dart
@@ -0,0 +1,592 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../models/api_connections_controller.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import '../terminal/terminal_text.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
+import 'box_chrome.dart' show ReadlineKeys;
+import 'terminal_text_action.dart';
+
+/// API setup uses the same preview, keymap, and controller as the model list.
+/// Secret text belongs only to this editor and is cleared when it closes.
+class ApiPickerForm extends StatefulWidget {
+ const ApiPickerForm({
+ super.key,
+ required this.controller,
+ required this.onClose,
+ required this.onFocusChanged,
+ this.onSwitchPane,
+ this.connectionId,
+ this.removing = false,
+ });
+ final ApiConnectionsController controller;
+ final String? connectionId;
+ final bool removing;
+ final ValueChanged<String?> onClose;
+ final ValueChanged<bool> onFocusChanged;
+ final VoidCallback? onSwitchPane;
+
+ @override
+ State<ApiPickerForm> createState() => ApiPickerFormState();
+}
+
+class ApiPickerFormState extends State<ApiPickerForm> {
+ final _scope = FocusNode(debugLabel: 'API editor');
+ final _fields = <String, TextEditingController>{};
+ final _inputs = <String, FocusNode>{};
+ final _buttons = <String, FocusNode>{};
+ ApiConnection? _editing;
+ bool _advanced = false, _visible = false;
+ String? _error;
+ ApiConnectionsController get controller => widget.controller;
+ bool get _existing => _editing?.id.isNotEmpty == true;
+ bool get _enabled => controller.available && !controller.saving;
+ bool get _composing => _fields.values.any(
+ (field) =>
+ field.value.composing.isValid && !field.value.composing.isCollapsed,
+ );
+
+ @override
+ void initState() {
+ super.initState();
+ final existing = controller.connections
+ .where((row) => row.id == widget.connectionId)
+ .firstOrNull;
+ if (existing != null) _setConnection(existing);
+ if (!controller.loaded && !controller.loading) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && !controller.loaded && !controller.loading) {
+ unawaited(controller.refresh());
+ }
+ });
+ }
+ focus();
+ }
+
+ void _setConnection(ApiConnection connection) {
+ final preset = controller.presets
+ .where((row) => row.provider == connection.provider)
+ .firstOrNull;
+ _editing = ApiConnection({...?preset?.data, ...connection.data});
+ var name = connection.name;
+ if (connection.id.isEmpty) {
+ var suffix = 2;
+ while (controller.connections.any(
+ (row) => row.name.toLowerCase() == name.toLowerCase(),
+ )) {
+ name = '${connection.name} ${suffix++}';
+ }
+ if (connection.provider == 'custom') name = '';
+ }
+ for (final entry in {
+ 'name': name,
+ 'url': _editing!.baseUrl,
+ 'key': '',
+ 'environment': _editing!.keyEnv,
+ 'header': _editing!.authHeader,
+ 'prefix': _editing!.authPrefix,
+ }.entries) {
+ _fields.putIfAbsent(entry.key, TextEditingController.new).text =
+ entry.value;
+ _inputs.putIfAbsent(
+ entry.key,
+ () => FocusNode(debugLabel: 'API ${entry.key}'),
+ );
+ }
+ _advanced = false;
+ _visible = false;
+ _error = null;
+ }
+
+ void _choose(ApiConnection connection) {
+ if (!_enabled) return;
+ setState(() => _setConnection(connection));
+ focus();
+ }
+
+ List<String> get _visibleFields => _editing == null || widget.removing
+ ? []
+ : [
+ if (_editing!.provider == 'custom' || _advanced) ...['name', 'url'],
+ 'key',
+ if (_advanced) ...['environment', 'header', 'prefix'],
+ ];
+
+ List<({String id, String label, VoidCallback? run})> get _actions {
+ if (widget.removing) {
+ return [
+ (id: 'delete', label: 'Delete', run: _enabled ? _remove : null),
+ (id: 'cancel', label: 'Cancel', run: () => widget.onClose(null)),
+ ];
+ }
+ if (_editing == null) {
+ return [
+ for (final preset in controller.presets.where(
+ (row) => row.provider != 'openai' && row.provider != 'anthropic',
+ ))
+ (
+ id: 'provider:${preset.provider}',
+ label: preset.name,
+ run: _enabled ? () => _choose(preset) : null,
+ ),
+ (
+ id: 'provider:custom',
+ label: 'Custom API',
+ run: _enabled
+ ? () => _choose(
+ const ApiConnection({
+ 'provider': 'custom',
+ 'name': 'Custom API',
+ }),
+ )
+ : null,
+ ),
+ if (controller.error != null)
+ (
+ id: 'retry',
+ label: 'Retry',
+ run: controller.loading
+ ? null
+ : () => unawaited(controller.refresh()),
+ ),
+ (id: 'cancel', label: 'Cancel', run: () => widget.onClose(null)),
+ ];
+ }
+ return [
+ (id: 'save', label: 'Save', run: _enabled ? _save : null),
+ (
+ id: 'visibility',
+ label: _visible ? 'Hide' : 'Show',
+ run: () => setState(() => _visible = !_visible),
+ ),
+ (
+ id: 'options',
+ label: 'Options',
+ run: () => setState(() => _advanced = !_advanced),
+ ),
+ if (_editing!.keyUrl != null)
+ (id: 'key-page', label: 'Get key', run: _openKeyPage),
+ if (!_existing)
+ (
+ id: 'back',
+ label: 'Back',
+ run: () {
+ setState(() {
+ _fields['key']?.clear();
+ _editing = null;
+ _error = null;
+ });
+ focus();
+ },
+ ),
+ (id: 'cancel', label: 'Cancel', run: () => widget.onClose(null)),
+ ];
+ }
+
+ List<FocusNode> get _nodes => [
+ for (final id in _visibleFields) _inputs[id]!,
+ for (final action in _actions)
+ if (action.run != null && _buttons[action.id] != null)
+ _buttons[action.id]!,
+ ];
+
+ FocusNode get _focusTarget =>
+ (widget.removing ? _buttons['cancel'] : _nodes.firstOrNull) ?? _scope;
+
+ void focus() {
+ if (_focusTarget.context != null) {
+ _focusTarget.requestFocus();
+ } else {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _focusTarget.requestFocus();
+ });
+ }
+ }
+
+ void _move(bool forward, {bool buttonsOnly = false}) {
+ if (_composing) return;
+ final nodes = _nodes
+ .where((node) => !buttonsOnly || _buttons.containsValue(node))
+ .toList();
+ if (nodes.isEmpty) return;
+ final current = nodes.indexWhere((node) => node.hasFocus);
+ final next = current < 0
+ ? 0
+ : (current + (forward ? 1 : -1)) % nodes.length;
+ nodes[next].requestFocus();
+ if (nodes[next].context case final context?) {
+ Scrollable.ensureVisible(context);
+ }
+ }
+
+ bool handle(String command) {
+ if (_composing) return true;
+ switch (command) {
+ case 'picker.cancel':
+ widget.onClose(null);
+ case 'picker.accept':
+ _scope.hasFocus ? _accept() : focus();
+ case 'picker.complete':
+ widget.onSwitchPane != null ? widget.onSwitchPane!() : _move(true);
+ case 'picker.complete_back':
+ widget.onSwitchPane != null ? widget.onSwitchPane!() : _move(false);
+ case 'picker.next':
+ if (!_scope.hasFocus) return false;
+ _move(true);
+ case 'picker.previous':
+ if (!_scope.hasFocus) return false;
+ _move(false);
+ default:
+ return false;
+ }
+ return true;
+ }
+
+ void _accept() {
+ if (_composing) return;
+ final action = _actions
+ .where((a) => _buttons[a.id]?.hasFocus == true)
+ .firstOrNull;
+ if (action != null) {
+ action.run?.call();
+ } else if (_editing != null && !widget.removing) {
+ unawaited(_save());
+ }
+ }
+
+ Future<void> _save() async {
+ if (!_enabled || _composing) return;
+ final url = Uri.tryParse(_fields['url']!.text.trim());
+ final invalid = _fields['name']!.text.trim().isEmpty
+ ? 'Enter a name.'
+ : url == null ||
+ !['http', 'https'].contains(url.scheme) ||
+ url.host.isEmpty ||
+ url.userInfo.isNotEmpty ||
+ url.hasQuery ||
+ url.hasFragment
+ ? 'Enter an API URL without credentials or query parameters.'
+ : !_existing && _fields['key']!.text.trim().isEmpty
+ ? 'Enter an API key.'
+ : _fields['header']!.text.trim().isEmpty
+ ? 'Enter an authentication header.'
+ : null;
+ if (invalid != null) {
+ setState(() => _error = invalid);
+ return;
+ }
+ final editing = _editing!;
+ if (_existing &&
+ !controller.connections.any((row) => row.id == editing.id)) {
+ setState(() => _error = 'This API was removed. Return to the list.');
+ return;
+ }
+ setState(() => _error = null);
+ final name = _fields['name']!.text.trim();
+ final saved = await controller.save({
+ if (_existing) 'id': editing.id,
+ 'provider': editing.provider,
+ 'name': name,
+ 'baseUrl': _fields['url']!.text.trim(),
+ 'keyEnv': _fields['environment']!.text.trim(),
+ 'authHeader': _fields['header']!.text.trim(),
+ 'authPrefix': _fields['prefix']!.text,
+ 'apiKey': _fields['key']!.text,
+ });
+ if (!mounted || !saved) return;
+ _fields['key']!.clear();
+ final id = controller.connections
+ .where((row) => row.name == name)
+ .firstOrNull
+ ?.id;
+ widget.onClose(id);
+ }
+
+ Future<void> _remove() async {
+ if (!_enabled || _editing == null) return;
+ if (await controller.remove(_editing!.id) && mounted) widget.onClose('');
+ }
+
+ Future<void> _openKeyPage() async {
+ try {
+ final opened = await launchUrl(
+ Uri.parse(_editing!.keyUrl!),
+ mode: LaunchMode.externalApplication,
+ );
+ if (!opened && mounted) {
+ setState(() => _error = 'Could not open the browser. Try again.');
+ }
+ } catch (_) {
+ if (mounted) {
+ setState(() => _error = 'Could not open the browser. Try again.');
+ }
+ }
+ }
+
+ Widget _keys(Widget child, {bool buttons = false}) {
+ if (KeymapTheme.of(context) != null) {
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: () => _composing,
+ actions: {
+ for (final command in [
+ 'picker.accept',
+ 'picker.cancel',
+ 'picker.complete',
+ 'picker.complete_back',
+ 'picker.next',
+ 'picker.previous',
+ ])
+ command: () => handle(command),
+ if (buttons) ...{
+ 'picker.control_next': () => _move(true, buttonsOnly: true),
+ 'picker.control_previous': () => _move(false, buttonsOnly: true),
+ },
+ },
+ child: child,
+ );
+ }
+ return CallbackShortcuts(
+ bindings: {
+ const SingleActivator(
+ LogicalKeyboardKey.enter,
+ includeRepeats: false,
+ ): () =>
+ handle('picker.accept'),
+ const SingleActivator(LogicalKeyboardKey.escape): () =>
+ handle('picker.cancel'),
+ const SingleActivator(LogicalKeyboardKey.tab): () =>
+ handle('picker.complete'),
+ const SingleActivator(LogicalKeyboardKey.tab, shift: true): () =>
+ handle('picker.complete_back'),
+ const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
+ handle('picker.next'),
+ const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
+ handle('picker.previous'),
+ if (buttons) ...{
+ const SingleActivator(LogicalKeyboardKey.arrowRight): () =>
+ _move(true, buttonsOnly: true),
+ const SingleActivator(LogicalKeyboardKey.arrowLeft): () =>
+ _move(false, buttonsOnly: true),
+ },
+ },
+ child: child,
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
+ final cell = terminalCellSizeOf(context);
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ final style = terminalContentStyle(color: theme.foreground);
+ final muted = terminalContentStyle(
+ color: theme.foreground.withValues(alpha: .54),
+ );
+ return ListenableBuilder(
+ listenable: controller,
+ builder: (context, _) => _keys(
+ Focus(
+ focusNode: _scope,
+ onFocusChange: widget.onFocusChanged,
+ onKeyEvent: (_, event) {
+ if (KeymapTheme.of(context) != null &&
+ _inputs.values.any((node) => node.hasFocus) &&
+ (event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter)) {
+ return _composing
+ ? KeyEventResult.skipRemainingHandlers
+ : KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(
+ child: SingleChildScrollView(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ widget.removing
+ ? 'Delete ${_editing?.name ?? 'API'}?'
+ : _editing?.name ?? 'Add API',
+ style: style,
+ ),
+ SizedBox(height: cell.height),
+ if (_editing != null &&
+ !widget.removing &&
+ _editing!.provider != 'custom')
+ Text(_editing!.baseUrl, style: muted),
+ if (widget.removing)
+ Text(
+ 'Remove this saved connection and key?',
+ style: style,
+ ),
+ if (controller.loading && !controller.saving)
+ Text('Loading APIs…', style: muted),
+ for (final id in _visibleFields)
+ Padding(
+ padding: EdgeInsets.only(bottom: cell.height),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(switch (id) {
+ 'url' => 'URL',
+ 'key' =>
+ _existing
+ ? 'Key (blank keeps saved key)'
+ : 'Key',
+ 'environment' => 'Key environment variable',
+ 'header' => 'Authentication header',
+ 'prefix' => 'Key prefix',
+ _ => 'Name',
+ }, style: muted),
+ ReadlineKeys(
+ controller: _fields[id]!,
+ enabled: !controller.saving,
+ onChanged: (_) {
+ if (_error != null) {
+ setState(() => _error = null);
+ }
+ },
+ child: TextField(
+ key: ValueKey('api-form-input:$id'),
+ controller: _fields[id],
+ focusNode: _inputs[id],
+ readOnly: controller.saving,
+ onTapOutside: (_) {},
+ obscureText: id == 'key' && !_visible,
+ autocorrect: false,
+ enableSuggestions: false,
+ style: style,
+ cursorColor: theme.foreground,
+ cursorWidth: 2,
+ decoration: const InputDecoration(
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ filled: false,
+ isDense: true,
+ isCollapsed: true,
+ constraints: BoxConstraints(),
+ contentPadding: EdgeInsets.zero,
+ ),
+ onEditingComplete: () {},
+ onChanged: (_) {
+ if (_error != null) {
+ setState(() => _error = null);
+ }
+ },
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (_editing != null && !widget.removing) ...[
+ Text('Stored on this computer.', style: muted),
+ SizedBox(height: cell.height),
+ ],
+ if (_error ?? controller.error case final error?) ...[
+ Text(
+ error,
+ style: terminalContentStyle(color: theme.yellow),
+ ),
+ SizedBox(height: cell.height),
+ ],
+ if (controller.saving) ...[
+ Text('Saving…', style: muted),
+ SizedBox(height: cell.height),
+ ],
+ _keys(
+ Wrap(
+ direction: _editing == null
+ ? Axis.vertical
+ : Axis.horizontal,
+ spacing: cell.width * 2,
+ runSpacing: cell.height,
+ children: [
+ for (final action in _actions)
+ TerminalTextAction(
+ key: ValueKey('api-form:${action.id}'),
+ label: action.label,
+ padding: EdgeInsets.zero,
+ focusNode: _buttons.putIfAbsent(
+ action.id,
+ () => FocusNode(debugLabel: action.label),
+ ),
+ onPressed: action.run,
+ ),
+ ],
+ ),
+ buttons: true,
+ ),
+ ],
+ ),
+ ),
+ ),
+ Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: Text(
+ [
+ for (final (command, label) in [
+ (
+ 'picker.accept',
+ _editing == null || widget.removing ? 'select' : 'save',
+ ),
+ (
+ 'picker.complete',
+ widget.onSwitchPane != null ? 'pane' : 'next',
+ ),
+ ('picker.cancel', 'back'),
+ ])
+ if (effectiveCommandHint(
+ context,
+ command,
+ contextKind: KeymapContext.picker,
+ )
+ case final hint?)
+ '${hint.replaceAll('⇥', 'Tab').replaceAll('↵', 'Enter')} $label',
+ ].join(' · '),
+ style: muted,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ @override
+ void dispose() {
+ _scope.dispose();
+ for (final field in _fields.values) {
+ field.clear();
+ field.dispose();
+ }
+ for (final node in [..._inputs.values, ..._buttons.values]) {
+ node.dispose();
+ }
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/widgets/grid_model_picker.dart b/desktop/lib/widgets/grid_model_picker.dart
index 0a430b02e..5dff21272 100644
--- a/desktop/lib/widgets/grid_model_picker.dart
+++ b/desktop/lib/widgets/grid_model_picker.dart
@@ -64,6 +64,9 @@ class GridModelPicker extends StatefulWidget {
final AppNotifier notifier;
final String machineId;
+ /// Uses the shared resource picker while keeping this control's live label.
+ final VoidCallback? onOpen;
+
/// Called with the chosen grid model.
final ValueChanged<GridModel>? onSelected;
@@ -104,6 +107,7 @@ class GridModelPicker extends StatefulWidget {
super.key,
required this.notifier,
required this.machineId,
+ this.onOpen,
this.onSelected,
this.onUseOwnLogin,
this.onRunLocalModel,
@@ -329,6 +333,10 @@ class _GridModelPickerState extends State<GridModelPicker> {
Future<void> _open() async {
if (_loading || !widget.enabled) return;
+ if (widget.onOpen case final open?) {
+ open();
+ return;
+ }
// A warm answer opens the menu with no wait at all. It is at most seconds old — the daemon's own
// memo is what bounds that — and the refresh below lands in time for the next open.
final GridModels answer;
diff --git a/desktop/lib/widgets/link_machine_dialog.dart b/desktop/lib/widgets/link_machine_dialog.dart
index deb75ed87..2dcd3bbfe 100644
--- a/desktop/lib/widgets/link_machine_dialog.dart
+++ b/desktop/lib/widgets/link_machine_dialog.dart
@@ -13,7 +13,11 @@ import '../terminal/terminal_text.dart';
import 'box_chrome.dart';
/// This computer's incoming password and, separately, its outgoing links.
-Future<void> showLinkMachineDialog(BuildContext context, AppNotifier notifier) {
+Future<void> showLinkMachineDialog(
+ BuildContext context,
+ AppNotifier notifier, {
+ bool passwordOnly = false,
+}) {
final keymap = KeymapTheme.of(context, listen: false);
return showAppDialog<void>(
context: context,
@@ -21,7 +25,10 @@ Future<void> showLinkMachineDialog(BuildContext context, AppNotifier notifier) {
veilBlur: 0,
veilTint: Colors.transparent,
builder: (_) {
- final dialog = _LinkMachineDialog(notifier: notifier);
+ final dialog = _LinkMachineDialog(
+ notifier: notifier,
+ passwordOnly: passwordOnly,
+ );
return keymap == null
? dialog
: KeymapProvider(keymap: keymap, child: dialog);
@@ -32,8 +39,12 @@ Future<void> showLinkMachineDialog(BuildContext context, AppNotifier notifier) {
enum _Page { password, clear, links, unlink }
class _LinkMachineDialog extends StatefulWidget {
- const _LinkMachineDialog({required this.notifier});
+ const _LinkMachineDialog({
+ required this.notifier,
+ required this.passwordOnly,
+ });
final AppNotifier notifier;
+ final bool passwordOnly;
@override
State<_LinkMachineDialog> createState() => _LinkMachineDialogState();
}
@@ -619,15 +630,17 @@ class _LinkMachineDialogState extends State<_LinkMachineDialog> {
style: boxMonoStyle(color: kBoxFaint),
),
],
- const SizedBox(height: 12),
- Align(
- alignment: Alignment.centerLeft,
- child: _button(
- 'Links from this computer…',
- _busy ? null : _links,
- key: const Key('remote-password-links-button'),
+ if (!widget.passwordOnly) ...[
+ const SizedBox(height: 12),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: _button(
+ 'Links from this computer…',
+ _busy ? null : _links,
+ key: const Key('remote-password-links-button'),
+ ),
),
- ),
+ ],
];
}
diff --git a/desktop/lib/widgets/machine_picker_form.dart b/desktop/lib/widgets/machine_picker_form.dart
new file mode 100644
index 000000000..7fb83cf01
--- /dev/null
+++ b/desktop/lib/widgets/machine_picker_form.dart
@@ -0,0 +1,762 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../auth/cli_link.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import '../state/app_state.dart';
+import '../terminal/terminal_text.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
+import 'box_chrome.dart' show ReadlineKeys;
+import 'link_another_machine_dialog.dart'
+ show
+ kHarnessDownloadUrl,
+ kLinkServerInstallCommand,
+ kLinkServerLoginCommand,
+ kLinkServerStartCommand;
+import 'terminal_text_action.dart';
+
+enum MachinePickerFormKind { connect, rename, password, delete, app, cli }
+
+/// An editor in the resource preview, not another route or machine picker.
+/// Pending writes belong to AppNotifier and survive leaving this editor.
+class MachinePickerForm extends StatefulWidget {
+ const MachinePickerForm({
+ super.key,
+ required this.app,
+ required this.kind,
+ required this.onClose,
+ required this.onFocusChanged,
+ this.onSwitchPane,
+ this.machineId,
+ });
+ final AppNotifier app;
+ final MachinePickerFormKind kind;
+ final String? machineId;
+ final ValueChanged<String?> onClose;
+ final ValueChanged<bool> onFocusChanged;
+ final VoidCallback? onSwitchPane;
+
+ @override
+ State<MachinePickerForm> createState() => MachinePickerFormState();
+}
+
+class MachinePickerFormState extends State<MachinePickerForm> {
+ final _scope = FocusNode(debugLabel: 'Machine editor');
+ final _input = FocusNode(debugLabel: 'Machine value');
+ final _confirmation = FocusNode(debugLabel: 'Confirm password');
+ final _buttons = <String, FocusNode>{};
+ final _value = TextEditingController();
+ final _confirm = TextEditingController();
+ RemotePasswordStatus? _passwordStatus;
+ bool _busy = false, _loading = false, _editingPassword = false;
+ bool _clearConfirmation = false, _showPassword = false;
+ String? _message;
+ bool _error = false;
+ int _clipboardRevision = 0;
+
+ AppNotifier get app => widget.app;
+ MachineState? get machine => app.stateOf(widget.machineId ?? '');
+ bool get _password => widget.kind == MachinePickerFormKind.password;
+ bool get _setup =>
+ widget.kind == MachinePickerFormKind.app ||
+ widget.kind == MachinePickerFormKind.cli;
+ bool get _hasInput =>
+ widget.kind == MachinePickerFormKind.rename ||
+ widget.kind == MachinePickerFormKind.connect ||
+ (_password && _editingPassword && !_clearConfirmation && !_loading);
+ bool get _composing => [_value, _confirm].any(
+ (controller) =>
+ controller.value.composing.isValid &&
+ !controller.value.composing.isCollapsed,
+ );
+
+ @override
+ void initState() {
+ super.initState();
+ if (widget.kind == MachinePickerFormKind.rename) {
+ _value.text =
+ app.pendingMachineName(widget.machineId!) ??
+ machine?.machine.displayName ??
+ '';
+ _value.selection = TextSelection(
+ baseOffset: 0,
+ extentOffset: _value.text.length,
+ );
+ }
+ final pending = switch (widget.kind) {
+ MachinePickerFormKind.connect => app.pendingMachineLink(
+ widget.machineId!,
+ ),
+ MachinePickerFormKind.rename => app.pendingMachineRename(
+ widget.machineId!,
+ ),
+ MachinePickerFormKind.delete => app.pendingMachineDelete(
+ widget.machineId!,
+ ),
+ _ => null,
+ };
+ if (pending != null) {
+ _busy = true;
+ unawaited(_finish(pending));
+ } else if (_password) {
+ if (app.pendingRemotePasswordChange case final pending?) {
+ _busy = true;
+ _clearConfirmation = app.clearingRemotePassword;
+ unawaited(_finish(pending.then((status) => status.error)));
+ } else {
+ unawaited(_loadPassword());
+ }
+ }
+ focus();
+ }
+
+ @override
+ void dispose() {
+ _scope.dispose();
+ _input.dispose();
+ _confirmation.dispose();
+ for (final node in _buttons.values) {
+ node.dispose();
+ }
+ _value.dispose();
+ _confirm.dispose();
+ super.dispose();
+ }
+
+ FocusNode get _focusTarget => _hasInput && !_busy
+ ? _input
+ : _buttons[widget.kind == MachinePickerFormKind.delete || _busy
+ ? 'Cancel'
+ : _actions.firstOrNull?.label] ??
+ _scope;
+
+ void focus() {
+ if (_focusTarget.context != null) {
+ _focusTarget.requestFocus();
+ } else {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _focusTarget.requestFocus();
+ });
+ }
+ }
+
+ List<FocusNode> get _nodes => [
+ if (_hasInput) _input,
+ if (_hasInput && _password) _confirmation,
+ for (final action in _actions)
+ if (action.run != null && _buttons[_buttonId(action.label)] != null)
+ _buttons[_buttonId(action.label)]!,
+ ];
+
+ void _move(bool forward, {bool buttonsOnly = false}) {
+ if (_composing) return;
+ final nodes = _nodes
+ .where((node) => !buttonsOnly || _buttons.containsValue(node))
+ .toList();
+ if (nodes.isEmpty) return;
+ final current = nodes.indexWhere((node) => node.hasFocus);
+ final index = current < 0
+ ? 0
+ : (current + (forward ? 1 : -1)) % nodes.length;
+ final node = nodes[index];
+ node.requestFocus();
+ if (node.context case final context?) Scrollable.ensureVisible(context);
+ }
+
+ bool handle(String command) {
+ if (_composing) return true;
+ switch (command) {
+ case 'picker.cancel':
+ widget.onClose(null);
+ case 'picker.accept':
+ if (!_scope.hasFocus) {
+ focus();
+ } else {
+ _accept();
+ }
+ case 'picker.complete':
+ _tab(true);
+ case 'picker.complete_back':
+ _tab(false);
+ case 'picker.next' || 'picker.previous':
+ if (!_scope.hasFocus) return false;
+ _move(command == 'picker.next');
+ default:
+ return false;
+ }
+ return true;
+ }
+
+ void _tab(bool forward) {
+ if (_composing) return;
+ widget.onSwitchPane != null ? widget.onSwitchPane!() : _move(forward);
+ }
+
+ void _accept() {
+ if (_composing) return;
+ final action = _actions
+ .where((a) => _buttons[_buttonId(a.label)]?.hasFocus == true)
+ .firstOrNull;
+ if (action != null) {
+ action.run?.call();
+ } else if (_hasInput && !_busy) {
+ if (_password && _input.hasFocus && _value.text.isNotEmpty) {
+ _confirmation.requestFocus();
+ } else {
+ _submit();
+ }
+ }
+ }
+
+ Future<void> _loadPassword() async {
+ setState(() {
+ _loading = true;
+ _message = null;
+ });
+ final status = await app.remotePasswordStatus();
+ if (!mounted) return;
+ setState(() {
+ _loading = false;
+ _passwordStatus = status.error == null ? status : null;
+ _editingPassword = status.error == null && !status.hasPassword;
+ _message = status.error;
+ _error = status.error != null;
+ });
+ focus();
+ }
+
+ void _say(String message, {bool error = true}) {
+ setState(() {
+ _message = message;
+ _error = error;
+ });
+ }
+
+ void _submit() {
+ if (_busy || _loading || _composing || _setup) return;
+ if (machine == null || machine!.machine.isShared) {
+ _say('This machine is no longer available to manage.');
+ return;
+ }
+ if (widget.kind == MachinePickerFormKind.connect &&
+ (machine!.isLocalMachine ||
+ !machine!.needsLink ||
+ machine!.isOffline)) {
+ _say(
+ machine!.isOffline
+ ? 'This machine is offline.'
+ : 'This machine is already connected.',
+ );
+ return;
+ }
+ if (_hasInput) {
+ if (widget.kind == MachinePickerFormKind.rename
+ ? _value.text.trim().isEmpty
+ : _value.text.isEmpty) {
+ _say(
+ widget.kind == MachinePickerFormKind.rename
+ ? 'Enter a name.'
+ : 'Enter a password.',
+ );
+ _input.requestFocus();
+ return;
+ }
+ if (widget.kind != MachinePickerFormKind.rename &&
+ _value.text.contains(RegExp(r'[\r\n]'))) {
+ _say('Use a password on one line.');
+ _input.requestFocus();
+ return;
+ }
+ if (_password && _value.text != _confirm.text) {
+ _say('Passwords do not match.');
+ _confirmation.requestFocus();
+ return;
+ }
+ }
+ final request = switch (widget.kind) {
+ MachinePickerFormKind.connect => app.connectWithPassword(
+ widget.machineId!,
+ _value.text,
+ ),
+ MachinePickerFormKind.rename => app.renameMachine(
+ widget.machineId!,
+ _value.text.trim(),
+ ),
+ MachinePickerFormKind.delete => app.deleteMachine(widget.machineId!),
+ MachinePickerFormKind.password when machine!.isLocalMachine =>
+ _clearConfirmation
+ ? app.clearRemotePassword()
+ : app.setRemotePassword(_value.text).then((result) => result.error),
+ _ => null,
+ };
+ if (request == null) return;
+ setState(() {
+ _busy = true;
+ _message = null;
+ });
+ _buttons['Cancel']?.requestFocus();
+ unawaited(_finish(request));
+ }
+
+ Future<void> _finish(Future<String?> request) async {
+ String? error;
+ try {
+ error = await request;
+ } catch (_) {
+ error = 'Could not finish. Try again.';
+ }
+ if (!mounted) return;
+ if (error == null) {
+ _value.clear();
+ _confirm.clear();
+ widget.onClose(
+ _password
+ ? (_clearConfirmation ? 'Password cleared.' : 'Password saved.')
+ : null,
+ );
+ return;
+ }
+ setState(() {
+ _busy = false;
+ _message = error;
+ _error = true;
+ });
+ if (_password && _passwordStatus == null) {
+ // A reopened request has no password buffer or trusted status yet.
+ await _loadPassword();
+ if (mounted) _say(error);
+ }
+ focus();
+ }
+
+ Future<void> _copy() async {
+ final revision = ++_clipboardRevision;
+ final cli = widget.kind == MachinePickerFormKind.cli;
+ try {
+ await Clipboard.setData(
+ ClipboardData(
+ text: cli
+ ? '$kLinkServerInstallCommand\n$kLinkServerLoginCommand\n$kLinkServerStartCommand'
+ : kHarnessDownloadUrl.toString(),
+ ),
+ );
+ if (mounted && revision == _clipboardRevision) {
+ _say(
+ cli ? 'Copied. Run on the other computer.' : 'Download link copied.',
+ error: false,
+ );
+ }
+ } catch (_) {
+ if (mounted && revision == _clipboardRevision) {
+ _say('Could not copy. Select the text to copy it.');
+ }
+ }
+ }
+
+ Future<void> _download() async {
+ try {
+ if (await launchUrl(
+ kHarnessDownloadUrl,
+ mode: LaunchMode.externalApplication,
+ )) {
+ return;
+ }
+ } catch (_) {
+ /* Keep recovery beside the download link. */
+ }
+ if (mounted) {
+ _say('Could not open the browser. Copy the download link instead.');
+ }
+ }
+
+ List<({String label, VoidCallback? run})> get _actions {
+ void close() => widget.onClose(null);
+ if (_setup) {
+ return [
+ if (widget.kind == MachinePickerFormKind.app)
+ (label: 'Download', run: () => unawaited(_download())),
+ (label: 'Copy', run: () => unawaited(_copy())),
+ (label: 'Back', run: close),
+ ];
+ }
+ if (_password &&
+ !_busy &&
+ !_loading &&
+ !_editingPassword &&
+ !_clearConfirmation) {
+ if (_passwordStatus == null) {
+ return [
+ (label: 'Retry', run: () => unawaited(_loadPassword())),
+ (label: 'Cancel', run: close),
+ ];
+ }
+ return [
+ (
+ label: 'Change',
+ run: () {
+ setState(() {
+ _editingPassword = true;
+ _message = null;
+ });
+ focus();
+ },
+ ),
+ (
+ label: 'Clear',
+ run: () {
+ setState(() {
+ _clearConfirmation = true;
+ _message = null;
+ });
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _buttons['Cancel']?.requestFocus();
+ });
+ },
+ ),
+ (label: 'Cancel', run: close),
+ ];
+ }
+ return [
+ (
+ label: switch (widget.kind) {
+ MachinePickerFormKind.connect => 'Connect',
+ MachinePickerFormKind.delete => 'Delete',
+ _ => _clearConfirmation ? 'Clear' : 'Save',
+ },
+ run: _busy || _loading ? null : _submit,
+ ),
+ if (_hasInput && widget.kind != MachinePickerFormKind.rename)
+ (
+ label: _showPassword ? 'Hide' : 'Show',
+ run: () => setState(() => _showPassword = !_showPassword),
+ ),
+ (label: 'Cancel', run: close),
+ ];
+ }
+
+ String _buttonId(String label) =>
+ label == 'Show' || label == 'Hide' ? 'visibility' : label;
+
+ String get _progress => switch (widget.kind) {
+ MachinePickerFormKind.connect => switch (app.machineLinkStage(
+ widget.machineId!,
+ )) {
+ 'deriving_key' => 'Checking password…',
+ 'exchanging' || 'verifying' => 'Verifying the link…',
+ _ => 'Connecting…',
+ },
+ MachinePickerFormKind.delete => 'Deleting…',
+ _ => 'Saving…',
+ };
+
+ Map<String, VoidCallback> get _keyActions => {
+ 'picker.accept': _accept,
+ 'picker.cancel': () => widget.onClose(null),
+ 'picker.complete': () => _tab(true),
+ 'picker.complete_back': () => _tab(false),
+ 'picker.next': () => _move(true),
+ 'picker.previous': () => _move(false),
+ };
+
+ Widget _keys(Widget child, {bool buttons = false}) {
+ if (KeymapTheme.of(context) != null) {
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: () => _composing,
+ actions: {
+ ..._keyActions,
+ if (buttons) ...{
+ 'picker.control_next': () => _move(true, buttonsOnly: true),
+ 'picker.control_previous': () => _move(false, buttonsOnly: true),
+ },
+ },
+ child: child,
+ );
+ }
+ return CallbackShortcuts(
+ bindings: {
+ const SingleActivator(
+ LogicalKeyboardKey.enter,
+ includeRepeats: false,
+ ): () {
+ if (!_composing) _accept();
+ },
+ const SingleActivator(
+ LogicalKeyboardKey.numpadEnter,
+ includeRepeats: false,
+ ): () {
+ if (!_composing) _accept();
+ },
+ const SingleActivator(LogicalKeyboardKey.escape): () {
+ if (!_composing) widget.onClose(null);
+ },
+ const SingleActivator(LogicalKeyboardKey.tab): () => _tab(true),
+ const SingleActivator(LogicalKeyboardKey.tab, shift: true): () =>
+ _tab(false),
+ const SingleActivator(LogicalKeyboardKey.arrowDown): () => _move(true),
+ const SingleActivator(LogicalKeyboardKey.arrowUp): () => _move(false),
+ if (buttons) ...{
+ const SingleActivator(LogicalKeyboardKey.arrowRight): () =>
+ _move(true, buttonsOnly: true),
+ const SingleActivator(LogicalKeyboardKey.arrowLeft): () =>
+ _move(false, buttonsOnly: true),
+ },
+ },
+ child: child,
+ );
+ }
+
+ Widget _field(
+ String label,
+ TextEditingController controller,
+ FocusNode focus,
+ String key,
+ ) {
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ final cell = terminalCellSizeOf(context);
+ return Row(
+ children: [
+ SizedBox(
+ width: cell.width * 10,
+ child: Text(
+ '$label >',
+ style: terminalContentStyle(
+ color: theme.foreground.withValues(alpha: .54),
+ ),
+ ),
+ ),
+ Expanded(
+ child: ReadlineKeys(
+ controller: controller,
+ enabled: !_busy,
+ onChanged: (_) {
+ if (_message != null) setState(() => _message = null);
+ },
+ child: TextField(
+ key: ValueKey(key),
+ controller: controller,
+ focusNode: focus,
+ readOnly: _busy,
+ onTapOutside: (_) {},
+ obscureText:
+ widget.kind != MachinePickerFormKind.rename && !_showPassword,
+ enableSuggestions: false,
+ autocorrect: false,
+ style: terminalContentStyle(color: theme.foreground),
+ cursorColor: theme.foreground,
+ cursorWidth: 2,
+ decoration: const InputDecoration(
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ filled: false,
+ isDense: true,
+ isCollapsed: true,
+ constraints: BoxConstraints(),
+ contentPadding: EdgeInsets.zero,
+ ),
+ onEditingComplete: () {},
+ onChanged: (_) {
+ if (_message != null) setState(() => _message = null);
+ },
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ TerminalFontScope.watch(context);
+ final cell = terminalCellSizeOf(context);
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ Widget line(String text, {bool selectable = false}) => selectable
+ ? SelectableText(
+ text,
+ style: terminalContentStyle(color: theme.foreground),
+ )
+ : Text(text, style: terminalContentStyle(color: theme.foreground));
+ final gap = SizedBox(height: cell.height);
+ final name = machine?.machine.displayName ?? '';
+ final email = app.currentUser?.email;
+ final body = SingleChildScrollView(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ line(
+ _setup
+ ? 'Add machine · ${widget.kind == MachinePickerFormKind.app ? 'App' : 'CLI'}'
+ : name,
+ ),
+ gap,
+ if (_setup) ...[
+ line('On the other computer:'),
+ gap,
+ if (widget.kind == MachinePickerFormKind.app) ...[
+ line('1. Install Harness for macOS or Linux.'),
+ line(kHarnessDownloadUrl.toString(), selectable: true),
+ gap,
+ line(
+ '2. Sign in ${email == null ? 'to the same account' : 'as $email'}.',
+ ),
+ gap,
+ line(
+ '3. Set its password in Cmd P → @ → this computer → Password.',
+ ),
+ ] else ...[
+ line('1. Install the CLI (skip if installed).'),
+ line(kLinkServerInstallCommand, selectable: true),
+ gap,
+ line(
+ '2. Sign in ${email == null ? 'to the same account' : 'as $email'}.',
+ ),
+ line(kLinkServerLoginCommand, selectable: true),
+ gap,
+ line('3. Start Harness and set its password.'),
+ line(kLinkServerStartCommand, selectable: true),
+ ],
+ gap,
+ line('Then select the machine here and Connect.'),
+ ] else if (widget.kind == MachinePickerFormKind.delete) ...[
+ line('Delete this machine from your account?'),
+ line('Its panes in this window will close.'),
+ ] else if (_clearConfirmation) ...[
+ line('Clear this computer’s remote password?'),
+ line('New connections will need a password set again.'),
+ ] else if (_loading)
+ line('Checking password…')
+ else if (_password && !_editingPassword) ...[
+ if (_passwordStatus != null) line('Password is set.'),
+ ] else if (_hasInput) ...[
+ if (widget.kind == MachinePickerFormKind.rename)
+ line('Rename machine')
+ else
+ line(
+ _password
+ ? 'Set a password for other computers to connect here.'
+ : 'Enter the password set on $name.',
+ ),
+ gap,
+ _field(
+ widget.kind == MachinePickerFormKind.rename ? 'name' : 'password',
+ _value,
+ _input,
+ widget.kind == MachinePickerFormKind.rename
+ ? 'machine-rename-input'
+ : _password
+ ? 'remote-password-field'
+ : 'remote-password-connect-field',
+ ),
+ if (_password) ...[
+ gap,
+ _field(
+ 'confirm',
+ _confirm,
+ _confirmation,
+ 'remote-password-confirm-field',
+ ),
+ ],
+ ],
+ gap,
+ if (_busy || _message != null) ...[
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ _busy ? _progress : _message!,
+ style: terminalContentStyle(
+ color: !_busy && _error
+ ? theme.yellow
+ : theme.foreground.withValues(alpha: .54),
+ ),
+ ),
+ ),
+ gap,
+ ],
+ _keys(
+ Wrap(
+ spacing: cell.width * 2,
+ runSpacing: cell.height,
+ children: [
+ for (final action in _actions)
+ TerminalTextAction(
+ key: ValueKey('machine-form:${_buttonId(action.label)}'),
+ label: action.label,
+ padding: EdgeInsets.zero,
+ focusNode: _buttons.putIfAbsent(
+ _buttonId(action.label),
+ () => FocusNode(debugLabel: action.label),
+ ),
+ onPressed: action.run,
+ ),
+ ],
+ ),
+ buttons: true,
+ ),
+ ],
+ ),
+ );
+ String? hint(String command) => effectiveCommandHint(
+ context,
+ command,
+ contextKind: KeymapContext.picker,
+ )?.replaceAll('⇥', 'Tab').replaceAll('↵', 'Enter');
+ return _keys(
+ Focus(
+ focusNode: _scope,
+ onFocusChange: widget.onFocusChanged,
+ onKeyEvent: (_, event) {
+ // Do not let the editor's native Enter bypass a deliberate unbinding.
+ if (KeymapTheme.of(context) != null &&
+ (_input.hasFocus || _confirmation.hasFocus) &&
+ (event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter)) {
+ return _composing
+ ? KeyEventResult.skipRemainingHandlers
+ : KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(child: body),
+ Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: Text(
+ [
+ if (hint('picker.accept') case final enter?) '$enter select',
+ if (hint('picker.complete') case final tab?)
+ '$tab ${widget.onSwitchPane != null ? 'pane' : 'next'}',
+ if (hint('picker.cancel') case final escape?) '$escape back',
+ ].join(' · '),
+ style: terminalContentStyle(
+ color: theme.foreground.withValues(alpha: .54),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index 969acef0d..e48d65248 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -347,6 +347,15 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_revealRow();
}
+ void _switchPane() {
+ if (box.locked) return;
+ if (_picking) {
+ _backToRows();
+ } else if (_hasChoices) {
+ setState(() => _listOpen = true);
+ }
+ }
+
/// Folder paths, project names and repository URLs keep their prompt active
/// even before anything is typed.
static const _prompts = {
@@ -676,13 +685,8 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
}
switch (event.logicalKey) {
case LogicalKeyboardKey.tab:
- // Tab is never let through. Unhandled, it runs Flutter's focus
- // traversal, which moves focus OUT of this form and leaves it deaf
- // to every later key — the screen looked frozen. Here it walks the
- // rows, which is what a form's Tab is expected to do anyway.
- _picking
- ? _stepMatch(HardwareKeyboard.instance.isShiftPressed ? -1 : 1)
- : _moveRow(HardwareKeyboard.instance.isShiftPressed ? -1 : 1);
+ // Arrows move within a pane; Tab switches panes without choosing.
+ _switchPane();
case LogicalKeyboardKey.arrowDown:
// While the list is open it owns ↑↓, so the rows below do not move
// under a highlight the reader is using to choose.
@@ -887,10 +891,8 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_runCommand(() => _picking ? _stepMatch(1) : _moveRow(1)),
'picker.previous': () =>
_runCommand(() => _picking ? _stepMatch(-1) : _moveRow(-1)),
- 'picker.complete': () =>
- _runCommand(() => _picking ? _stepMatch(1) : _moveRow(1)),
- 'picker.complete_back': () =>
- _runCommand(() => _picking ? _stepMatch(-1) : _moveRow(-1)),
+ 'picker.complete': () => _runCommand(_switchPane),
+ 'picker.complete_back': () => _runCommand(_switchPane),
'picker.more_options': () {
if (!box.locked) _toggleAdvanced();
},
diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dart
index 2d54c30a2..bba0c5867 100644
--- a/desktop/lib/widgets/swarm_resource_preview.dart
+++ b/desktop/lib/widgets/swarm_resource_preview.dart
@@ -1,9 +1,12 @@
import 'dart:async';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import '../core/models.dart';
-import '../models/api_connections_panel.dart';
+import '../core/test_run.dart';
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
import '../models/model_search_catalog.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
@@ -14,25 +17,29 @@ import '../state/swarm_search.dart';
import '../terminal/terminal_text.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
-import 'link_machine_dialog.dart';
-import 'link_machine_screen.dart';
-import 'machine_actions.dart';
-import 'machines_manager.dart' show showMachineRenameDialog;
-import 'link_another_machine_dialog.dart';
+import 'machine_picker_form.dart';
+import 'api_picker_form.dart';
import 'swarm_search_preview.dart';
import 'swarm_preview_scroll.dart';
+import 'terminal_text_action.dart';
const resourcePickerCommands = {
'picker.resource_toggle',
'picker.resource_more',
'picker.resource_rename',
'picker.resource_settings',
+ 'picker.resource_connect',
'picker.resource_link',
'picker.resource_add_api',
'picker.resource_remove',
'picker.resource_filter',
'picker.resource_sort',
'picker.refresh',
+ 'picker.model_download',
+ 'picker.model_start',
+ 'picker.model_stop',
+ 'picker.machine_app',
+ 'picker.machine_cli',
};
/// Shortcuts act on the current result without moving focus out of search.
@@ -59,7 +66,7 @@ class _ResourceAction {
final String? hint;
}
-/// A read-only preview; named commands operate on the selected resource.
+/// Resource details and management share the picker’s keyboard and selection.
/// All mutations use their existing controllers and account/session checks.
class SwarmResourcePreview extends StatefulWidget {
const SwarmResourcePreview({
@@ -68,7 +75,6 @@ class SwarmResourcePreview extends StatefulWidget {
required this.controls,
required this.onChoose,
required this.onRefocus,
- required this.onManageModels,
required this.onModalChanged,
required this.onCommands,
});
@@ -76,7 +82,6 @@ class SwarmResourcePreview extends StatefulWidget {
final SearchPreviewControls controls;
final ValueChanged<SwarmSearchSelection> onChoose;
final VoidCallback onRefocus;
- final Future<void> Function() onManageModels;
final ValueChanged<bool> onModalChanged;
final VoidCallback onCommands;
@@ -91,6 +96,141 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
final _pending = <String>{};
final _errors = <String, String>{};
late SwarmPreviewScrollController _scroll;
+ final _actionFocus = FocusNode(debugLabel: 'Resource controls');
+ final _buttonFocus = <String, FocusNode>{};
+ Timer? _resourceTimer;
+ String? _focusedResource;
+ bool _readingResources = false;
+ MachinePickerFormKind? _machineForm;
+ String? _formResource;
+ var _formKey = GlobalKey<MachinePickerFormState>();
+ final _messages = <String, String>{};
+ bool _apiFormOpen = false, _apiRemoving = false;
+ String? _apiResource, _apiConnectionId;
+ var _apiFormKey = GlobalKey<ApiPickerFormState>();
+ bool get _editingApi => _apiFormOpen && _apiResource == row?.id;
+
+ bool get _machineSetup =>
+ row?.isCreate == true && widget.search.isMachineMode;
+ bool get _isManagement =>
+ row?.isMachine == true || row?.isModel == true || _machineSetup;
+ bool get _editingMachine => _machineForm != null && _formResource == row?.id;
+
+ void _editMachine(MachinePickerFormKind kind) {
+ setState(() {
+ _formKey = GlobalKey<MachinePickerFormState>();
+ _machineForm = kind;
+ _formResource = row?.id;
+ });
+ }
+
+ void _closeMachineForm(String? message) {
+ if (!mounted) return;
+ setState(() {
+ if (message != null && row != null) _messages[row!.id] = message;
+ _machineForm = null;
+ _formResource = null;
+ });
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _focusActions();
+ });
+ }
+
+ void _addMachine() {
+ final search = widget.search;
+ search.setQuery('@');
+ final index = search.rows.indexWhere((row) => row.isCreate);
+ if (index >= 0) search.move(index - search.cursor);
+ widget.onRefocus();
+ }
+
+ void _focusActions({bool last = false}) {
+ final selectedId = row?.id;
+ if (selectedId == null) return;
+ void focus() {
+ if (!mounted || row?.id != selectedId) return;
+ final actions = _visibleActions()
+ .where((a) => a.onPressed != null)
+ .toList();
+ final action = last ? actions.lastOrNull : actions.firstOrNull;
+ final node = action == null ? _actionFocus : _buttonFocus[action.command];
+ (node ?? _actionFocus).requestFocus();
+ if (node?.context case final context?) Scrollable.ensureVisible(context);
+ }
+
+ if (widget.search.hasPreview) {
+ focus();
+ } else {
+ widget.search.togglePreview();
+ WidgetsBinding.instance.addPostFrameCallback((_) => focus());
+ }
+ }
+
+ bool _traverseActions(bool forward, {bool stay = false}) {
+ if (row == null ||
+ widget.search.showsTypeHints ||
+ !widget.search.supportsPreview) {
+ return false;
+ }
+ if (!_actionFocus.hasFocus) {
+ _focusActions(last: !forward);
+ return true;
+ }
+ final actions = _visibleActions()
+ .where((a) => a.onPressed != null)
+ .toList();
+ final index = actions.indexWhere(
+ (a) => _buttonFocus[a.command]?.hasFocus == true,
+ );
+ final next = index < 0
+ ? (forward ? 0 : actions.length - 1)
+ : index + (forward ? 1 : -1);
+ if (next < 0 || next >= actions.length) {
+ if (!stay) widget.onRefocus();
+ } else {
+ final node = _buttonFocus[actions[next].command]!;
+ node.requestFocus();
+ if (node.context case final context?) Scrollable.ensureVisible(context);
+ }
+ return true;
+ }
+
+ void _searchChanged() {
+ if (_apiFormOpen && _apiResource != row?.id) {
+ _apiFormOpen = false;
+ _apiResource = null;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) widget.onRefocus();
+ });
+ }
+ if (_machineForm != null && _formResource != row?.id) {
+ // A click/query change closes the old editor before any later reply.
+ _machineForm = null;
+ _formResource = null;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) widget.onRefocus();
+ });
+ }
+ if (_actionFocus.hasFocus && _focusedResource != row?.id) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) widget.onRefocus();
+ });
+ }
+ }
+
+ Future<void> _readResources() async {
+ if (_readingResources ||
+ !widget.search.isMachineMode ||
+ !app.inForeground) {
+ return;
+ }
+ _readingResources = true;
+ try {
+ await widget.search.refreshMachineResources();
+ } finally {
+ _readingResources = false;
+ }
+ }
@override
void initState() {
@@ -98,6 +238,13 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
_scroll = _scrollController();
widget.controls.dispatch = _dispatch;
widget.controls.commands = _commands;
+ widget.search.addListener(_searchChanged);
+ if (!kUnderTest) {
+ _resourceTimer = Timer.periodic(
+ const Duration(seconds: 10),
+ (_) => unawaited(_readResources()),
+ );
+ }
}
SwarmPreviewScrollController _scrollController() =>
@@ -110,6 +257,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
void didUpdateWidget(SwarmResourcePreview oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.search != widget.search) {
+ oldWidget.search.removeListener(_searchChanged);
+ widget.search.addListener(_searchChanged);
_scroll.dispose();
_scroll = _scrollController();
}
@@ -119,11 +268,96 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
void dispose() {
widget.controls.dispatch = null;
widget.controls.commands = null;
+ widget.search.removeListener(_searchChanged);
+ _resourceTimer?.cancel();
+ _actionFocus.dispose();
+ for (final node in _buttonFocus.values) {
+ node.dispose();
+ }
_scroll.dispose();
super.dispose();
}
bool _dispatch(String command) {
+ if (widget.search.isCommandMode || widget.search.isHelpMode) {
+ // Command previews are read-only. Keep Tab from stepping results or
+ // focusing resource controls that are not displayed in this scope.
+ return command == 'picker.complete' || command == 'picker.complete_back';
+ }
+ if (command == 'picker.complete' || command == 'picker.complete_back') {
+ if (row == null || widget.search.showsTypeHints) return false;
+ _switchPane();
+ return true;
+ }
+ if (_editingApi &&
+ widget.search.managing &&
+ _apiFormKey.currentState?.handle(command) == true) {
+ return true;
+ }
+ if (_editingMachine &&
+ widget.search.managing &&
+ _formKey.currentState?.handle(command) == true) {
+ return true;
+ }
+ if (command == 'picker.resource_add_api' && widget.search.isModelMode) {
+ _editApi(null);
+ return true;
+ }
+ if (command == 'picker.focus_actions') {
+ _focusPane();
+ return row != null;
+ }
+ if (_actionFocus.hasFocus &&
+ (command == 'picker.next' || command == 'picker.previous')) {
+ return _traverseActions(command == 'picker.next', stay: true);
+ }
+ if (command == 'picker.cancel') {
+ if (!_actionFocus.hasFocus) return false;
+ widget.onRefocus();
+ return true;
+ }
+ if (command == 'picker.accept') {
+ if (_actionFocus.hasFocus) {
+ if (_focusedResource != row?.id) {
+ widget.onRefocus();
+ return true;
+ }
+ final action = _visibleActions()
+ .where((a) => _buttonFocus[a.command]?.hasFocus == true)
+ .firstOrNull;
+ action?.onPressed?.call();
+ return true;
+ }
+ if (widget.search.canSelectModel(row) ||
+ widget.search.isModelDownloadsRow(row)) {
+ _open();
+ return true;
+ }
+ if (widget.search.isModelMode) {
+ if (row != null && widget.search.canGetModel(row)) {
+ final selected = row!;
+ unawaited(_run(() => widget.search.getModel(selected)));
+ }
+ if (row?.isCreate == true) _editApi(null);
+ // Model rows perform Use/Get directly; unavailable rows stay put.
+ return true;
+ }
+ if (_isManagement) {
+ if (row?.isMachine == true && app.stateOf(row!.machineId!) == null) {
+ return false;
+ }
+ _focusPane();
+ return true;
+ }
+ }
+ if (model?.local case final local?
+ when command == 'picker.resource_toggle') {
+ command = local.canStop
+ ? 'picker.model_stop'
+ : local.downloaded
+ ? 'picker.model_start'
+ : 'picker.model_download';
+ }
if (command == 'picker.resource_more') {
widget.onCommands();
return true;
@@ -140,6 +374,24 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
return true;
}
+ void _focusPane() {
+ if (_editingApi) {
+ _apiFormKey.currentState?.focus();
+ } else if (_editingMachine) {
+ _formKey.currentState?.focus();
+ } else {
+ _focusActions();
+ }
+ }
+
+ void _switchPane() {
+ if (widget.search.managing) {
+ widget.onRefocus();
+ } else {
+ _focusPane();
+ }
+ }
+
List<_ResourceAction> _filterActions() => [
if (widget.search.activityFirst && widget.search.scopePrefix.isEmpty) ...[
for (final filter in SessionFilter.values)
@@ -163,11 +415,14 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
];
List<SwarmDestination> _commands() => [
- for (final action in [
- ..._actions(),
- ..._secondaryActions(),
- ..._filterActions(),
- ])
+ for (final action in {
+ for (final action in [
+ ..._secondaryActions(),
+ ..._filterActions(),
+ ..._actions(),
+ ])
+ action.command: action,
+ }.values)
if (action.onPressed != null &&
action.command != 'picker.accept' &&
action.command != 'picker.resource_filter' &&
@@ -213,19 +468,6 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
});
}
- Future<void> _dialog(Future<void> Function() action) async {
- widget.onModalChanged(true);
- try {
- await _run(() async {
- await action();
- return null;
- });
- } finally {
- widget.onModalChanged(false);
- if (mounted) widget.onRefocus();
- }
- }
-
void _open() {
final selected = row;
if (selected == null) return;
@@ -280,31 +522,200 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
_run(() async {
final catalog = widget.search.models!;
await Future.wait([
- catalog.manager.refresh(force: true),
+ catalog.refresh(force: true),
catalog.manager.apis.refresh(),
catalog.subscriptions.refresh(),
]);
- return catalog.manager.error ?? catalog.manager.apis.error;
+ return model?.controller?.error ??
+ catalog.manager.error ??
+ catalog.manager.apis.error;
}),
);
+ void _refreshMachines() => unawaited(
+ _run(() async {
+ await app.retryMachines();
+ await widget.search.refreshMachineResources();
+ return app.machineListError;
+ }),
+ );
+
+ List<_ResourceAction> _visibleActions() => [
+ ..._actions(),
+ if (!_isManagement && row?.isCreate != true && _commands().isNotEmpty)
+ _ResourceAction(
+ 'Actions…',
+ widget.onCommands,
+ command: 'picker.resource_more',
+ ),
+ ];
+
+ Widget _actionButtons() {
+ final target = row?.id;
+ final cell = terminalCellSizeOf(context);
+ final controls = Focus(
+ focusNode: _actionFocus,
+ onFocusChange: (focused) {
+ _focusedResource = focused ? row?.id : null;
+ widget.search.setManaging(focused);
+ },
+ child: Wrap(
+ key: const ValueKey('swarm-search-resource-actions'),
+ spacing: cell.width * 2,
+ runSpacing: cell.height,
+ children: [
+ for (final action in _visibleActions())
+ TerminalTextAction(
+ key: ValueKey('resource-action:${action.command}'),
+ focusNode: _buttonFocus.putIfAbsent(
+ action.command,
+ () => FocusNode(debugLabel: action.label),
+ ),
+ label: action.label,
+ padding: EdgeInsets.zero,
+ onPressed: action.onPressed == null
+ ? null
+ : () {
+ if (row?.id != target) return;
+ // Resolve again so stale widgets cannot operate on an old resource.
+ final current = _visibleActions()
+ .where((a) => a.command == action.command)
+ .firstOrNull;
+ current?.onPressed?.call();
+ },
+ ),
+ ],
+ ),
+ );
+ void next() => _traverseActions(true, stay: true);
+ void previous() => _traverseActions(false, stay: true);
+ if (KeymapTheme.of(context) != null) {
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ actions: {
+ ...?KeymapRegion.of(context)?.actions,
+ 'picker.next': next,
+ 'picker.previous': previous,
+ 'picker.control_next': next,
+ 'picker.control_previous': previous,
+ },
+ child: controls,
+ );
+ }
+ return CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.arrowRight): next,
+ const SingleActivator(LogicalKeyboardKey.arrowDown): next,
+ const SingleActivator(LogicalKeyboardKey.arrowLeft): previous,
+ const SingleActivator(LogicalKeyboardKey.arrowUp): previous,
+ },
+ child: controls,
+ );
+ }
+
+ Widget _controlHints() {
+ String? key(String command) => effectiveCommandHint(
+ context,
+ command,
+ contextKind: KeymapContext.picker,
+ )?.replaceAll('⇥', 'Tab').replaceAll('↵', 'Enter');
+ final managing = widget.search.managing;
+ final starting =
+ widget.search.usingModelId != null &&
+ widget.search.usingModelId == row?.modelId;
+ final hints = [
+ if (managing &&
+ key('picker.control_previous') != null &&
+ key('picker.control_next') != null)
+ '${key('picker.control_previous')}/${key('picker.control_next')} move',
+ if (starting)
+ 'Starting…'
+ else if (key('picker.accept') case final enter?
+ when managing ||
+ row?.isModel != true ||
+ widget.search.canSelectModel(row) ||
+ widget.search.canGetModel(row) ||
+ widget.search.isModelDownloadsRow(row))
+ '$enter ${managing
+ ? 'select'
+ : widget.search.canSelectModel(row)
+ ? 'Use'
+ : widget.search.canGetModel(row)
+ ? 'Get'
+ : widget.search.isModelDownloadsRow(row)
+ ? widget.search.actionLabel(row)
+ : _isManagement
+ ? _machineSetup
+ ? 'setup'
+ : 'Manage'
+ : widget.search.actionLabel(row)}',
+ if (key('picker.complete') case final tab?) '$tab pane',
+ if (key('picker.cancel') case final escape? when managing || starting)
+ '$escape ${starting ? 'cancel' : 'back'}',
+ ];
+ final cell = terminalCellSizeOf(context);
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ return Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: Text(
+ hints.join(' · '),
+ key: const ValueKey('resource-control-hints'),
+ style: terminalContentStyle(
+ color: theme.foreground.withValues(alpha: .54),
+ ),
+ ),
+ );
+ }
+
List<_ResourceAction> _actions() {
final search = widget.search;
final selected = row;
final busy = _pending.contains(selected?.id ?? search.title);
+ if (search.isModelDownloadsRow(selected)) {
+ return [
+ _ResourceAction(
+ search.modelDownloadsVisible ? 'Hide catalog' : 'Get models',
+ _open,
+ command: 'picker.accept',
+ ),
+ ];
+ }
if (selected?.isCreate == true) {
+ if (search.isMachineMode) {
+ return [
+ _ResourceAction(
+ 'App',
+ () => _editMachine(MachinePickerFormKind.app),
+ command: 'picker.machine_app',
+ ),
+ _ResourceAction(
+ 'CLI',
+ () => _editMachine(MachinePickerFormKind.cli),
+ command: 'picker.machine_cli',
+ ),
+ ];
+ }
+ if (search.isModelMode) {
+ return [
+ _ResourceAction(
+ 'Add',
+ busy ? null : () => _editApi(null),
+ command: 'picker.accept',
+ ),
+ ];
+ }
return [
_ResourceAction(
selected!.title.replaceFirst('New ', 'Create '),
busy ? null : _open,
command: 'picker.accept',
),
- if (search.isModelMode)
- _ResourceAction(
- 'Add API',
- () => _editApi(null),
- command: 'picker.resource_add_api',
- ),
];
}
if (search.isStoreMode) {
@@ -318,79 +729,102 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
}
if (search.isModelMode) {
final catalog = search.models!;
- final entry = model;
- final local = entry?.local;
- final api = entry?.api;
- return [
- if (local != null) ...[
- _ResourceAction(
- 'Open Model Manager',
- busy ? null : () => unawaited(_dialog(widget.onManageModels)),
- command: 'picker.accept',
- ),
+ final local = model?.local;
+ final api = model?.api;
+ final owner = model?.controller ?? catalog.manager;
+ if (local != null) {
+ final enabled =
+ !busy &&
+ !owner.busy &&
+ owner.inventoryAvailable &&
+ owner.machine?.connectionStatus == ConnectionStatus.connected &&
+ owner.machine?.needsLink == false &&
+ (owner.targetMachineId == null ||
+ owner.machine?.isOffline == false);
+ final stop = local.canStop;
+ final get = !stop && !local.downloaded;
+ final action = stop
+ ? 'stop'
+ : get
+ ? 'download'
+ : 'start';
+ return [
_ResourceAction(
- catalog.manager.operationFor(local)?.active == true ||
- catalog.manager.pendingId == local.id
- ? catalog.localStatus(local)
- : local.canStop
+ stop
? 'Stop'
- : local.downloaded
- ? 'Start'
- : 'Download and start',
- busy ||
- catalog.manager.busy ||
- !catalog.manager.inventoryAvailable ||
- (!local.canStart && !local.canStop)
- ? null
- : () => unawaited(
- _run(() async {
- await catalog.manager.toggle(local);
- return catalog.manager.error;
- }),
- ),
- command: 'picker.resource_toggle',
- hint: local.canStop ? 'Free memory; keep the download.' : null,
+ : get
+ ? 'Get'
+ : 'Use',
+ enabled &&
+ (stop ||
+ (get
+ ? local.canStart
+ : search.canSelectModel(selected)))
+ ? !stop && !get
+ ? _open
+ : () => unawaited(
+ _run(() async {
+ await owner.control(
+ local,
+ get && !owner.supportsDownload ? 'start' : action,
+ );
+ return owner.error;
+ }),
+ )
+ : null,
+ command: 'picker.model_$action',
),
- ] else if (api != null)
+ ];
+ }
+ if (api != null) {
+ return [
_ResourceAction(
'Edit',
- () => _editApi(api.id),
- command: 'picker.accept',
- )
- else
+ busy ? null : () => _editApi(api.id),
+ command: 'picker.resource_settings',
+ ),
+ ..._secondaryActions().where(
+ (a) => a.command == 'picker.resource_remove',
+ ),
+ ];
+ }
+ if (model?.subscription != null) {
+ return [
_ResourceAction(
- 'Open Model Manager',
- busy ? null : () => unawaited(_dialog(widget.onManageModels)),
- command: 'picker.accept',
+ 'Refresh',
+ busy ? null : _refreshModels,
+ command: 'picker.refresh',
),
+ ];
+ }
+ return [
+ _ResourceAction(
+ 'Use',
+ !busy && search.canSelectModel(selected) ? _open : null,
+ command: 'picker.accept',
+ ),
];
}
if (selected?.isMachine == true) {
final machine = app.stateOf(selected!.machineId!);
if (machine == null) return [];
+ final secondary = _secondaryActions();
return [
- _ResourceAction(
- 'Open sessions on',
- busy ? null : _open,
- command: 'picker.accept',
- ),
+ ...secondary.where((a) => a.command == 'picker.resource_connect'),
+ ...secondary.where((a) => a.command == 'picker.resource_settings'),
if (!machine.machine.isShared)
_ResourceAction(
'Rename',
- busy
- ? null
- : () => unawaited(
- _dialog(
- () => showMachineRenameDialog(
- context,
- app,
- selected.machineId!,
- machine.machine.displayName,
- ),
- ),
- ),
+ busy ? null : () => _editMachine(MachinePickerFormKind.rename),
command: 'picker.resource_rename',
),
+ ...secondary.where((a) => a.command == 'picker.resource_remove'),
+ if (app.machineListError != null)
+ _ResourceAction(
+ 'Retry',
+ busy ? null : _refreshMachines,
+ command: 'picker.refresh',
+ ),
];
}
final session = _session;
@@ -431,29 +865,37 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
];
}
- void _editApi(String? id) {
+ void _editApi(String? id, {bool removing = false}) {
final catalog = widget.search.models;
if (catalog == null) return;
- unawaited(
- _dialog(() async {
- await showDialog<void>(
- context: context,
- builder: (context) => Dialog(
- child: SizedBox(
- width: 520,
- child: SingleChildScrollView(
- child: ApiConnectionsPanel(
- controller: catalog.manager.apis,
- query: '',
- initialConnectionId: id,
- onEditingChanged: (_) {},
- ),
- ),
- ),
- ),
- );
- }),
- );
+ setState(() {
+ _apiFormKey = GlobalKey<ApiPickerFormState>();
+ _apiResource = row?.id;
+ _apiConnectionId = id;
+ _apiRemoving = removing;
+ _apiFormOpen = true;
+ });
+ }
+
+ void _closeApiForm(String? id) {
+ if (!mounted) return;
+ setState(() {
+ _apiFormOpen = false;
+ _apiResource = null;
+ });
+ if (id?.isNotEmpty == true) {
+ final search = widget.search;
+ if (!search.rows.any((row) => row.modelId == 'model:api:$id')) {
+ search.setQuery(':');
+ }
+ final index = search.rows.indexWhere(
+ (row) => row.modelId == 'model:api:$id',
+ );
+ if (index >= 0) search.move(index - search.cursor);
+ }
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) widget.onRefocus();
+ });
}
List<_ResourceAction> _secondaryActions() {
@@ -483,82 +925,35 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
command: 'picker.resource_settings',
),
_ResourceAction(
- 'Remove API connection…',
- () => unawaited(
- _dialog(() async {
- final remove = await showDialog<bool>(
- context: context,
- builder: (context) => AlertDialog(
- title: Text('Remove ${api.name}?'),
- actions: [
- TextButton(
- onPressed: () => Navigator.pop(context, false),
- child: const Text('Cancel'),
- ),
- TextButton(
- onPressed: () => Navigator.pop(context, true),
- child: const Text('Remove'),
- ),
- ],
- ),
- );
- if (remove == true && mounted) {
- final controller = search.models!.manager.apis;
- if (!await controller.remove(api.id) && mounted) {
- setState(
- () => _errors[selected!.id] =
- controller.error ?? 'Could not remove API.',
- );
- }
- }
- }),
- ),
+ 'Delete',
+ () => _editApi(api.id, removing: true),
command: 'picker.resource_remove',
),
],
] else if (selected?.isMachine == true && machine != null) ...[
- if (machine.needsLink && machine.nodeOnline != false)
+ if (!machine.isLocalMachine &&
+ machine.needsLink &&
+ machine.nodeOnline != false)
_ResourceAction(
- 'Link',
- busy
- ? null
- : () => unawaited(
- _dialog(
- () => showLinkMachineScreenDialog(
- context,
- app,
- selected!.machineId!,
- ),
- ),
- ),
+ 'Connect',
+ busy ? null : () => _editMachine(MachinePickerFormKind.connect),
command: 'picker.resource_connect',
),
if (machine.isLocalMachine && !machine.machine.isShared)
_ResourceAction(
- 'Password / connection settings',
- () => unawaited(_dialog(() => showLinkMachineDialog(context, app))),
+ 'Password',
+ () => _editMachine(MachinePickerFormKind.password),
command: 'picker.resource_settings',
),
if (!machine.isLocalMachine && !machine.machine.isShared)
_ResourceAction(
- 'Remove from account…',
- () => unawaited(
- _dialog(
- () => confirmDeleteMachine(
- context,
- app,
- machineId: machine.machine.machineId,
- displayName: machine.machine.displayName,
- ),
- ),
- ),
+ 'Delete',
+ () => _editMachine(MachinePickerFormKind.delete),
command: 'picker.resource_remove',
),
_ResourceAction(
- 'Link another machine',
- () => unawaited(
- _dialog(() => showLinkAnotherMachineDialog(context, app)),
- ),
+ 'Add machine',
+ _addMachine,
command: 'picker.resource_link',
),
_ResourceAction(
@@ -614,31 +1009,78 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
Widget _modelPreview() {
final catalog = widget.search.models!;
+ if (widget.search.isModelDownloadsRow(row)) {
+ return _details([
+ 'Get models',
+ 'Browse models available to download on your machines.',
+ ], controls: true);
+ }
final entry = model;
if (entry == null) {
return _details([
catalog.manager.scanning ? 'Finding models…' : 'No matching models',
- ?catalog.manager.error,
]);
}
final local = entry.local;
+ final owner = entry.controller ?? catalog.manager;
+ final operation = local == null ? null : owner.operationFor(local);
+ final pending = local != null && owner.pendingId == local.id;
+ String window(double seconds) => seconds % 86400 == 0
+ ? '${(seconds / 86400).toInt()}d'
+ : seconds % 3600 == 0
+ ? '${(seconds / 3600).toInt()}h'
+ : '${seconds.toInt()}s';
return _details([
entry.name,
- [entry.source, entry.node].whereType<String>().join(' · '),
- '',
- entry.status,
+ if (widget.search.modelUseErrorId == entry.id)
+ ?widget.search.modelUseError,
+ [
+ if (local == null) entry.source,
+ ?entry.node,
+ if (local?.sizeBytes case final size?)
+ '${(size / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB',
+ ].join(' · '),
if (local != null) ...[
- if (local.sizeBytes case final size?)
- '${(size / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB download',
- ?local.quant,
- if (local.running && local.tokensPerSecond != null)
- '${local.tokensPerSecond!.toStringAsFixed(1)} tokens/sec',
if (local.running &&
- local.requests != null &&
- local.windowSeconds != null)
- '${local.requests!.toInt()} requests / ${local.windowSeconds!.toInt()} sec',
- ?catalog.manager.operationFor(local)?.error,
- ?catalog.manager.error,
+ (local.tokensPerSecond != null || local.requests != null))
+ [
+ if (local.tokensPerSecond case final speed?)
+ '${speed.toStringAsFixed(1)} tok/s',
+ if (local.requests != null && local.windowSeconds != null)
+ '${local.requests!.toInt()} requests / ${window(local.windowSeconds!)}',
+ ].join(' · '),
+ if (local.resting) 'Resting until your next message',
+ if (pending || operation?.active == true || operation?.failed == true)
+ catalog.localStatus(local, controller: owner),
+ ?operation?.error,
+ if (!local.downloaded &&
+ !owner.supportsDownload &&
+ local.canStart &&
+ !pending &&
+ operation?.active != true)
+ 'Downloads and starts on ${entry.node ?? 'this machine'}.',
+ ] else if (entry.status != 'Available')
+ entry.status,
+ if (widget.search.modelUseReason(row) case final reason?
+ when reason != 'No active harness' &&
+ reason != entry.status &&
+ reason != 'Tools only' &&
+ reason != 'Download first')
+ switch (reason) {
+ 'Claude only' => 'Use this subscription in a Claude harness.',
+ 'Codex only' => 'Use this subscription in a Codex harness.',
+ 'Other account' =>
+ 'This account is not signed in on the harness’s machine.',
+ 'Not serving' => 'Not serving on ${entry.node ?? 'its host'}.',
+ _ => reason,
+ },
+ if (entry.own && local == null && owner.scanning)
+ 'Finding model controls…',
+ if (!identical(owner, catalog.manager)) ...[
+ if (owner.machine?.connectionStatus != ConnectionStatus.connected)
+ 'Connect to ${entry.node} to manage its models.'
+ else
+ ?owner.error,
],
if (entry.api case final api?) ...[
api.baseUrl,
@@ -646,62 +1088,52 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
'Available to harness tools on this computer.',
],
if (entry.subscription case final subscription?) ...[
- if ('${subscription['account'] ?? ''}'.isNotEmpty)
- 'Account ${subscription['account']}',
...((subscription['details'] as List?) ?? const [])
.map((detail) => '$detail')
.where((detail) => detail != entry.status),
],
- ]);
+ ], controls: true);
}
- Widget _machineDetails() {
- final cell = terminalCellSizeOf(context);
- final theme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- );
+ Widget _machinePreview() {
final machine = app.stateOf(row!.machineId!);
+ if (machine == null) return _details([row!.title, 'Unavailable']);
final online =
- machine != null &&
machine.nodeOnline != false &&
!machine.needsLink &&
machine.connectionStatus == ConnectionStatus.connected;
final resources = online
? widget.search.machineResources[row!.machineId]
: null;
- final cpu = resources?.cpuPercent;
- final used = resources?.memoryUsedBytes;
- final total = resources?.memoryTotalBytes;
- return Padding(
- padding: EdgeInsets.fromLTRB(
- cell.width * 2,
- cell.height,
- cell.width * 2,
- 0,
- ),
- child: Text(
- [
- machine?.nodeOnline == false
- ? 'Offline'
- : machine?.needsLink == true
- ? 'Link required'
- : online
- ? 'Connected'
- : 'Offline',
- if (machine?.machine.isShared == true) 'View only',
- if (cpu != null) 'CPU ${cpu.round()}%',
- if (used != null && total != null)
- 'RAM ${(used / (1024 * 1024 * 1024)).toStringAsFixed(1)} / ${(total / (1024 * 1024 * 1024)).toStringAsFixed(0)} GB',
- ].join(' · '),
- style: terminalContentStyle(
- color: theme.foreground.withValues(alpha: .54),
- ),
- ),
- );
+ final status = machine.nodeOnline == false
+ ? 'Offline'
+ : machine.needsLink
+ ? 'Link required'
+ : switch (machine.connectionStatus) {
+ ConnectionStatus.connected => 'Connected',
+ ConnectionStatus.connecting => 'Connecting',
+ ConnectionStatus.reconnecting => 'Reconnecting',
+ ConnectionStatus.disconnected => 'Offline',
+ };
+ return _details([
+ row!.title,
+ [
+ status,
+ if (machine.isLocalMachine) 'This computer',
+ if (machine.machine.isShared) 'View only',
+ ].join(' · '),
+ '',
+ if (resources?.cpuPercent case final cpu?) 'CPU ${cpu.round()}%',
+ if (resources?.memoryUsedBytes != null &&
+ resources?.memoryTotalBytes != null)
+ 'RAM ${(resources!.memoryUsedBytes! / (1024 * 1024 * 1024)).toStringAsFixed(1)} / ${(resources.memoryTotalBytes! / (1024 * 1024 * 1024)).toStringAsFixed(0)} GB',
+ '${machine.agents.length} ${machine.agents.length == 1 ? 'harness' : 'harnesses'}',
+ ?app.machineListError,
+ ?_messages[row!.id],
+ ], controls: true);
}
- Widget _details(List<String> lines) {
+ Widget _details(List<String> lines, {bool controls = false}) {
final cell = terminalCellSizeOf(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
@@ -726,6 +1158,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
: theme.foreground.withValues(alpha: .54),
),
),
+ if (controls) ...[SizedBox(height: cell.height), _actionButtons()],
],
);
}
@@ -743,12 +1176,37 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
vertical: cell.height,
),
children: [
- Text(
- '@ machines\n# projects\n: models\n* store\n> commands',
+ Column(
key: const ValueKey('swarm-search-type-hints'),
- style: terminalContentStyle(
- color: theme.foreground.withValues(alpha: .54),
- ),
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ for (final (prefix, label) in [
+ ('@', 'machines'),
+ ('#', 'projects'),
+ (':', 'models'),
+ ('*', 'store'),
+ ('>', 'commands'),
+ ])
+ TextButton(
+ key: ValueKey('swarm-search-scope:$prefix'),
+ onPressed: () {
+ widget.search.setQuery('$prefix ');
+ widget.onRefocus();
+ },
+ style: TextButton.styleFrom(
+ foregroundColor: theme.foreground.withValues(alpha: .54),
+ textStyle: terminalContentStyle(),
+ padding: EdgeInsets.zero,
+ minimumSize: Size.zero,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ shape: const RoundedRectangleBorder(),
+ ),
+ child: SizedBox(
+ height: cell.height,
+ child: Text('$prefix $label'),
+ ),
+ ),
+ ],
),
],
);
@@ -767,6 +1225,13 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
terminalThemeStore,
]),
builder: (context, _) {
+ if (widget.search.isCommandMode || widget.search.isHelpMode) {
+ return SwarmSearchPreview(
+ key: const ValueKey('swarm-search-preview'),
+ search: widget.search,
+ terminal: true,
+ );
+ }
final cell = terminalCellSizeOf(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
@@ -775,6 +1240,21 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
+ if (widget.search.isModelMode &&
+ widget.search.models?.manager.error != null)
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ cell.width * 2,
+ cell.height,
+ cell.width * 2,
+ 0,
+ ),
+ child: Text(
+ 'Local models · ${widget.search.models!.manager.error}',
+ key: const ValueKey('local-model-inventory-notice'),
+ style: terminalContentStyle(color: theme.yellow),
+ ),
+ ),
if (_pending.contains(row?.id))
Padding(
padding: EdgeInsets.fromLTRB(
@@ -801,16 +1281,33 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
style: terminalContentStyle(color: theme.yellow),
),
),
- if (row?.isMachine == true) _machineDetails(),
Expanded(
- child: widget.search.showsTypeHints
+ child: _editingApi
+ ? ApiPickerForm(
+ key: _apiFormKey,
+ controller: widget.search.models!.manager.apis,
+ connectionId: _apiConnectionId,
+ removing: _apiRemoving,
+ onClose: _closeApiForm,
+ onFocusChanged: widget.search.setManaging,
+ onSwitchPane: _switchPane,
+ )
+ : _editingMachine
+ ? MachinePickerForm(
+ key: _formKey,
+ app: app,
+ kind: _machineForm!,
+ machineId: row?.machineId,
+ onClose: _closeMachineForm,
+ onFocusChanged: widget.search.setManaging,
+ onSwitchPane: _switchPane,
+ )
+ : widget.search.showsTypeHints
? _typeHints()
: row?.isCreate == true
? _details([
- widget.search.createDescription,
- if (widget.search.isModelMode)
- ?widget.search.models?.manager.error,
- ])
+ ...widget.search.createDescription.split('\n'),
+ ], controls: _machineSetup)
: widget.search.isStoreMode
? _details([
if (row?.storeId case final id?) ...[
@@ -824,6 +1321,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
] else
'No matching store entries',
])
+ : row?.isMachine == true
+ ? _machinePreview()
: widget.search.isModelMode
? _modelPreview()
: SwarmSearchPreview(
@@ -832,6 +1331,22 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
terminal: true,
),
),
+ if (row != null &&
+ !widget.search.showsTypeHints &&
+ !_editingMachine &&
+ !_editingApi) ...[
+ if (!_isManagement)
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ cell.width * 2,
+ cell.height,
+ cell.width * 2,
+ 0,
+ ),
+ child: _actionButtons(),
+ ),
+ _controlHints(),
+ ],
],
);
},
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index cf426666e..3d255b273 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -24,6 +24,7 @@ import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
import '../state/swarm_navigation.dart';
import '../state/swarm_search.dart';
+import '../models/model_search_catalog.dart';
import '../state/harness_sessions.dart' show SessionFilter, harnessActivityAge;
import '../store/store_mark.dart';
import 'engine_identity.dart';
@@ -161,6 +162,7 @@ class SwarmSearchKeys extends StatelessWidget {
}
void dismiss() {
+ if (previewControls?.invoke('picker.cancel') == true) return;
if (search?.back() == true) {
onRefocus?.call();
} else {
@@ -181,6 +183,12 @@ class SwarmSearchKeys extends StatelessWidget {
if (switchingMode) onRefocus?.call();
});
void move(int delta) => run(() {
+ if (previewControls?.invoke(
+ delta > 0 ? 'picker.next' : 'picker.previous',
+ ) ==
+ true) {
+ return;
+ }
if (search == null) {
onOpen?.call();
} else {
@@ -189,6 +197,12 @@ class SwarmSearchKeys extends StatelessWidget {
}
});
void complete(bool forward) => run(() {
+ if (previewControls?.invoke(
+ forward ? 'picker.complete' : 'picker.complete_back',
+ ) ==
+ true) {
+ return;
+ }
if (search?.setupLayout == true) {
move(forward ? 1 : -1);
} else if (forward) {
@@ -485,6 +499,22 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
(Size, double)? _geometry;
SwarmSearchController get search => widget.search;
+ List<({int? index, String? heading})> get _modelRows {
+ if (!search.isModelMode) return const [];
+ final items = <({int? index, String? heading})>[];
+ for (final section in ModelSearchSection.values) {
+ final indices = [
+ for (final (index, row) in search.rows.indexed)
+ if (search.modelSection(row) == section) index,
+ ];
+ if (indices.isEmpty && search.matchQuery.trim().isNotEmpty) continue;
+ if (items.isNotEmpty) items.add((index: null, heading: null));
+ items.add((index: null, heading: section.label));
+ items.addAll(indices.map((index) => (index: index, heading: null)));
+ }
+ return items;
+ }
+
double _fittedHeight(
BoxConstraints constraints, {
required bool sideBySide,
@@ -581,11 +611,15 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
}
bool get _pinsCreate =>
- search.resultsFromBottom && search.rows.firstOrNull?.isCreate == true;
+ !search.isModelMode &&
+ search.resultsFromBottom &&
+ search.rows.firstOrNull?.isCreate == true;
void _scrollToSelection() {
if (!_scroll.hasClients || search.rows.isEmpty) return;
- final index = search.cursor - (_createPinned ? 1 : 0);
+ final index = search.isModelMode
+ ? _modelRows.indexWhere((item) => item.index == search.cursor)
+ : search.cursor - (_createPinned ? 1 : 0);
if (index < 0) return;
final top = index * _rowHeight;
final bottom = top + _rowHeight;
@@ -697,9 +731,11 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
// does not change when a query, preview, or selection changes.
final pinCreate = _createPinned =
_pinsCreate && constraints.maxHeight >= _rowHeight + 16;
+ final modelRows = _modelRows;
Widget buildRow(BuildContext context, int index) {
final row = search.rows[index];
- final highlighted = index == search.cursor;
+ final selected = index == search.cursor;
+ final highlighted = selected && !search.managing;
final canSubmit = search.canSubmit(row);
final unavailableReason = search.sessionUnavailable(row);
final alreadyHere = search.alreadyHere(row);
@@ -708,6 +744,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
: null;
final presentation = (
row,
+ selected,
highlighted,
canSubmit,
unavailableReason,
@@ -723,6 +760,9 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
widget.terminal,
stacked,
activityAge,
+ row.isModel ? search.modelRowAction(row) : null,
+ row.isModel ? search.canSelectModel(row) : null,
+ row.isModel ? search.canGetModel(row) : null,
);
final previous = _rowWidgets.remove(row.id);
if (previous?.presentation == presentation) {
@@ -734,7 +774,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
}
final tile = widget.bios
? Semantics(
- selected: highlighted,
+ selected: selected,
enabled: canSubmit,
button: true,
child: InkWell(
@@ -890,7 +930,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
// arriving under a parked pointer: that took the
// highlight from the keyboard untouched.
onHover: (event) {
- if (_pointer.moved(event)) {
+ if (_pointer.moved(event) && !search.managing) {
_focusResult(row.id);
}
},
@@ -985,13 +1025,50 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
_rowHeight,
),
reverse: search.resultsFromBottom,
- itemCount:
- search.rows.length - (pinCreate ? 1 : 0),
+ itemCount: search.isModelMode
+ ? modelRows.length
+ : search.rows.length - (pinCreate ? 1 : 0),
itemExtent: _rowHeight,
- itemBuilder: (context, index) => buildRow(
- context,
- index + (pinCreate ? 1 : 0),
- ),
+ itemBuilder: (context, index) {
+ if (!search.isModelMode) {
+ return buildRow(
+ context,
+ index + (pinCreate ? 1 : 0),
+ );
+ }
+ final item = modelRows[index];
+ if (item.index != null) {
+ return buildRow(context, item.index!);
+ }
+ if (item.heading == null) {
+ return const SizedBox();
+ }
+ return Semantics(
+ header: true,
+ child: Padding(
+ key: ValueKey(
+ 'model-section:${item.heading}',
+ ),
+ padding: EdgeInsets.symmetric(
+ horizontal: widget.bios
+ ? cell.width * 3
+ : 10,
+ ),
+ child: Text(
+ item.heading!,
+ maxLines: 1,
+ style: widget.bios
+ ? terminalContentStyle(
+ color: theme.foreground
+ .withValues(alpha: .54),
+ )
+ : grid.AppType.monoLabel(
+ color: Colors.white60,
+ ),
+ ),
+ ),
+ );
+ },
),
),
),
@@ -1225,10 +1302,18 @@ class _SearchRowContentState extends State<_SearchRowContent> {
terminalThemeStore.value,
);
final muted = theme.foreground.withValues(alpha: .54);
+ final modelAction = row.isModel
+ ? widget.search.modelRowAction(row)
+ : null;
final style = terminalContentStyle(
- color: !widget.enabled
+ color:
+ !widget.enabled ||
+ (row.isModel &&
+ !widget.search.isModelDownloadsRow(row) &&
+ !widget.search.canSelectModel(row) &&
+ !widget.search.canGetModel(row))
? theme.foreground.withValues(alpha: .28)
- : row.isCreate
+ : row.isCreate || widget.search.isModelDownloadsRow(row)
? theme.cursor
: theme.foreground,
);
@@ -1249,6 +1334,7 @@ class _SearchRowContentState extends State<_SearchRowContent> {
label: row.isCreate
? '${row.title}\n$detail'
: '${row.title}\n${row.terminalDetail ?? row.detail}'
+ '${modelAction == null ? '' : ', $modelAction'}'
'${widget.unavailableReason == null ? '' : ', ${widget.unavailableReason}'}'
'${row.shortcut == null ? '' : ', Shortcut ${row.shortcut}'}'
'${widget.activityAge == null ? '' : ', Last active ${widget.activityAge} ago'}',
@@ -1275,7 +1361,19 @@ class _SearchRowContentState extends State<_SearchRowContent> {
style: style,
),
),
- if (widget.unavailableReason case final reason?) ...[
+ if (modelAction != null) ...[
+ SizedBox(width: cell.width * 2),
+ Text(
+ modelAction,
+ key: ValueKey('model-row-action:${row.id}'),
+ maxLines: 1,
+ style: terminalContentStyle(
+ color: modelAction == 'Use'
+ ? theme.foreground
+ : muted,
+ ),
+ ),
+ ] else if (widget.unavailableReason case final reason?) ...[
SizedBox(width: cell.width * 2),
Text(
reason,
diff --git a/desktop/lib/widgets/terminal_text_action.dart b/desktop/lib/widgets/terminal_text_action.dart
index 0ea1554db..527d977da 100644
--- a/desktop/lib/widgets/terminal_text_action.dart
+++ b/desktop/lib/widgets/terminal_text_action.dart
@@ -13,11 +13,13 @@ class TerminalTextAction extends StatelessWidget {
required this.onPressed,
this.focusNode,
this.overArtwork = false,
+ this.padding,
});
final String label;
- final VoidCallback onPressed;
+ final VoidCallback? onPressed;
final FocusNode? focusNode;
final bool overArtwork;
+ final EdgeInsetsGeometry? padding;
@override
Widget build(BuildContext context) {
@@ -41,7 +43,11 @@ class TerminalTextAction extends StatelessWidget {
? const Color(0xcc242424)
: Colors.transparent,
textStyle: terminalContentStyle(),
- padding: EdgeInsets.symmetric(horizontal: cell.width),
+ padding:
+ padding ?? EdgeInsets.symmetric(horizontal: cell.width),
+ disabledForegroundColor: theme.foreground.withValues(
+ alpha: .28,
+ ),
minimumSize: Size.zero,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
shape: const RoundedRectangleBorder(),
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 4d61c9105..219c075e4 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -1215,10 +1215,6 @@ private final class SwarmTabStrip: NSView {
fileprivate let focusedModelButton = SwarmContextButton()
private var focusedModelTarget: [String: Any]?
fileprivate let pullRequestButton = SwarmContextButton()
- fileprivate let harnessesButton = SwarmStatusSymbolButton()
- fileprivate let machinesButton = SwarmStatusSymbolButton()
- fileprivate let modelsButton = SwarmStatusSymbolButton()
- fileprivate let storeButton = SwarmStatusSymbolButton()
private var barFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
private var terminalForeground = NSColor(white: 0.85, alpha: 1)
private var tabs: [SwarmTabButton] = []
@@ -1238,19 +1234,10 @@ private final class SwarmTabStrip: NSView {
scroll.hasVerticalScroller = false
scroll.documentView = document
addSubview(scroll)
- func button(_ button: NSButton, _ symbol: String, _ label: String, _ action: Selector) {
- button.image = NSImage(systemSymbolName: symbol, accessibilityDescription: label)
- button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .regular)
- button.isBordered = false
- button.title = ""
- button.imagePosition = .imageOnly
- button.contentTintColor = terminalForeground
- button.target = self
- button.action = action
- button.setAccessibilityLabel(label)
- addSubview(button)
- }
- button(newButton, "plus", "New Tab", #selector(newSwarm))
+ newButton.isBordered = false
+ newButton.target = self
+ newButton.action = #selector(newSwarm)
+ addSubview(newButton)
newButton.setAccessibilityLabel("New Tab")
newButton.isEnabled = false
newButton.toolTip = "New Tab ⌘T"
@@ -1279,25 +1266,7 @@ private final class SwarmTabStrip: NSView {
pullRequestButton.setAccessibilityLabel("Open pull request on GitHub")
pullRequestButton.isHidden = true
addSubview(pullRequestButton)
- for (control, name, symbol, action) in [
- (harnessesButton, "Harnesses", ">", #selector(openHarnessControls)),
- (machinesButton, "Machines", "@", #selector(openMachineControls)),
- (modelsButton, "Models", ":", #selector(openModelControls)),
- (storeButton, "Harness Store", "*", #selector(openStore)),
- ] {
- control.title = symbol
- control.imagePosition = .noImage
- control.isBordered = false
- control.font = barFont
- control.target = self
- control.action = action
- control.setAccessibilityLabel(name)
- control.toolTip = name
- control.isEnabled = false
- addSubview(control)
- }
- setAccessibilityChildren([scroll, newButton, focusedModelButton, contextButton, pullRequestButton,
- harnessesButton, machinesButton, modelsButton, storeButton])
+ setAccessibilityChildren([scroll, newButton, focusedModelButton, contextButton, pullRequestButton])
registerForDraggedTypes([swarmPasteboardType])
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
@@ -1323,7 +1292,7 @@ private final class SwarmTabStrip: NSView {
?? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
terminalForeground = statusColor(style["foreground"], fallback: terminalForeground)
}
- for control in [newButton, harnessesButton, machinesButton, modelsButton, storeButton] {
+ for control in [newButton] {
control.font = barFont
control.foreground = terminalForeground
control.isEnabled = actionsEnabled
@@ -1398,17 +1367,10 @@ private final class SwarmTabStrip: NSView {
let previousDocumentSize = document.frame.size
let cell = ceil(("m" as NSString).size(withAttributes: [.font: barFont]).width)
let trailing = cell
- let toolColumns = max(ceil(28 / cell), min(4, floor((bounds.width - cell * 9) / (cell * 4))))
- let toolWidth = cell * toolColumns
let toolHeight = workspaceBarControlHeight(barFont)
- let toolsX = bounds.width - trailing - toolWidth * 4
- for (index, control) in [harnessesButton, machinesButton, modelsButton, storeButton].enumerated() {
- control.frame = NSRect(x: toolsX + CGFloat(index) * toolWidth,
- y: (bounds.height - toolHeight) / 2, width: toolWidth, height: toolHeight)
- }
- let statusRight = toolsX - cell * 2
+ let statusRight = bounds.width - trailing
// Compact windows keep a scrolling tab list; context never overlaps it.
- let available = max(0, bounds.width - toolWidth * 4 - cell * 9)
+ let available = max(0, bounds.width - cell * 7)
let widths = tabs.map { min($0.preferredWidth, available * 0.45) }
let total = widths.reduce(0, +)
let occupied = min(total, available * 0.45)
@@ -1487,18 +1449,6 @@ private final class SwarmTabStrip: NSView {
@objc private func newSwarm() {
if actionsEnabled && newButton.isEnabled { emit?("new", nil) }
}
- @objc private func openMachineControls() {
- if actionsEnabled && machinesButton.isEnabled { emit?("machineControls", nil) }
- }
- @objc private func openHarnessControls() {
- if actionsEnabled && harnessesButton.isEnabled { emit?("harnessControls", nil) }
- }
- @objc private func openModelControls() {
- if actionsEnabled && modelsButton.isEnabled { emit?("modelControls", nil) }
- }
- @objc private func openStore() {
- if actionsEnabled && storeButton.isEnabled { emit?("store", nil) }
- }
private func draggedTab(_ sender: NSDraggingInfo) -> SwarmTabButton? {
guard actionsEnabled, sender.draggingSourceOperationMask.contains(.move),
let source = sender.draggingSource as? SwarmTabButton,
diff --git a/desktop/test/api_connections_test.dart b/desktop/test/api_connections_test.dart
index cf7282af3..7a09a2119 100644
--- a/desktop/test/api_connections_test.dart
+++ b/desktop/test/api_connections_test.dart
@@ -11,6 +11,7 @@ import 'package:harness/logging/redact.dart';
import 'package:harness/models/api_connections_controller.dart';
import 'package:harness/models/model_manager_controller.dart';
import 'package:harness/models/models_panel.dart';
+import 'package:harness/widgets/api_picker_form.dart';
import 'package:harness/usage/models_menu_controller.dart';
import 'package:harness/ws/ws_conn.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
@@ -106,6 +107,205 @@ void main() {
))
.load();
});
+ testWidgets(
+ 'inline API setup masks the key, reports errors, and saves once',
+ (tester) async {
+ final app = _ApiApp();
+ final controller = ApiConnectionsController(app);
+ final closed = <String?>[];
+ try {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ApiPickerForm(
+ controller: controller,
+ onClose: closed.add,
+ onFocusChanged: (_) {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.byType(Dialog), findsNothing);
+ await tester.tap(
+ find.byKey(const ValueKey('api-form:provider:openrouter')),
+ );
+ await tester.pumpAndSettle();
+ final key = find.byKey(const ValueKey('api-form-input:key'));
+ expect(tester.widget<TextField>(key).focusNode!.hasFocus, isTrue);
+ expect(tester.widget<TextField>(key).obscureText, isTrue);
+ await tester.enterText(key, 'fixture-only-key');
+ app.response = {'error': 'fixture', 'detail': 'Try saving again.'};
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Try saving again.'), findsOneWidget);
+ expect(closed, isEmpty);
+ expect(
+ tester.widget<TextField>(key).controller!.text,
+ 'fixture-only-key',
+ );
+ app.response = null;
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(closed, ['openrouter']);
+ expect(
+ app.requests.where((row) => row['action'] == 'save'),
+ hasLength(2),
+ );
+ expect(
+ controller.connections.single.data.containsKey('apiKey'),
+ isFalse,
+ );
+ expect(tester.widget<TextField>(key).controller!.text, isEmpty);
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ controller.dispose();
+ app.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'inline API form validates custom URLs and keeps a saved key on edit',
+ (tester) async {
+ final app = _ApiApp();
+ final controller = ApiConnectionsController(app);
+ final closed = <String?>[];
+ await controller.refresh();
+ try {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ApiPickerForm(
+ controller: controller,
+ onClose: closed.add,
+ onFocusChanged: (_) {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('api-form:provider:custom')),
+ );
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:name')),
+ 'Example',
+ );
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:url')),
+ 'https://example.test/v1?key=bad',
+ );
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:key')),
+ 'fixture-only-key',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining('without credentials or query parameters'),
+ findsOneWidget,
+ );
+ expect(app.requests.where((row) => row['action'] == 'save'), isEmpty);
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:url')),
+ 'https://example.test/v1',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(closed, ['custom-fixture']);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ApiPickerForm(
+ key: const ValueKey('edit-api'),
+ controller: controller,
+ connectionId: 'custom-fixture',
+ onClose: closed.add,
+ onFocusChanged: (_) {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final key = find.byKey(const ValueKey('api-form-input:key'));
+ expect(tester.widget<TextField>(key).controller!.text, isEmpty);
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:name')),
+ 'Renamed',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(controller.connections.single.name, 'Renamed');
+ expect((app.requests.last['connection'] as Map)['apiKey'], isEmpty);
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ controller.dispose();
+ app.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'leaving a pending inline API save cannot reopen or refocus the editor',
+ (tester) async {
+ final app = _ApiApp();
+ final controller = ApiConnectionsController(app);
+ final closed = <String?>[];
+ await controller.refresh();
+ final reply = Completer<Map<String, dynamic>>();
+ try {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ApiPickerForm(
+ controller: controller,
+ onClose: closed.add,
+ onFocusChanged: (_) {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('api-form:provider:openrouter')),
+ );
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:key')),
+ 'fixture-only-key',
+ );
+ app.held = reply;
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(controller.saving, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(closed, [null]);
+ await tester.pumpWidget(const SizedBox());
+ reply.complete({
+ 'connections': [
+ {...preset, 'id': 'openrouter'},
+ ],
+ 'presets': [preset],
+ });
+ await tester.pumpAndSettle();
+ expect(closed, [null]);
+ expect(controller.saving, isFalse);
+ expect(tester.takeException(), isNull);
+ } finally {
+ if (!reply.isCompleted) {
+ reply.complete({'connections': [], 'presets': []});
+ }
+ await tester.pumpWidget(const SizedBox());
+ controller.dispose();
+ app.dispose();
+ }
+ },
+ );
test('metadata and frame logging strip credentials', () {
final value = ApiConnection.fromJson({
...preset,
diff --git a/desktop/test/boot_flow_widget_test.dart b/desktop/test/boot_flow_widget_test.dart
index 8c711e50b..14a18d5a0 100644
--- a/desktop/test/boot_flow_widget_test.dart
+++ b/desktop/test/boot_flow_widget_test.dart
@@ -1,3 +1,4 @@
+import 'support/workspace_tools.dart';
import 'swarm_interactions_test.dart' show chord;
import 'package:flutter/services.dart';
@@ -1130,7 +1131,13 @@ void main() {
),
findsNothing,
);
- expect(find.textContaining('Offline'), findsOneWidget);
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is Icon && widget.semanticLabel == 'remote-mac: Offline',
+ ),
+ findsOneWidget,
+ );
expect(find.text('Harness is offline'), findsNothing);
expect(find.text('harness start'), findsNothing);
await tester.pumpWidget(const SizedBox());
@@ -1179,7 +1186,7 @@ void main() {
await tester.pump();
expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
- await tester.tap(find.byKey(const ValueKey('swarm-machines-button')));
+ await openWorkspaceManagement(tester, 'machines');
await tester.pumpAndSettle();
await tester.ensureVisible(find.text('link-mac'));
await tester.tap(
@@ -1263,7 +1270,7 @@ void main() {
await tester.pump();
expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
- await tester.tap(find.byKey(const ValueKey('swarm-machines-button')));
+ await openWorkspaceManagement(tester, 'machines');
await tester.pumpAndSettle();
await tester.ensureVisible(find.text('link-mac'));
await tester.tap(
diff --git a/desktop/test/command_picker_rendering_test.dart b/desktop/test/command_picker_rendering_test.dart
index fd29ade32..be8726492 100644
--- a/desktop/test/command_picker_rendering_test.dart
+++ b/desktop/test/command_picker_rendering_test.dart
@@ -273,6 +273,13 @@ void main() {
await key(tester, LogicalKeyboardKey.pageUp);
expect(search.cursor, first);
await key(tester, LogicalKeyboardKey.tab);
+ expect(search.cursor, first);
+ expect(field.focusNode!.hasFocus, isTrue);
+ expect(
+ find.byKey(const ValueKey('swarm-search-resource-actions')),
+ findsNothing,
+ );
+ await key(tester, LogicalKeyboardKey.arrowDown);
expect(search.cursor, first + 1);
expect(field.controller!.value, value);
expect(field.focusNode!.hasFocus, isTrue);
diff --git a/desktop/test/harness_placement_test.dart b/desktop/test/harness_placement_test.dart
index 2e4339f2d..dbcc07def 100644
--- a/desktop/test/harness_placement_test.dart
+++ b/desktop/test/harness_placement_test.dart
@@ -503,7 +503,7 @@ void main() {
expect(search.createTask, isNull);
expect(search.rows.any((row) => row.isCreate), query.startsWith('@'));
if (query.startsWith('@')) {
- expect(search.rows.first.title, 'New Machine');
+ expect(search.rows.last.title, 'Add machine');
}
}
search.setQuery('');
diff --git a/desktop/test/harness_session_manager_test.dart b/desktop/test/harness_session_manager_test.dart
index e8d7df557..2cd2b6c9f 100644
--- a/desktop/test/harness_session_manager_test.dart
+++ b/desktop/test/harness_session_manager_test.dart
@@ -1,3 +1,5 @@
+import 'support/workspace_tools.dart';
+
import 'dart:async';
import 'dart:io';
import 'dart:ui' show SemanticsAction;
@@ -69,7 +71,7 @@ void main() {
find.byKey(ValueKey('session-toggle:${agentDestinationId('m', id)}'));
Future<void> open(WidgetTester tester) async {
await mount(tester, app);
- await tester.tap(find.byKey(const ValueKey('swarm-harnesses-button')));
+ await openWorkspaceManagement(tester, 'harnesses');
await tester.pumpAndSettle();
}
@@ -230,7 +232,7 @@ void main() {
await app.addAgentToSwarm('m', 'a0');
app.machineStates['m']!.blockedAgents['a0'] = question('a0');
await mount(tester, app);
- await tester.tap(find.byKey(const ValueKey('swarm-harnesses-button')));
+ await openWorkspaceManagement(tester, 'harnesses');
await tester.pump(const Duration(milliseconds: 300));
expect(
find.byKey(const ValueKey('swarm-notifications-button')),
@@ -474,7 +476,7 @@ void main() {
await tester.pump();
connection.stopReplies.single.complete({'deleted': true});
await tester.pump();
- await tester.tap(find.byKey(const ValueKey('swarm-harnesses-button')));
+ await openWorkspaceManagement(tester, 'harnesses');
await tester.pump();
expect(toggle('a0'), findsNothing);
expect(find.byTooltip('Pausing…'), findsOneWidget);
@@ -831,7 +833,7 @@ void main() {
expect(find.byKey(pane.cellKey), findsNothing);
expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
expect(connection.stops, isEmpty);
- await tester.tap(find.byKey(const ValueKey('swarm-harnesses-button')));
+ await openWorkspaceManagement(tester, 'harnesses');
await tester.pumpAndSettle();
expect(find.text(_running.name), findsOneWidget);
},
diff --git a/desktop/test/keymap_host_test.dart b/desktop/test/keymap_host_test.dart
index 286cf5599..99f033398 100644
--- a/desktop/test/keymap_host_test.dart
+++ b/desktop/test/keymap_host_test.dart
@@ -129,6 +129,27 @@ void main() {
expect(command('cmd+['), 'navigation.back');
});
+ test('Models uses Cmd I and respects a saved pane shortcut', () {
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ expect(map.hint('models.list'), '⌘I');
+ expect(harnessCommandById['pane.last']!.keys, isEmpty);
+ map.apply('''{"bindings":[
+ {"keys":"cmd+semicolon","command":"pane.last"},
+ {"keys":"cmd+y","command":"models.list"}
+ ]}''');
+ for (final context in KeymapContext.values) {
+ expect(
+ map.current.match(context, [KeyStroke.parse('cmd+semicolon')]).command,
+ 'pane.last',
+ );
+ expect(
+ map.current.match(context, [KeyStroke.parse('cmd+y')]).command,
+ 'models.list',
+ );
+ }
+ });
+
test(
'Mac native editing and window conflicts are rejected before activation',
() {
diff --git a/desktop/test/keymap_native_test.dart b/desktop/test/keymap_native_test.dart
index bdc0f77d4..66e04a88b 100644
--- a/desktop/test/keymap_native_test.dart
+++ b/desktop/test/keymap_native_test.dart
@@ -46,6 +46,8 @@ void main() {
{"keys":"cmd+k","command":null},
{"keys":"cmd+k cmd+n","command":"swarm.new"},
{"keys":"cmd+left","command":null,"when":"terminal"},
+ {"keys":"cmd+i","command":null},
+ {"keys":"cmd+y","command":"models.list"},
{"keys":"down","command":null,"when":"picker"},
{"keys":"ctrl+j","command":"picker.previous","when":"picker"}
]}''');
diff --git a/desktop/test/machines_manager_test.dart b/desktop/test/machines_manager_test.dart
index dacd4c210..593620a81 100644
--- a/desktop/test/machines_manager_test.dart
+++ b/desktop/test/machines_manager_test.dart
@@ -52,7 +52,7 @@ class _ToolbarApp extends ModelManagerTestApp {
void main() {
for (final nativeTabs in [false, true]) {
testWidgets(
- 'status symbols open management panels and Store (native=$nativeTabs)',
+ 'Search unifies categories and preserves management commands (native=$nativeTabs)',
(tester) async {
final app = _ToolbarApp();
app.stateOf('m')!.nodeOnline = true;
@@ -63,36 +63,55 @@ void main() {
await app.modelManager.refresh();
await mount(tester, app, nativeTabs: nativeTabs);
- Future<void> open(String name, String action) async {
- if (nativeTabs) {
- final dispatched = native(tester, action);
- await tester.pumpAndSettle();
- await dispatched;
- } else {
- await tester.tap(find.byKey(ValueKey('swarm-$name-button')));
- await tester.pumpAndSettle();
- }
+ if (nativeTabs) {
+ final dispatched = native(tester, 'sessions');
+ await tester.pumpAndSettle();
+ await dispatched;
+ } else {
+ await openWorkspaceTool(tester, 'harnesses');
+ await tester.pumpAndSettle();
}
+ expect(resourceField, findsOneWidget);
+ expect(resourceSearch(tester).selected, isNull);
+ await tester.tap(find.byKey(const ValueKey('swarm-search-scope:@')));
+ await tester.pumpAndSettle();
+ expect(resourceScope('@'), findsOneWidget);
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ expect(
+ tester.widget<TextField>(resourceField).focusNode!.hasFocus,
+ isTrue,
+ );
+ final search = resourceSearch(tester);
+ final other = search.rows.indexWhere((row) => row.machineId == 'other');
+ search.move(other - search.cursor);
+ await tester.pump();
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.resource_connect')),
+ findsOneWidget,
+ );
+ expect(app.actions, isEmpty);
- await open('harnesses', 'harnessControls');
+ await tester.enterText(resourceField, '');
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('swarm-search-scope::')));
+ await tester.pumpAndSettle();
+ expect(resourceScope(':'), findsOneWidget);
+ expect(find.byType(ModelsPanel), findsNothing);
+ expect(app.actions, isEmpty);
+
+ await openWorkspaceManagement(tester, 'harnesses');
+ await tester.pumpAndSettle();
expect(find.byType(HarnessSessionManager), findsOneWidget);
- expect(resourceField, findsNothing);
- await open('harnesses', 'harnessControls');
- expect(find.byType(HarnessSessionManager), findsNothing);
- await open('harnesses', 'harnessControls');
- await open('machines', 'machineControls');
+ await openWorkspaceManagement(tester, 'machines');
+ await tester.pumpAndSettle();
expect(find.byType(HarnessSessionManager), findsNothing);
expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
- expect(find.text('Set password'), findsOneWidget);
- expect(find.text('Connect'), findsOneWidget);
- expect(resourceScope('@'), findsNothing);
- await open('models', 'modelControls');
+ await openWorkspaceManagement(tester, 'models');
+ await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
expect(find.byType(ModelsPanel), findsOneWidget);
- expect(find.byKey(const ValueKey('model-action-qwen')), findsOneWidget);
- expect(resourceScope(':'), findsNothing);
- expect(app.actions, isEmpty);
- await open('store', 'store');
+ await openWorkspaceTool(tester, 'store');
+ await tester.pumpAndSettle();
expect(find.byType(ModelsPanel), findsNothing);
expect(app.activeSwarm.isStore, isTrue);
expect(tester.takeException(), isNull);
@@ -318,7 +337,7 @@ void main() {
expect(resourceScope('@'), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(find.byKey(const ValueKey('swarm-machines-button')), findsOneWidget);
+ expect(find.byKey(const ValueKey('swarm-search-button')), findsNothing);
await openWorkspaceTool(tester, 'machines');
await tester.pumpAndSettle();
expect(resourceScope('@'), findsOneWidget);
@@ -332,7 +351,7 @@ void main() {
});
testWidgets(
- 'clicking a linked machine scopes work by ID even when names match',
+ 'clicking a linked machine manages its ID even when names match',
(tester) async {
final app = createApp();
app.stateOf('m')!
@@ -358,19 +377,18 @@ void main() {
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('machine:m')));
await tester.pumpAndSettle();
- expect(resourceScope('@'), findsNothing);
+ expect(resourceScope('@'), findsOneWidget);
+ expect(resourceSearch(tester).selected!.machineId, 'm');
+ expect(resourceSearch(tester).managing, isTrue);
final search = tester.widget<TextField>(
find.byKey(const ValueKey('swarm-search-input')),
);
- expect(search.controller!.text, isEmpty);
- expect(search.decoration!.hintText, 'Search harnesses in Test host');
+ expect(search.controller!.text, '@');
expect(find.text('Task from another Test host'), findsNothing);
- await tester.enterText(
- find.byKey(const ValueKey('swarm-search-input')),
- 'Task from another',
- );
+ await key(tester, LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
- expect(find.text('Task from another Test host'), findsNothing);
+ expect(resourceSearch(tester).selected!.machineId, 'm');
+ expect(resourceSearch(tester).managing, isFalse);
expect(search.focusNode!.hasFocus, isTrue);
await tester.pumpWidget(const SizedBox());
app.dispose();
@@ -413,7 +431,7 @@ void main() {
);
}
- testWidgets('an empty machine session list waits for Cmd-N to create there', (
+ testWidgets('machine management waits for Cmd-N to create on that machine', (
tester,
) async {
final previous = newHarnessOpensInBox;
@@ -451,7 +469,7 @@ void main() {
for (final fail in [false, true]) {
testWidgets(
- 'Machines toolbar opens Rename and updates names (failure=$fail)',
+ 'Machines picker renames inline and updates names (failure=$fail)',
(tester) async {
const channel = MethodChannel('harness/swarm_tabs');
final updates = <Map>[];
@@ -486,12 +504,12 @@ void main() {
await tester.pumpAndSettle();
await runResourceCommand(tester, 'Rename');
await tester.pumpAndSettle();
- expect(find.text('Rename Machine'), findsOneWidget);
- final field = find.byType(TextField).last;
+ expect(find.text('Rename machine'), findsOneWidget);
+ final field = find.byKey(const ValueKey('machine-rename-input'));
await tester.enterText(field, ' ');
- await tester.testTextInput.receiveAction(TextInputAction.done);
+ await key(tester, LogicalKeyboardKey.enter);
await tester.pump();
- expect(find.text('Name cannot be empty'), findsOneWidget);
+ expect(find.text('Enter a name.'), findsOneWidget);
expect(api.calls, isEmpty);
await tester.enterText(field, ' Office Mac ');
if (fail) api.error = 'Connection unavailable';
@@ -505,7 +523,7 @@ void main() {
await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
}
- expect(find.text('Rename Machine'), findsNothing);
+ expect(find.text('Rename machine'), findsNothing);
expect(
find.descendant(
of: find.byKey(const ValueKey('machine:m')),
@@ -517,6 +535,13 @@ void main() {
expect((updates.last['machines'] as List).single['name'], 'Office Mac');
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
+ expect(resourceScope('@'), findsOneWidget);
+ expect(
+ tester.widget<TextField>(resourceField).focusNode!.hasFocus,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
expect(resourceScope('@'), findsNothing);
expect(
tester
diff --git a/desktop/test/machines_panel_test.dart b/desktop/test/machines_panel_test.dart
index 44027ba62..de0660bd5 100644
--- a/desktop/test/machines_panel_test.dart
+++ b/desktop/test/machines_panel_test.dart
@@ -1,3 +1,5 @@
+import 'support/workspace_tools.dart';
+
import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;
@@ -223,7 +225,7 @@ void main() {
await tester.pumpAndSettle();
}
if (workspace) {
- await tester.tap(find.byKey(const ValueKey('swarm-machines-button')));
+ await openWorkspaceManagement(tester, 'machines');
await tester.pumpAndSettle();
} else {
await tester.tap(find.text('open machines'));
@@ -451,7 +453,7 @@ void main() {
await capture(tester, 'machines-toolbar-set-password');
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- await tester.tap(find.byKey(const ValueKey('swarm-machines-button')));
+ await openWorkspaceManagement(tester, 'machines');
await tester.pumpAndSettle();
expect(localInput, findsNothing);
await tap(tester, find.byKey(const ValueKey('connect-machine-remote')));
diff --git a/desktop/test/model_manager_controller_test.dart b/desktop/test/model_manager_controller_test.dart
index d3e6059cf..af84eac57 100644
--- a/desktop/test/model_manager_controller_test.dart
+++ b/desktop/test/model_manager_controller_test.dart
@@ -29,6 +29,66 @@ void main() {
app.dispose();
});
+ test(
+ 'Download is explicit and never falls back to Start on an older daemon',
+ () async {
+ app.localInventory.remove('supportsDownload');
+ await controller.refresh();
+ await controller.control(controller.localModels.first, 'download');
+ expect(app.downloads, isEmpty);
+ expect(app.actions, isEmpty);
+ app.localInventory['supportsDownload'] = true;
+ await controller.refresh();
+ await controller.control(controller.localModels.first, 'download');
+ expect(app.downloads, [(machine: 'm', model: 'qwen')]);
+ expect(app.actions, isEmpty);
+ expect(
+ controller.operationFor(controller.localModels.first)?.action,
+ 'download',
+ );
+ expect(
+ controller.operationFor(controller.localModels.first)?.label,
+ 'Downloading',
+ );
+ expect(controller.readyModel, isNull);
+ await controller.control(controller.localModels.first, 'start');
+ expect(app.actions, isEmpty);
+ },
+ );
+
+ test('model titles include supplied quantization exactly once', () {
+ expect(
+ const LocalModel(
+ id: 'local:Qwen3.8-27B-Q4_0.gguf',
+ name: 'qwen3.8-27b',
+ ).displayName,
+ 'qwen3.8-27b · Q4_0',
+ );
+ expect(
+ const LocalModel(
+ id: 'local:Qwen3.5-4B-Q4_K_M.gguf',
+ name: 'qwen35-4b',
+ ).displayName,
+ 'qwen35-4b · Q4_K_M',
+ );
+ expect(
+ const LocalModel(id: 'a', name: 'Example', quant: 'Q4_K_M').displayName,
+ 'Example · Q4_K_M',
+ );
+ expect(
+ const LocalModel(
+ id: 'a',
+ name: 'Example-Q4_K_M',
+ quant: 'Q4_K_M',
+ ).displayName,
+ 'Example-Q4_K_M',
+ );
+ expect(
+ const LocalModel(id: 'a', name: 'Example', quant: '').displayName,
+ 'Example',
+ );
+ });
+
test('silent discovery preserves the workspace and never starts a model or sends a chat', () async {
connection.holdCreation = Completer<void>();
final original = app.activeSwarmId;
@@ -356,19 +416,25 @@ void main() {
expect(controller.localModels, isEmpty);
});
- test('a notice beside the list keeps the list, and every row it offers', () async {
- // ⚠️ REGRESSION. The daemon's sentence for a grid it could not fully read rode in `error`,
- // and an `error` fails the request whole — the rows it came with were thrown away and the
- // Local tab read 0. The sentence now arrives as `notice`, and the list with it.
- app.localInventory = {
- ...modelInventory(),
- 'notice': 'Running models could not be checked. Try again.',
- };
- await controller.refresh();
- expect(controller.localModels, hasLength(5));
- expect(controller.inventoryAvailable, isTrue);
- expect(controller.error, 'Running models could not be checked. Try again.');
- });
+ test(
+ 'a notice beside the list keeps the list, and every row it offers',
+ () async {
+ // ⚠️ REGRESSION. The daemon's sentence for a grid it could not fully read rode in `error`,
+ // and an `error` fails the request whole — the rows it came with were thrown away and the
+ // Local tab read 0. The sentence now arrives as `notice`, and the list with it.
+ app.localInventory = {
+ ...modelInventory(),
+ 'notice': 'Running models could not be checked. Try again.',
+ };
+ await controller.refresh();
+ expect(controller.localModels, hasLength(5));
+ expect(controller.inventoryAvailable, isTrue);
+ expect(
+ controller.error,
+ 'Running models could not be checked. Try again.',
+ );
+ },
+ );
test('an old daemon or malformed inventory disables actions without clearing the last view', () async {
await controller.refresh();
@@ -377,6 +443,11 @@ void main() {
expect(controller.localModels, hasLength(5));
expect(controller.inventoryAvailable, isFalse);
expect(controller.error, contains('Update Harness'));
+ app.localInventory = {};
+ await controller.refresh();
+ expect(controller.localModels, hasLength(5));
+ expect(controller.inventoryAvailable, isFalse);
+ expect(controller.error, contains('unavailable'));
app.localInventory = {
'models': [
{'id': 7},
diff --git a/desktop/test/model_search_catalog_test.dart b/desktop/test/model_search_catalog_test.dart
new file mode 100644
index 000000000..10ab0dd0d
--- /dev/null
+++ b/desktop/test/model_search_catalog_test.dart
@@ -0,0 +1,430 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/models/model_search_catalog.dart';
+import 'package:harness/models/api_connections_controller.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/usage/models_menu_controller.dart';
+import 'package:harness/widgets/resting_model_words.dart';
+
+import 'support/model_manager.dart';
+
+class _NoSubscriptions extends ModelsMenuController {
+ @override
+ List<Map<String, Object?>> get rows => const [];
+}
+
+class _WithSubscriptions extends ModelsMenuController {
+ @override
+ List<Map<String, Object?>> get rows => const [
+ {'engine': 'codex', 'title': 'OpenAI'},
+ ];
+}
+
+class _MachineSubscriptions extends ModelsMenuController {
+ bool signedOut = false;
+
+ @override
+ List<Map<String, Object?>> get rows => [
+ {
+ 'engine': 'codex',
+ 'title': 'OpenAI',
+ 'account': 'local-account',
+ 'status': signedOut ? 'Not signed in' : '50% remaining',
+ },
+ {
+ 'engine': 'codex',
+ 'title': 'OpenAI',
+ 'account': 'remote-account',
+ 'status': '75% remaining',
+ },
+ ];
+
+ @override
+ Map<String, Object?>? subscriptionFor(
+ String engine, {
+ required bool local,
+ required String machineName,
+ }) => engine != 'codex'
+ ? null
+ : local
+ ? rows.first
+ : machineName == 'Other computer'
+ ? rows.last
+ : null;
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late ModelManagerTestApp app;
+ late ModelsMenuController subscriptions;
+ late ModelSearchCatalog catalog;
+ setUp(() {
+ app = ModelManagerTestApp(ModelManagerConnection());
+ subscriptions = _NoSubscriptions();
+ catalog = ModelSearchCatalog(
+ app.modelManager,
+ subscriptions,
+ pollHosts: false,
+ );
+ });
+ tearDown(() {
+ catalog.dispose();
+ subscriptions.dispose();
+ app.dispose();
+ });
+
+ test(
+ 'four sections separate installed and shared models from downloads',
+ () async {
+ final usage = _WithSubscriptions();
+ final grouped = ModelSearchCatalog(
+ app.modelManager,
+ usage,
+ pollHosts: false,
+ );
+ final search = SwarmSearchController(
+ app,
+ const [],
+ models: grouped,
+ offersCreate: true,
+ adding: true,
+ )..setQuery(':');
+ try {
+ app.localInventory = {
+ 'models': [
+ {'id': 'available', 'name': 'AAA catalog'},
+ {
+ 'id': 'installed',
+ 'name': 'ZZZ installed',
+ 'state': 'downloaded',
+ 'canStart': true,
+ },
+ ],
+ };
+ app.inventory = const GridModels(
+ gridName: 'home',
+ models: [],
+ grids: [
+ GridSection(
+ name: 'Team',
+ own: false,
+ models: [GridModel(id: 'Shared Qwen', node: 'team.lan')],
+ ),
+ ],
+ );
+ app.modelManager.apis.connections = [
+ const ApiConnection({'id': 'custom', 'name': 'Custom API'}),
+ ];
+ await app.modelManager.refresh();
+ expect(search.rows.map((row) => row.title), [
+ 'OpenAI',
+ 'Custom API',
+ '[ Add ]',
+ 'ZZZ installed',
+ '[ Get models ]',
+ 'Shared Qwen · team.lan',
+ ]);
+ expect(search.rows.map(search.modelSection), [
+ ModelSearchSection.subscriptions,
+ ModelSearchSection.apis,
+ ModelSearchSection.apis,
+ ModelSearchSection.local,
+ ModelSearchSection.local,
+ ModelSearchSection.shared,
+ ]);
+ search.move(
+ search.rows.indexWhere(search.isModelDownloadsRow) - search.cursor,
+ );
+ expect(search.submit(), isNull);
+ expect(search.modelDownloadsVisible, isTrue);
+ expect(search.rows.map((row) => row.title), [
+ 'OpenAI',
+ 'Custom API',
+ '[ Add ]',
+ 'ZZZ installed',
+ '[ Hide catalog ]',
+ 'AAA catalog',
+ 'Shared Qwen · team.lan',
+ ]);
+ expect(search.selected!.title, 'AAA catalog');
+ expect(search.modelRowAction(search.selected!), isNull);
+ search.move(
+ search.rows.indexWhere(search.isModelDownloadsRow) - search.cursor,
+ );
+ search.submit();
+ expect(search.modelDownloadsVisible, isFalse);
+ expect(search.rows.any((row) => row.title == 'AAA catalog'), isFalse);
+ search.setQuery(':Local AI');
+ expect(
+ search.rows.where((row) => !row.isCreate).map((row) => row.title),
+ ['ZZZ installed', 'AAA catalog'],
+ );
+ expect(app.actions, isEmpty);
+ } finally {
+ search.dispose();
+ grouped.dispose();
+ usage.dispose();
+ }
+ },
+ );
+
+ test(
+ 'own models precede shared models even without local inventory',
+ () async {
+ app.localReadFails = true;
+ app.inventory = const GridModels(
+ gridName: 'home',
+ models: [],
+ grids: [
+ GridSection(
+ name: 'Team',
+ own: false,
+ models: [GridModel(id: 'Shared model', node: 'team.lan')],
+ ),
+ GridSection(
+ name: 'home',
+ own: true,
+ models: [GridModel(id: 'qwen3.8-27b', node: 'mac.lan')],
+ ),
+ ],
+ );
+ await app.modelManager.refresh();
+ expect(catalog.rows.map((row) => row.title), [
+ 'qwen3.8-27b',
+ 'Shared model · team.lan',
+ ]);
+ final own = catalog.entries[catalog.rows.first.modelId]!;
+ expect(own.source, 'On your machines');
+ expect(own.node, 'mac.lan');
+ expect(own.local, isNull);
+ final search = SwarmSearchController(app, const [], models: catalog)
+ ..setQuery(':local');
+ addTearDown(search.dispose);
+ expect(search.rows.map((row) => row.title), ['qwen3.8-27b']);
+ search.setQuery(':mac.lan');
+ expect(search.rows.map((row) => row.title), ['qwen3.8-27b']);
+ expect(app.actions, isEmpty);
+ expect(app.downloads, isEmpty);
+ },
+ );
+
+ test('legacy own-grid replies remain visible in models', () async {
+ app.localInventory = {'models': <Object>[]};
+ app.inventory = const GridModels(
+ gridName: 'home',
+ models: [GridModel(id: 'Qwen', node: 'mac.lan')],
+ );
+ await app.modelManager.refresh();
+ expect(catalog.rows.single.title, 'Qwen');
+ expect(catalog.entries.values.single.source, 'On your machines');
+ });
+
+ test('Use identifies only the subscription available on the pane host', () {
+ final usage = _MachineSubscriptions();
+ final accounts = ModelSearchCatalog(
+ app.modelManager,
+ usage,
+ pollHosts: false,
+ );
+ final search = SwarmSearchController(app, const [], models: accounts)
+ ..setQuery(':OpenAI')
+ ..setModelSelection('codex', app.inventory, machineId: 'm');
+ try {
+ final local = search.rows.firstWhere(
+ (row) =>
+ accounts.entries[row.modelId]?.subscription?['account'] ==
+ 'local-account',
+ );
+ final remote = search.rows.firstWhere(
+ (row) =>
+ accounts.entries[row.modelId]?.subscription?['account'] ==
+ 'remote-account',
+ );
+ expect(search.modelRowAction(local), 'Use');
+ expect(search.modelRowAction(remote), isNull);
+ search.setModelSelection('codex', app.inventory, machineId: 'other');
+ expect(search.modelRowAction(local), isNull);
+ expect(search.modelRowAction(remote), 'Use');
+ search.setModelSelection('claude', app.inventory, machineId: 'm');
+ expect(search.rows.any(search.canSelectModel), isFalse);
+ search.setModelSelection('codex', app.inventory, machineId: 'm');
+ usage.signedOut = true;
+ expect(search.canSelectModel(local), isFalse);
+ expect(app.actions, isEmpty);
+ } finally {
+ search.dispose();
+ accounts.dispose();
+ usage.dispose();
+ }
+ });
+
+ test(
+ 'matching model names never hide hosts or grant local controls',
+ () async {
+ app.localInventory = {
+ 'models': [
+ {'id': 'qwen', 'name': 'Qwen'},
+ ],
+ };
+ app.inventory = const GridModels(
+ gridName: 'home',
+ models: [
+ GridModel(id: 'qwen', node: 'This Mac'),
+ GridModel(id: 'qwen', node: 'mac.lan'),
+ ],
+ );
+ await app.modelManager.refresh();
+ expect(catalog.rows, hasLength(3));
+ expect(catalog.entries, hasLength(3));
+ expect(
+ catalog.entries.values.where((entry) => entry.local != null),
+ hasLength(1),
+ );
+ expect(
+ catalog.entries.values.where(
+ (entry) => entry.source == 'On your machines',
+ ),
+ hasLength(2),
+ );
+ },
+ );
+
+ test(
+ 'each linked host exposes its own inventory without a served Grid row',
+ () async {
+ const model = {
+ 'id': 'weights.gguf',
+ 'name': 'Qwen',
+ 'state': 'downloaded',
+ 'canStart': true,
+ };
+ app.localInventory = {
+ 'models': [model],
+ 'supportsDownload': true,
+ };
+ app.machineStates['other']!
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ app.machineInventories['other'] = {
+ 'models': [model],
+ };
+ catalog.setVisible(true);
+ await catalog.refresh();
+ expect(
+ catalog.entries.values.where((entry) => entry.local != null),
+ hasLength(2),
+ );
+ final remote = catalog.entries.values.singleWhere(
+ (entry) => entry.controller?.targetMachineId == 'other',
+ );
+ expect(remote.gridModel, isNull);
+ expect(remote.controller!.supportsDownload, isFalse);
+ await remote.controller!.control(remote.local!, 'start');
+ expect(app.actions, [
+ (machine: 'other', model: 'weights.gguf', start: true),
+ ]);
+ expect(app.localInventory['models'], [model]);
+ expect(app.connection.creations, isEmpty);
+ },
+ );
+
+ test(
+ 'unlinked and offline hosts are not queried or given controls',
+ () async {
+ final remote = app.machineStates['other']!
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true
+ ..needsLink = true;
+ catalog.setVisible(true);
+ await catalog.refresh();
+ expect(app.inventoryReads, isNot(contains('other')));
+ remote
+ ..needsLink = false
+ ..nodeOnline = false;
+ app.notifyListeners();
+ await catalog.refresh();
+ expect(app.inventoryReads, isNot(contains('other')));
+ expect(app.actions, isEmpty);
+ expect(app.connection.creations, isEmpty);
+ },
+ );
+
+ test(
+ 'selection follows the target pane machine model capabilities',
+ () async {
+ app.localInventory = {'models': <Object>[]};
+ app.inventory = const GridModels(
+ gridName: 'home',
+ models: [GridModel(id: 'Qwen', node: 'mac.lan')],
+ );
+ await app.modelManager.refresh();
+ final search = SwarmSearchController(app, const [], models: catalog)
+ ..setQuery(':Qwen')
+ ..setModelSelection(
+ 'codex',
+ const GridModels.unreachable(),
+ machineId: 'other',
+ );
+ addTearDown(search.dispose);
+ expect(search.canSelectModel(search.selected), isFalse);
+ // A live picture from the pane's host updates availability without reopening.
+ app.gridPictures.adopt('other', app.inventory);
+ expect(search.canSelectModel(search.selected), isTrue);
+ expect(search.actionLabel(search.selected), 'Use');
+ app.gridPictures.adopt(
+ 'other',
+ const GridModels(
+ gridName: 'home',
+ models: [GridModel(id: 'Qwen', node: 'mac.lan')],
+ localModelEngines: {'claude'},
+ ),
+ );
+ expect(search.canSelectModel(search.selected), isFalse);
+ expect(search.actionLabel(search.selected), 'Unavailable');
+ expect(app.actions, isEmpty);
+ },
+ );
+
+ test(
+ 'own model states use the existing offline and resting wording',
+ () async {
+ app.localInventory = {'models': <Object>[]};
+ app.inventory = const GridModels(
+ gridName: 'home',
+ models: [],
+ grids: [
+ GridSection(
+ name: 'home',
+ own: true,
+ state: GridSectionState.asleep,
+ lastKnownAge: 120,
+ models: [
+ GridModel(id: 'Resting', node: 'mac.lan'),
+ GridModel(
+ id: 'Offline',
+ node: 'rig.lan',
+ unavailable: GridModelUnavailable(machine: 'Rig'),
+ ),
+ ],
+ ),
+ ],
+ );
+ await app.modelManager.refresh();
+ final rows = catalog.entries.values.toList();
+ expect(rows[0].status, restingSubtitle(120));
+ expect(rows[1].status, offlineRowSentence('Rig'));
+ final search = SwarmSearchController(app, const [], models: catalog)
+ ..setQuery(':')
+ ..setModelSelection('codex', app.inventory, machineId: 'm');
+ try {
+ final resting = search.rows.firstWhere((row) => row.title == 'Resting');
+ final offline = search.rows.firstWhere((row) => row.title == 'Offline');
+ expect(search.modelRowAction(resting), 'Use');
+ expect(search.modelRowAction(offline), isNull);
+ expect(search.canSelectModel(offline), isFalse);
+ } finally {
+ search.dispose();
+ }
+ },
+ );
+}
diff --git a/desktop/test/model_use_test.dart b/desktop/test/model_use_test.dart
new file mode 100644
index 000000000..586506d30
--- /dev/null
+++ b/desktop/test/model_use_test.dart
@@ -0,0 +1,234 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/models/model_search_catalog.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/usage/models_menu_controller.dart';
+
+import 'support/model_manager.dart';
+
+class _Subscriptions extends ModelsMenuController {
+ @override
+ List<Map<String, Object?>> get rows => const [];
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late ModelManagerTestApp app;
+ late ModelSearchCatalog catalog;
+ late _Subscriptions subscriptions;
+ late SwarmSearchController search;
+ const downloaded = {
+ 'id': 'weights.gguf',
+ 'name': 'Qwen',
+ 'state': 'downloaded',
+ 'canStart': true,
+ };
+
+ Future<void> prepare() async {
+ app = ModelManagerTestApp(ModelManagerConnection());
+ app.machineStates['m']!.nodeOnline = true;
+ app.localInventory = {
+ 'models': [downloaded],
+ };
+ await app.modelManager.refresh();
+ subscriptions = _Subscriptions();
+ catalog = ModelSearchCatalog(
+ app.modelManager,
+ subscriptions,
+ pollHosts: false,
+ );
+ search = SwarmSearchController(app, const [], models: catalog)
+ ..setQuery(':Qwen')
+ ..setModelSelection('codex', app.inventory, machineId: 'm');
+ }
+
+ void dispose({bool searchDisposed = false}) {
+ if (!searchDisposed) search.dispose();
+ catalog.dispose();
+ subscriptions.dispose();
+ app.dispose();
+ }
+
+ testWidgets('an unserved instance cannot be used until it can start again', (
+ tester,
+ ) async {
+ await prepare();
+ try {
+ app.localInventory = {
+ 'models': [
+ {...downloaded, 'canStart': false, 'canStop': true},
+ ],
+ };
+ await app.modelManager.refresh();
+ final row = search.selected!;
+ expect(search.modelRowAction(row), isNull);
+ expect(search.modelUseReason(row), 'Not serving');
+ expect(search.submit(row), isNull);
+ expect(app.actions, isEmpty);
+ app.localInventory = {
+ 'models': [downloaded],
+ };
+ await app.modelManager.refresh();
+ expect(search.selected!.id, row.id);
+ expect(search.modelRowAction(search.selected!), 'Use');
+ expect(search.canStartModelForUse(search.selected), isTrue);
+ } finally {
+ dispose();
+ }
+ });
+
+ testWidgets(
+ 'Enter starts installed weights once and waits for serving readiness',
+ (tester) async {
+ await prepare();
+ try {
+ final row = search.selected!;
+ expect(search.canSelectModel(row), isTrue);
+ final selected = search.startModelForUse(row, stillCurrent: () => true);
+ await tester.pump();
+ expect(app.actions, [
+ (machine: 'm', model: 'weights.gguf', start: true),
+ ]);
+ expect(search.usingModelId, row.modelId);
+ expect(
+ await search.startModelForUse(row, stillCurrent: () => true),
+ isNull,
+ );
+ expect(app.actions, hasLength(1));
+ app.localInventory = {
+ 'models': [
+ {
+ ...downloaded,
+ 'state': 'running',
+ 'canStart': false,
+ 'canStop': true,
+ },
+ ],
+ };
+ app.inventory = const GridModels(
+ gridName: 'home',
+ models: [GridModel(id: 'Qwen', node: 'This Mac')],
+ );
+ await tester.pump(const Duration(seconds: 2));
+ expect((await selected)?.id, 'Qwen');
+ expect(search.selected!.id, row.id);
+ expect(search.usingModelId, isNull);
+ expect(app.downloads, isEmpty);
+ } finally {
+ dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'startup failure remains in the picker without selecting or retrying',
+ (tester) async {
+ await prepare();
+ try {
+ final row = search.selected!;
+ final selected = search.startModelForUse(row, stillCurrent: () => true);
+ await tester.pump();
+ app.localInventory = {
+ 'models': [
+ {
+ ...downloaded,
+ 'operation': {
+ 'id': 'operation',
+ 'modelId': 'weights.gguf',
+ 'action': 'start',
+ 'stage': 'starting',
+ 'phase': 'failed',
+ 'error': 'Not enough memory.',
+ },
+ },
+ ],
+ };
+ await tester.pump(const Duration(seconds: 2));
+ expect(await selected, isNull);
+ expect(search.modelUseError, 'Not enough memory.');
+ expect(search.modelUseErrorId, row.modelId);
+ expect(app.actions, hasLength(1));
+ expect(search.usingModelId, isNull);
+ } finally {
+ dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'closing the picker cancels the switch without stopping model startup',
+ (tester) async {
+ await prepare();
+ final selected = search.startModelForUse(
+ search.selected!,
+ stillCurrent: () => true,
+ );
+ await tester.pump();
+ search.dispose();
+ await tester.pump();
+ expect(await selected, isNull);
+ expect(app.actions, [(machine: 'm', model: 'weights.gguf', start: true)]);
+ dispose(searchDisposed: true);
+ },
+ );
+
+ testWidgets('focus changes cancel the pending switch to the original pane', (
+ tester,
+ ) async {
+ await prepare();
+ try {
+ var current = true;
+ final selected = search.startModelForUse(
+ search.selected!,
+ stillCurrent: () => current,
+ );
+ await tester.pump();
+ current = false;
+ await tester.pump(const Duration(seconds: 2));
+ expect(await selected, isNull);
+ expect(search.usingModelId, isNull);
+ expect(app.actions, hasLength(1));
+ } finally {
+ dispose();
+ }
+ });
+
+ testWidgets('uninstalled and disconnected models never start on Enter', (
+ tester,
+ ) async {
+ await prepare();
+ try {
+ app.localInventory = {
+ 'models': [
+ {...downloaded, 'state': 'available'},
+ ],
+ };
+ await app.modelManager.refresh();
+ expect(search.canStartModelForUse(search.selected), isFalse);
+ expect(
+ await search.startModelForUse(
+ search.selected!,
+ stillCurrent: () => true,
+ ),
+ isNull,
+ );
+ app.localInventory = {
+ 'models': [downloaded],
+ };
+ await app.modelManager.refresh();
+ app.machineStates['m']!.connectionStatus = ConnectionStatus.disconnected;
+ expect(search.canStartModelForUse(search.selected), isFalse);
+ expect(
+ await search.startModelForUse(
+ search.selected!,
+ stillCurrent: () => true,
+ ),
+ isNull,
+ );
+ expect(app.actions, isEmpty);
+ expect(app.downloads, isEmpty);
+ } finally {
+ dispose();
+ }
+ });
+}
diff --git a/desktop/test/new_harness_form_test.dart b/desktop/test/new_harness_form_test.dart
index bd98123ae..f55355138 100644
--- a/desktop/test/new_harness_form_test.dart
+++ b/desktop/test/new_harness_form_test.dart
@@ -136,7 +136,7 @@ void main() {
]) {
expect(find.byKey(ValueKey('new-harness-field-$field')), findsOneWidget);
}
- await press(tester, LogicalKeyboardKey.enter);
+ await press(tester, LogicalKeyboardKey.pageUp);
expect(find.byKey(const ValueKey('new-harness-field-model')), findsNothing);
});
@@ -423,25 +423,37 @@ void main() {
);
});
- testWidgets('Tab walks the rows and never escapes the form', (tester) async {
+ testWidgets('Tab switches panes without changing the selected agent', (
+ tester,
+ ) async {
final box = await mount(tester, focus: 'harness');
- for (var i = 0; i < 1; i++) {
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
- await tester.pumpAndSettle();
- }
- expect(
- box.field,
- NewHarnessField.projectMenu,
- reason: 'Tab walks the rows.',
- );
- // The real bug: traversal moved focus out and the form went deaf. Up
- // rather than down, since the row under Branch edits no field at all.
- await press(tester, LogicalKeyboardKey.arrowUp);
+ final engine = box.engine;
+ await press(tester, LogicalKeyboardKey.tab);
+ expect(harnessChoicesActive(tester), isTrue);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.engine, engine);
+ await press(tester, LogicalKeyboardKey.tab);
+ expect(harnessChoicesActive(tester), isFalse);
+ expect(box.field, NewHarnessField.harness);
expect(
- box.field,
- NewHarnessField.harness,
- reason: 'Keys must still reach the form after Tab.',
+ box.engine,
+ engine,
+ reason: 'Switching panes must not choose a value.',
);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
+ await press(tester, LogicalKeyboardKey.tab);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
+ expect(harnessChoicesActive(tester), isTrue);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ final selected = box.selected!.engine;
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(harnessChoicesActive(tester), isFalse);
+ expect(box.engine, selected);
+ expect(box.field, NewHarnessField.launch);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.field, NewHarnessField.harness);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.field, NewHarnessField.projectMenu);
});
testWidgets('the doors can be reached and opened', (tester) async {
@@ -842,7 +854,7 @@ void main() {
await focusLaunchRow(tester, 'approvals');
expect(box.field, NewHarnessField.mode);
- await press(tester, LogicalKeyboardKey.tab);
+ await press(tester, LogicalKeyboardKey.arrowDown);
expect(
tester
.widget<Semantics>(
diff --git a/desktop/test/new_harness_grid_test.dart b/desktop/test/new_harness_grid_test.dart
index 20eed8716..c2df22c8f 100644
--- a/desktop/test/new_harness_grid_test.dart
+++ b/desktop/test/new_harness_grid_test.dart
@@ -449,38 +449,31 @@ void main() {
expect(daemon.requests, contains('agent_create'));
});
- testWidgets(
- 'remapped next and previous keys move the rows, then the list',
- (tester) async {
- final keymap = MemoryKeymap()
- ..apply(
- '{"bindings":['
- '{"keys":"ctrl+l","command":"picker.complete","when":"picker"},'
- '{"keys":"ctrl+h","command":"picker.complete_back","when":"picker"}]}',
- );
- final (box, _) = await mount(tester, keymap: keymap);
- expect(box.field, NewHarnessField.harness);
- for (final (move, back) in [
- (LogicalKeyboardKey.keyN, LogicalKeyboardKey.keyP),
- (LogicalKeyboardKey.keyL, LogicalKeyboardKey.keyH),
- ]) {
- // The list closed: they walk the rows.
- await key(tester, move, ctrl: true);
- expect(box.field, NewHarnessField.projectMenu);
- await key(tester, back, ctrl: true);
- expect(box.field, NewHarnessField.harness);
- // The list open: they walk the choices, and the row stays put.
- await key(tester, LogicalKeyboardKey.arrowRight);
- final first = box.selected!.id;
- await key(tester, move, ctrl: true);
- expect(box.selected!.id, isNot(first));
- expect(box.field, NewHarnessField.harness);
- await key(tester, back, ctrl: true);
- expect(box.selected!.id, first);
- await key(tester, LogicalKeyboardKey.escape);
- }
- },
- );
+ testWidgets('remapped Tab switches panes while arrow aliases browse', (
+ tester,
+ ) async {
+ final keymap = MemoryKeymap()
+ ..apply(
+ '{"bindings":[{"keys":"ctrl+l","command":"picker.complete","when":"picker"},{"keys":"ctrl+h","command":"picker.complete_back","when":"picker"}]}',
+ );
+ final (box, _) = await mount(tester, keymap: keymap);
+ expect(box.field, NewHarnessField.harness);
+ final engine = box.engine;
+ await key(tester, LogicalKeyboardKey.keyL, ctrl: true);
+ expect(harnessChoicesActive(tester), isTrue);
+ final first = box.selected!.id;
+ await key(tester, LogicalKeyboardKey.keyN, ctrl: true);
+ expect(box.selected!.id, isNot(first));
+ expect(box.field, NewHarnessField.harness);
+ await key(tester, LogicalKeyboardKey.keyP, ctrl: true);
+ expect(box.selected!.id, first);
+ await key(tester, LogicalKeyboardKey.keyH, ctrl: true);
+ expect(harnessChoicesActive(tester), isFalse);
+ expect(box.field, NewHarnessField.harness);
+ expect(box.engine, engine);
+ await key(tester, LogicalKeyboardKey.keyN, ctrl: true);
+ expect(box.field, NewHarnessField.projectMenu);
+ });
testWidgets('a narrow window keeps a status line on the grid', (
tester,
diff --git a/desktop/test/new_harness_models_test.dart b/desktop/test/new_harness_models_test.dart
index 86cacfbff..dc7108e65 100644
--- a/desktop/test/new_harness_models_test.dart
+++ b/desktop/test/new_harness_models_test.dart
@@ -223,6 +223,26 @@ void main() {
expect(box.modelLabel, 'OpenAI');
expect(box.usesProfile, isTrue);
});
+ test(
+ 'model choices explain when their serving machine seems offline',
+ () async {
+ final connection = connections.putIfAbsent('m', _Connection.new);
+ final own = (connection.answer['grids'] as List).first as Map;
+ own['models'] = [
+ <String, dynamic>{
+ 'id': 'Qwen-35B',
+ 'node': 'Mac Studio',
+ 'unavailable': {'reason': 'offline', 'machine': 'Mac Studio'},
+ },
+ ];
+ final box = controller();
+ await load(box);
+ expect(localChoice(box).detail, 'Mac Studio · seems offline');
+ expect(box.model, isNull);
+ expect(connection.creates, isEmpty);
+ },
+ );
+
test('inline choices reject an agent invalidated by a harness change and a profile from another machine', () async {
final box = controller();
await app.probeDsh('m', force: true);
diff --git a/desktop/test/new_harness_scenarios_test.dart b/desktop/test/new_harness_scenarios_test.dart
index ea63e5506..80fd2b6e0 100644
--- a/desktop/test/new_harness_scenarios_test.dart
+++ b/desktop/test/new_harness_scenarios_test.dart
@@ -747,39 +747,43 @@ void main() {
},
);
- testWidgets('reverse Tab, key repeats and Page keys stay within setup', (
- tester,
- ) async {
- final scenario = await _mount(tester, engine: 'claude');
- await focusLaunchRow(tester, 'harness');
- await key(tester, LogicalKeyboardKey.tab, shift: true);
- expect(
- tester.widget<Semantics>(_field('start')).properties.selected,
- isTrue,
- );
- await key(tester, LogicalKeyboardKey.tab, shift: true);
- expect(
- tester.widget<Semantics>(_field('advanced')).properties.selected,
- isTrue,
- );
- await focusLaunchRow(tester, 'approvals');
- final originalMode = scenario.box.mode;
- await key(tester, LogicalKeyboardKey.pageDown);
- expect(scenario.box.mode, isNot(originalMode));
- await key(tester, LogicalKeyboardKey.pageUp);
- expect(scenario.box.mode, originalMode);
- await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowUp);
- await tester.sendKeyRepeatEvent(LogicalKeyboardKey.arrowUp);
- await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowUp);
- await tester.pump();
- // Two steps up from Approvals: Model, then Options.
- expect(
- tester.widget<Semantics>(_field('advanced')).properties.selected,
- isTrue,
- );
- expect(FocusManager.instance.primaryFocus?.debugLabel, 'new-harness-form');
- expect(scenario.creates, 0);
- });
+ testWidgets(
+ 'reverse navigation, key repeats and Page keys stay within setup',
+ (tester) async {
+ final scenario = await _mount(tester, engine: 'claude');
+ await focusLaunchRow(tester, 'harness');
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ expect(
+ tester.widget<Semantics>(_field('start')).properties.selected,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ expect(
+ tester.widget<Semantics>(_field('advanced')).properties.selected,
+ isTrue,
+ );
+ await focusLaunchRow(tester, 'approvals');
+ final originalMode = scenario.box.mode;
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(scenario.box.mode, isNot(originalMode));
+ await key(tester, LogicalKeyboardKey.pageUp);
+ expect(scenario.box.mode, originalMode);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowUp);
+ await tester.sendKeyRepeatEvent(LogicalKeyboardKey.arrowUp);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowUp);
+ await tester.pump();
+ // Two steps up from Approvals: Model, then Options.
+ expect(
+ tester.widget<Semantics>(_field('advanced')).properties.selected,
+ isTrue,
+ );
+ expect(
+ FocusManager.instance.primaryFocus?.debugLabel,
+ 'new-harness-form',
+ );
+ expect(scenario.creates, 0);
+ },
+ );
testWidgets(
'paste fills the active search and backspace removes a whole Unicode character',
@@ -1283,7 +1287,7 @@ void main() {
);
testWidgets(
- 'folder completion can switch machines and reverse Tab walks choices',
+ 'folder completion uses arrows for choices and can switch machines',
(tester) async {
final scenario = await _mount(tester);
scenario.app.machineStates['m']!.localOnly = false;
@@ -1295,9 +1299,9 @@ void main() {
await tester.pump(const Duration(milliseconds: 100));
await tester.pumpAndSettle();
final first = scenario.box.selected!.id;
- await key(tester, LogicalKeyboardKey.tab, shift: true);
+ await key(tester, LogicalKeyboardKey.arrowUp);
expect(scenario.box.selected!.id, isNot(first));
- await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.arrowDown);
expect(scenario.box.selected!.id, first);
for (
var i = 0;
diff --git a/desktop/test/quick_access_test.dart b/desktop/test/quick_access_test.dart
index f8ea1db26..08675a396 100644
--- a/desktop/test/quick_access_test.dart
+++ b/desktop/test/quick_access_test.dart
@@ -4,6 +4,8 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/state/harness_placement.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/terminal/terminal_binary.dart';
@@ -16,6 +18,63 @@ import 'swarm_screen_test.dart' show terminal;
import 'swarm_state_test.dart' show createApp;
void main() {
+ test('machine order prioritizes connection opportunities and preserves selection', () {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.localOnly = true;
+ for (final (id, name, online) in [
+ ('new10', 'Rig 10', true),
+ ('new2', 'Rig 2', true),
+ ('offline', 'AAA offline', false),
+ ]) {
+ app.machineStates[id] =
+ MachineState(
+ Machine(
+ machineId: id,
+ name: name,
+ authMode: MachineAuthMode.remote,
+ ),
+ )
+ ..nodeOnline = online
+ ..needsLink = true;
+ }
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ offersCreate: true,
+ activityFirst: true,
+ )..setQuery('@');
+ addTearDown(search.dispose);
+ expect(search.rows.map((row) => row.machineId), [
+ 'new2',
+ 'new10',
+ 'm',
+ 'studio',
+ 'offline',
+ 'build',
+ null,
+ ]);
+ expect(search.selected!.machineId, 'new2');
+ app.machineStates['new2']!
+ ..needsLink = false
+ ..connectionStatus = ConnectionStatus.connected;
+ app.notifyListeners();
+ expect(search.rows.map((row) => row.machineId), [
+ 'new10',
+ 'm',
+ 'studio',
+ 'new2',
+ 'offline',
+ 'build',
+ null,
+ ]);
+ expect(search.selected!.machineId, 'new2');
+ search.setQuery('@AAA offline');
+ expect(search.selected!.machineId, 'offline');
+ });
+
test('Cmd-P never creates harnesses in root or scoped session lists', () {
final app = createApp();
seedMixedAgents(app);
@@ -39,7 +98,12 @@ void main() {
search.setQuery(query);
expect(search.rows.any((row) => row.isCreate), query.startsWith('@'));
expect(search.selected!.isCreate, isFalse);
- expect(search.submit(), isNull);
+ if (query.startsWith('@')) {
+ expect(search.submit()!.destination.isMachine, isTrue);
+ search.scopeToGroup(search.selected!.id);
+ } else {
+ expect(search.submit(), isNull);
+ }
expect(search.canGoBack, isTrue);
expect(search.rows, isNotEmpty);
expect(search.rows.any((row) => row.isCreate), isFalse);
@@ -98,7 +162,7 @@ void main() {
expect(search.rows.single.commandId, 'app.store');
expect(search.createTask, isNull);
search.setQuery('@ Office');
- expect(search.rows.first.title, 'New Machine');
+ expect(search.rows.last.title, 'Add machine');
expect(
search.rows.where((row) => !row.isCreate).single.isMachine,
isTrue,
@@ -240,7 +304,7 @@ void main() {
.every((row) => row.machineId == 'studio'),
isTrue,
);
- expect(field.focusNode!.hasFocus, isTrue);
+ expect(search.managing, isTrue);
await key(tester, LogicalKeyboardKey.escape);
expect(field.controller!.text, '@ Office');
expect(search.isMachineMode, isTrue);
diff --git a/desktop/test/resource_picker_test.dart b/desktop/test/resource_picker_test.dart
index 7d25623c5..e5ea79802 100644
--- a/desktop/test/resource_picker_test.dart
+++ b/desktop/test/resource_picker_test.dart
@@ -1,6 +1,7 @@
import 'support/open_harness.dart';
import 'dart:io';
+import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
@@ -9,9 +10,10 @@ import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/auth/cli_link.dart';
import 'package:harness/core/models.dart';
import 'package:harness/models/api_connections_controller.dart';
-import 'package:harness/models/api_connections_panel.dart';
+import 'package:harness/widgets/api_picker_form.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/theme/color_palette.dart';
import 'package:harness/state/swarm_search.dart';
@@ -19,8 +21,10 @@ import 'package:harness/terminal/terminal_text.dart';
import 'package:harness/terminal/terminal_theme.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
import 'package:harness/widgets/swarm_resource_preview.dart';
+import 'package:harness/widgets/machine_picker_form.dart';
import 'package:harness/widgets/swarm_switcher.dart';
import 'package:harness/widgets/search_result_text.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
import 'package:xterm/xterm.dart' show TerminalStyle;
import 'keymap_host_test.dart' show MemoryKeymap, key;
@@ -34,8 +38,8 @@ final field = find.byKey(const ValueKey('swarm-search-input'));
SwarmSearchController search(WidgetTester tester) =>
tester.widget<SwarmSearchResults>(find.byType(SwarmSearchResults)).search;
-Future<ModelManagerTestApp> fixture() async {
- final app = ModelManagerTestApp(ModelManagerConnection());
+Future<ModelManagerTestApp> fixture({ModelManagerTestApp? provided}) async {
+ final app = provided ?? ModelManagerTestApp(ModelManagerConnection());
await seedPreviews(app);
app.adoptSessionForTest(terminal('a69', []));
app.machineStates['m']!.dsh.replace(const [
@@ -69,6 +73,163 @@ Future<ModelManagerTestApp> fixture() async {
return app;
}
+class _MachineApp extends ModelManagerTestApp {
+ _MachineApp() : super(ModelManagerConnection());
+ final edits = <({String action, String id, String value})>[];
+ String? editError;
+ Completer<String?>? editReply;
+ final pending = <String, Future<String?>>{};
+ bool passwordSet = false;
+
+ Future<String?> change(String action, String id, String value) {
+ if (pending[action] case final request?) return request;
+ edits.add((action: action, id: id, value: value));
+ final future = (editReply?.future ?? Future<String?>.value(editError)).then(
+ (error) {
+ pending.remove(action);
+ if (error == null) {
+ if (action == 'connect') {
+ machineStates[id]!
+ ..needsLink = false
+ ..connectionStatus = ConnectionStatus.connected;
+ } else if (action == 'rename') {
+ final original = machineStates[id]!.machine;
+ machineStates[id]!.machine = Machine(
+ machineId: id,
+ name: value,
+ authMode: original.authMode,
+ );
+ } else if (action == 'delete') {
+ machineStates.remove(id);
+ } else if (action == 'password') {
+ passwordSet = true;
+ } else if (action == 'clear') {
+ passwordSet = false;
+ }
+ notifyListeners();
+ }
+ return error;
+ },
+ );
+ pending[action] = future;
+ return future;
+ }
+
+ @override
+ Future<String?> connectWithPassword(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ }) => change('connect', machineId, password);
+ @override
+ Future<String?>? pendingMachineLink(String machineId) => pending['connect'];
+ @override
+ Future<String?> renameMachine(String machineId, String name) =>
+ change('rename', machineId, name);
+ @override
+ Future<String?>? pendingMachineRename(String machineId) => pending['rename'];
+ @override
+ String? pendingMachineName(String machineId) =>
+ pending.containsKey('rename') ? edits.last.value : null;
+ @override
+ Future<String?> deleteMachine(String machineId) =>
+ change('delete', machineId, '');
+ @override
+ Future<RemotePasswordStatus> remotePasswordStatus() async =>
+ RemotePasswordStatus(hasPassword: passwordSet);
+ @override
+ Future<RemotePasswordSetResult> setRemotePassword(String password) async =>
+ RemotePasswordSetResult(error: await change('password', 'm', password));
+ @override
+ Future<String?> clearRemotePassword() => change('clear', 'm', '');
+}
+
+class _ModelSelectionApp extends ModelManagerTestApp {
+ _ModelSelectionApp() : super(ModelManagerConnection());
+ bool completeStarts = false;
+
+ @override
+ Future<Map<String, dynamic>> controlLocalModel(
+ String machineId,
+ String modelId, {
+ required bool start,
+ }) async {
+ final answer = await super.controlLocalModel(
+ machineId,
+ modelId,
+ start: start,
+ );
+ if (!start || !completeStarts) return answer;
+ final original = inventoryFor(machineId);
+ final model = (original['models'] as List).singleWhere(
+ (model) => model['id'] == modelId,
+ );
+ setInventoryFor(machineId, {
+ ...original,
+ 'busy': false,
+ 'models': [
+ for (final entry in original['models'] as List)
+ if (entry['id'] == modelId)
+ {
+ ...entry as Map<String, dynamic>,
+ 'state': 'running',
+ 'canStart': false,
+ 'canStop': true,
+ 'operation': null,
+ }
+ else
+ entry,
+ ],
+ });
+ final host = stateOf(machineId)!.machine;
+ inventory = GridModels(
+ gridName: 'home',
+ models: [
+ ...inventory.models,
+ GridModel(
+ id: model['name'] as String,
+ node: host.hostname ?? host.displayName,
+ ),
+ ],
+ );
+ return {
+ 'operation': {
+ ...answer['operation'] as Map<String, dynamic>,
+ 'stage': 'verifying',
+ 'phase': 'done',
+ },
+ };
+ }
+
+ final selections =
+ <({String machine, String agent, String? model, String? grid})>[];
+
+ @override
+ Future<void> retargetAgentToGridModel(
+ String machineId,
+ String agentId,
+ String modelId, {
+ String? gridName,
+ }) async {
+ selections.add((
+ machine: machineId,
+ agent: agentId,
+ model: modelId,
+ grid: gridName,
+ ));
+ }
+
+ @override
+ Future<void> clearAgentGrid(String machineId, String agentId) async {
+ selections.add((
+ machine: machineId,
+ agent: agentId,
+ model: null,
+ grid: null,
+ ));
+ }
+}
+
Future<void> capture(WidgetTester tester, String name) async {
final directory = Platform.environment['RESOURCE_PICKER_CAPTURE_DIR'];
if (directory == null) return;
@@ -102,14 +263,687 @@ void main() {
.load();
});
+ for (final withKeymap in [false, true]) {
+ testWidgets('machine editors stay in Cmd P ($withKeymap)', (tester) async {
+ final app = _MachineApp();
+ await fixture(provided: app);
+ final map = MemoryKeymap();
+ app.machineStates['other']!
+ ..needsLink = true
+ ..nodeOnline = true;
+ try {
+ if (withKeymap) {
+ await configured.mount(tester, app, map);
+ } else {
+ await mount(tester, app);
+ }
+ await openHarnessPicker(tester);
+ await tester.enterText(field, '@');
+ await tester.pumpAndSettle();
+ final origin = search(tester);
+ final editor = tester.widget<TextField>(field).controller;
+ expect(origin.selected!.machineId, 'other');
+ expect(origin.rows.last.title, 'Add machine');
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final password = find.byKey(
+ const ValueKey('remote-password-connect-field'),
+ );
+ expect(password, findsOneWidget);
+ expect(find.byType(Dialog), findsNothing);
+ expect(field, findsOneWidget);
+ expect(origin.managing, isTrue);
+ await tester.enterText(password, 'fixture password');
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(origin.selected!.machineId, 'other');
+ expect(app.edits, isEmpty);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(tester.widget<TextField>(password).focusNode!.hasFocus, isTrue);
+ expect(
+ tester.widget<TextField>(password).controller!.text,
+ 'fixture password',
+ );
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(
+ tester.widget<TextField>(password).controller!.selection.extentOffset,
+ 15,
+ );
+ expect(origin.selected!.machineId, 'other');
+ app.editError = 'Password did not match.';
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Password did not match.'), findsOneWidget);
+ expect(app.edits.single.action, 'connect');
+ await capture(tester, 'machine-connect-inline');
+ app.editError = null;
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(MachinePickerForm), findsNothing);
+ expect(origin.selected!.machineId, 'other');
+ expect(origin.query, '@');
+ await tester.tap(
+ find.byKey(const ValueKey('resource-action:picker.resource_rename')),
+ );
+ await tester.pumpAndSettle();
+ final name = find.byKey(const ValueKey('machine-rename-input'));
+ expect(name, findsOneWidget);
+ expect(
+ tester
+ .widget<TextField>(name)
+ .controller!
+ .selection
+ .textInside('Other computer'),
+ 'Other computer',
+ );
+ await tester.enterText(name, 'Remote office');
+ await capture(tester, 'machine-rename-inline');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ app.machineStates['other']!.machine.displayName,
+ 'Remote office',
+ );
+ expect(origin.selected!.machineId, 'other');
+ expect(tester.widget<TextField>(field).controller, same(editor));
+ await tester.tap(
+ find.byKey(const ValueKey('resource-action:picker.resource_remove')),
+ );
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.edits.where((edit) => edit.action == 'delete'), isEmpty);
+ expect(find.byType(MachinePickerForm), findsNothing);
+ await tester.tap(
+ find.byKey(const ValueKey('resource-action:picker.resource_remove')),
+ );
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ app.edits.where((edit) => edit.action == 'delete'),
+ hasLength(1),
+ );
+ expect(find.byType(MachinePickerForm), findsNothing);
+ expect(origin.query, '@');
+ expect(find.byType(Dialog), findsNothing);
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ });
+
+ testWidgets('Manage focuses controls without running them ($withKeymap)', (
+ tester,
+ ) async {
+ final app = await fixture();
+ final map = MemoryKeymap();
+ try {
+ if (withKeymap) {
+ await configured.mount(tester, app, map);
+ } else {
+ await mount(tester, app);
+ }
+ await openHarnessPicker(tester);
+ await tester.enterText(field, '@This Mac');
+ await tester.pumpAndSettle();
+ final controller = search(tester);
+ final selectedId = controller.selected!.id;
+ final actions = find.byKey(
+ const ValueKey('swarm-search-resource-actions'),
+ );
+ expect(
+ find.descendant(of: actions, matching: find.text('[ Password ]')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: actions, matching: find.text('[ Rename ]')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: actions, matching: find.text('[ Actions… ]')),
+ findsNothing,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(controller.managing, isTrue);
+ expect(controller.isMachineMode, isTrue);
+ expect(
+ find.byKey(const ValueKey('remote-password-field')),
+ findsNothing,
+ );
+ TextButton button(String command) => tester.widget<TextButton>(
+ find.descendant(
+ of: find.byKey(ValueKey('resource-action:$command')),
+ matching: find.byType(TextButton),
+ ),
+ );
+ expect(button('picker.resource_settings').focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ expect(button('picker.resource_rename').focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(button('picker.resource_settings').focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(button('picker.resource_rename').focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ expect(button('picker.resource_settings').focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
+ expect(button('picker.resource_rename').focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.keyK, ctrl: true);
+ expect(button('picker.resource_settings').focusNode!.hasFocus, isTrue);
+ expect(controller.selected!.id, selectedId);
+ expect(controller.managing, isTrue);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(button('picker.resource_settings').focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(controller.selected!.id, selectedId);
+ await capture(tester, 'machine-controls');
+
+ await tester.enterText(field, ':Qwen3.8-27B');
+ await tester.pumpAndSettle();
+ expect(button('picker.model_download').onPressed, isNotNull);
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.model_start')),
+ findsNothing,
+ );
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.model_stop')),
+ findsNothing,
+ );
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(controller.managing, isTrue);
+ expect(button('picker.model_download').focusNode!.hasFocus, isTrue);
+ expect(app.actions, isEmpty);
+ expect(app.downloads, isEmpty);
+ await tester.pump(const Duration(milliseconds: 200));
+ await capture(tester, 'model-manage-focused');
+ await key(tester, LogicalKeyboardKey.space);
+ expect(app.downloads, [(machine: 'm', model: 'qwen')]);
+ expect(button('picker.model_download').onPressed, isNull);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.downloads, hasLength(1));
+ expect(app.actions, isEmpty);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(controller.query, ':Qwen3.8-27B');
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ });
+ }
+
testWidgets(
- 'platform picker and command shortcuts',
+ 'password edits validate, clear drafts and confirm clearing in place',
+ (tester) async {
+ final app = _MachineApp();
+ await fixture(provided: app);
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await openHarnessPicker(tester);
+ await tester.enterText(field, '@This Mac');
+ await tester.pumpAndSettle();
+ Future<void> openPassword() async {
+ await tester.tap(
+ find.byKey(
+ const ValueKey('resource-action:picker.resource_settings'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ final password = find.byKey(const ValueKey('remote-password-field'));
+ final confirm = find.byKey(
+ const ValueKey('remote-password-confirm-field'),
+ );
+ await openPassword();
+ await tester.enterText(password, 'fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(tester.widget<TextField>(confirm).focusNode!.hasFocus, isTrue);
+ await tester.enterText(confirm, 'different');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(find.text('Passwords do not match.'), findsOneWidget);
+ expect(app.edits, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await openPassword();
+ expect(tester.widget<TextField>(password).controller!.text, isEmpty);
+ expect(tester.widget<TextField>(confirm).controller!.text, isEmpty);
+ await tester.enterText(password, 'fixture password');
+ await tester.enterText(confirm, 'fixture password');
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(password).obscureText, isFalse);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(tester.widget<TextField>(password).obscureText, isTrue);
+ await tester.tap(confirm);
+ await capture(tester, 'machine-password-inline');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.edits.single.action, 'password');
+ expect(find.text('Password saved.'), findsOneWidget);
+ await openPassword();
+ expect(find.text('Password is set.'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('machine-form:Clear')));
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.edits, hasLength(1));
+ await openPassword();
+ await tester.tap(find.byKey(const ValueKey('machine-form:Clear')));
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.edits.last.action, 'clear');
+ expect(find.text('Password cleared.'), findsOneWidget);
+ expect(find.byType(Dialog), findsNothing);
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'inline rename respects remaps and composition in a narrow pane',
+ (tester) async {
+ final app = _MachineApp();
+ await fixture(provided: app);
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await tester.binding.setSurfaceSize(const Size(800, 600));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await openHarnessPicker(tester);
+ await tester.enterText(field, '@');
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('resource-action:picker.resource_rename')),
+ );
+ await tester.pumpAndSettle();
+ final name = find.byKey(const ValueKey('machine-rename-input'));
+ map.apply(
+ '{"bindings":[{"keys":"enter","command":null,"when":"picker"},{"keys":"f8","command":"picker.accept","when":"picker"},{"keys":"f9","command":"picker.cancel","when":"picker"}]}',
+ );
+ const composing = TextEditingValue(
+ text: '日本',
+ selection: TextSelection.collapsed(offset: 2),
+ composing: TextRange(start: 0, end: 2),
+ );
+ tester.testTextInput.updateEditingValue(composing);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.f8);
+ expect(app.edits, isEmpty);
+ expect(tester.widget<TextField>(name).controller!.text, '日本');
+ tester.testTextInput.updateEditingValue(
+ composing.copyWith(composing: TextRange.empty),
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.edits, isEmpty);
+ await capture(tester, 'machine-rename-inline-narrow');
+ await key(tester, LogicalKeyboardKey.f8);
+ await tester.pumpAndSettle();
+ expect(app.edits.single.value, '日本');
+ expect(find.byType(MachinePickerForm), findsNothing);
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'pending machine edits survive leaving the form without stealing selection',
+ (tester) async {
+ final app = _MachineApp();
+ await fixture(provided: app);
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await openHarnessPicker(tester);
+ await tester.enterText(field, '@Other');
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('resource-action:picker.resource_rename')),
+ );
+ await tester.pumpAndSettle();
+ final reply = app.editReply = Completer<String?>();
+ await tester.enterText(
+ find.byKey(const ValueKey('machine-rename-input')),
+ 'Renamed remote',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Saving…'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('resource-action:picker.resource_rename')),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Saving…'), findsOneWidget);
+ expect(app.edits, hasLength(1));
+ await tester.enterText(field, '@This Mac');
+ await tester.pumpAndSettle();
+ expect(find.byType(MachinePickerForm), findsNothing);
+ reply.complete(null);
+ await tester.pumpAndSettle();
+ expect(search(tester).selected!.machineId, 'm');
+ expect(search(tester).query, '@This Mac');
+ expect(app.edits, hasLength(1));
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'Download stays separate from Start and reports progress in place',
(tester) async {
final app = await fixture();
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await openHarnessPicker(tester);
+ await tester.enterText(field, ':Qwen3.8-27B');
+ await tester.pumpAndSettle();
+ final origin = search(tester);
+ expect(find.text('Enter Get · Tab pane'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(app.downloads, [(machine: 'm', model: 'qwen')]);
+ expect(app.actions, isEmpty);
+ expect(find.text('Downloading 42%'), findsOneWidget);
+ expect(search(tester), same(origin));
+ expect(origin.query, ':Qwen3.8-27B');
+ await capture(tester, 'model-downloading');
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'Cmd I selects for the pinned pane and Tab manages the model host',
+ (tester) async {
+ final app = _ModelSelectionApp()
+ ..inventory = const GridModels(
+ gridName: 'home',
+ models: [GridModel(id: 'qwen3.8-27b', node: 'mac.lan')],
+ grids: [
+ GridSection(
+ name: 'home',
+ own: true,
+ models: [GridModel(id: 'qwen3.8-27b', node: 'mac.lan')],
+ ),
+ GridSection(
+ name: 'Team',
+ own: false,
+ models: [GridModel(id: 'Gemma-4-E4B', node: 'shared.lan')],
+ ),
+ ],
+ );
+ await fixture(provided: app);
+ app.machineStates['m']!
+ ..localEndpoint = LocalCliEndpoint(
+ computerId: 'fixture',
+ wsUri: Uri.parse('ws://fixture.invalid'),
+ protocolVersion: 1,
+ terminalProtocolVersion: 3,
+ )
+ ..agents.add(
+ const Agent(
+ id: 'a69',
+ name: 'Current harness',
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ );
+ app.machineStates['other']!
+ ..machine = const Machine(
+ machineId: 'other',
+ authMode: MachineAuthMode.remote,
+ name: 'M2',
+ hostname: 'mac.lan',
+ )
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ app.machineInventories['other'] = {
+ 'models': [
+ {
+ 'id': 'local:Qwen3.8-27B-Q4_0.gguf',
+ 'name': 'qwen3.8-27b',
+ 'state': 'running',
+ 'canStop': true,
+ 'sizeBytes': 16056478688,
+ },
+ ],
+ };
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ expect(search(tester).modelSelectionEngine, 'codex');
+ expect(search(tester).selected!.title, 'OpenAI');
+ expect(
+ search(tester).rows.any((row) => row.modelId == 'model:local:qwen'),
+ isFalse,
+ );
+ for (final heading in [
+ 'Subscriptions',
+ 'APIs',
+ 'Your local AI models',
+ 'Shared with you',
+ ]) {
+ expect(
+ find.byKey(ValueKey('model-section:$heading')),
+ findsOneWidget,
+ );
+ }
+ final browse = search(tester).rows
+ .indexWhere(search(tester).isModelDownloadsRow);
+ search(tester).move(browse - search(tester).cursor);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(search(tester).modelDownloadsVisible, isTrue);
+ expect(
+ search(tester)
+ .models!
+ .entries[search(tester).selected!.modelId]!
+ .needsDownload,
+ isTrue,
+ );
+ expect(search(tester).modelRowAction(search(tester).selected!), 'Get');
+ expect(app.actions, isEmpty);
+ expect(app.downloads, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ expect(search(tester).modelDownloadsVisible, isFalse);
+ final usable = search(tester).rows
+ .firstWhere((row) => row.title == 'qwen3.8-27b · Q4_0');
+ search(tester)
+ .move(search(tester).rows.indexOf(usable) - search(tester).cursor);
+ await tester.pump();
+ expect(
+ find.byKey(ValueKey('model-row-action:${usable.id}')),
+ findsOneWidget,
+ );
+ expect(search(tester).modelRowAction(usable), 'Use');
+ await capture(tester, 'four-model-sections');
+ await tester.enterText(field, ':mac.lan');
+ await tester.pumpAndSettle();
+ expect(
+ search(tester).rows.where((row) => row.isModel),
+ hasLength(1),
+ reason: search(tester).rows
+ .map((row) => '${row.id}: ${row.title}')
+ .join('\n'),
+ );
+ expect(find.text('Enter Use · Tab pane'), findsOneWidget);
+ expect(find.text('M2 · 15.0 GB'), findsOneWidget);
+ await capture(tester, 'remote-model-select');
+ final origin = search(tester);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(origin.managing, isTrue);
+ final stop = find.byKey(
+ const ValueKey('resource-action:picker.model_stop'),
+ );
+ final button = tester.widget<TextButton>(
+ find.descendant(of: stop, matching: find.byType(TextButton)),
+ );
+ expect(button.focusNode!.hasFocus, isTrue);
+ expect(app.actions, isEmpty);
+ expect(app.selections, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(origin.managing, isFalse);
+ expect(origin.query, ':mac.lan');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(field, findsNothing);
+ expect(app.selections, [
+ (machine: 'm', agent: 'a69', model: 'qwen3.8-27b', grid: 'home'),
+ ]);
+ expect(app.actions, isEmpty);
+
+ // The same model scope uses Enter consistently from either shortcut.
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.enterText(field, ':mac.lan');
+ await tester.pumpAndSettle();
+ expect(search(tester).canSelectModel(search(tester).selected), isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(field, findsNothing);
+ expect(app.selections, hasLength(2));
+
+ // Enter on downloaded weights starts, waits for serving, then switches.
+ app.completeStarts = true;
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ for (final heading in [
+ 'Subscriptions',
+ 'APIs',
+ 'Your local AI models',
+ 'Shared with you',
+ ]) {
+ expect(
+ find.byKey(ValueKey('model-section:$heading')),
+ findsOneWidget,
+ );
+ }
+ await capture(tester, 'model-sections');
+ await tester.enterText(field, ':gemma-4-12B');
+ await tester.pumpAndSettle();
+ expect(search(tester).canSelectModel(search(tester).selected), isTrue);
+ await capture(tester, 'downloaded-model-use');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(field, findsNothing);
+ expect(app.selections, hasLength(3));
+ expect(app.selections.last, (
+ machine: 'm',
+ agent: 'a69',
+ model: 'gemma-4-12B',
+ grid: 'home',
+ ));
+ expect(app.actions, [(machine: 'm', model: 'gemma', start: true)]);
+ expect(app.downloads, isEmpty);
+
+ // The pane can return to its own subscription without changing engine.
+ final agents = app.machineStates['m']!.agents;
+ agents[agents.indexWhere((agent) => agent.id == 'a69')] = const Agent(
+ id: 'a69',
+ name: 'Current harness',
+ engine: 'codex',
+ terminalAvailable: true,
+ gridModel: 'qwen3.8-27b',
+ );
+ app.notifyListeners();
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ expect(search(tester).selected!.title, 'qwen3.8-27b · Q4_0');
+ await tester.enterText(field, ':Anthropic');
+ await tester.pumpAndSettle();
+ expect(search(tester).canSelectModel(search(tester).selected), isFalse);
+ await tester.enterText(field, ':OpenAI');
+ await tester.pumpAndSettle();
+ expect(search(tester).canSelectModel(search(tester).selected), isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(field, findsNothing);
+ expect(app.selections.last, (
+ machine: 'm',
+ agent: 'a69',
+ model: null,
+ grid: null,
+ ));
+
+ // Selection cannot silently jump to a different pane after opening.
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.enterText(field, ':mac.lan');
+ await tester.pumpAndSettle();
+ app.adoptSessionForTest(terminal('a0', []));
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.selections, hasLength(4));
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'platform picker and command shortcuts',
+ (tester) async {
+ final provided = ModelManagerTestApp(ModelManagerConnection())
+ ..inventory = const GridModels(
+ gridName: 'home',
+ models: [GridModel(id: 'qwen3.8-27b', node: 'mac.lan')],
+ );
+ final app = await fixture(provided: provided);
final keymap = MemoryKeymap();
try {
await configured.mount(tester, app, keymap);
final mac = defaultTargetPlatform == TargetPlatform.macOS;
+ final pane = app.focusedPaneId;
+ await key(tester, LogicalKeyboardKey.keyI, cmd: mac, ctrl: !mac);
+ expect(search(tester).isModelMode, isTrue);
+ expect(tester.widget<TextField>(field).controller!.text, ':');
+ expect(
+ tester.widget<TextField>(field).controller!.selection,
+ const TextSelection.collapsed(offset: 1),
+ );
+ expect(app.focusedPaneId, pane);
+ expect(
+ search(tester).rows.any((row) => row.title == 'qwen3.8-27b'),
+ isTrue,
+ );
+ await tester.enterText(field, ':mac.lan');
+ await tester.pump();
+ expect(search(tester).selected!.title, 'qwen3.8-27b');
+ expect(find.text('On your machines · mac.lan'), findsOneWidget);
+ if (mac) await capture(tester, 'own-machine-model');
+ await key(tester, LogicalKeyboardKey.escape);
await key(tester, LogicalKeyboardKey.keyO, cmd: mac, ctrl: !mac);
expect(field, findsOneWidget);
expect(search(tester).scopePrefix, '#');
@@ -140,6 +974,13 @@ void main() {
expect(hints, findsNothing);
expect(search(tester).isModelMode, isTrue);
await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: mac, ctrl: !mac);
+ final origin = search(tester);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: mac, ctrl: !mac);
+ expect(search(tester), same(origin));
+ expect(search(tester).isModelMode, isTrue);
+ expect(tester.widget<TextField>(field).controller!.text, ':');
+ await key(tester, LogicalKeyboardKey.escape);
await key(
tester,
LogicalKeyboardKey.keyP,
@@ -182,9 +1023,21 @@ void main() {
final listPosition = tester.getTopLeft(
find.byKey(const ValueKey('swarm-search-result-list')),
);
- const fullHint =
- '@ machines\n# projects\n: models\n* store\n> commands';
- expect(tester.widget<Text>(hints).data, fullHint);
+ const hintLabels = [
+ '@ machines',
+ '# projects',
+ ': models',
+ '* store',
+ '> commands',
+ ];
+ expect(
+ tester
+ .widgetList<Text>(
+ find.descendant(of: hints, matching: find.byType(Text)),
+ )
+ .map((text) => text.data),
+ hintLabels,
+ );
final controller = search(tester);
expect(controller.selected, isNull);
expect(controller.rows.any((row) => row.isCreate), isFalse);
@@ -219,7 +1072,9 @@ void main() {
expect(controller.selected, controller.rows.first);
expect(hints, findsNothing);
await key(tester, LogicalKeyboardKey.tab);
- expect(controller.selected, controller.rows[1]);
+ expect(controller.selected, controller.rows.first);
+ expect(controller.managing, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
await tester.enterText(field, 'search');
await tester.pump();
@@ -266,11 +1121,14 @@ void main() {
);
tester.view.physicalSize = const Size(480, 600);
await tester.pumpAndSettle();
- final compact = tester.widget<Text>(hints);
- expect(compact.data, fullHint);
- expect(compact.style!.fontSize, 18);
+ final compact = find
+ .descendant(of: hints, matching: find.byType(Text))
+ .first;
+ final compactStyle = DefaultTextStyle.of(tester.element(compact)).style;
+ expect(tester.widget<Text>(compact).data, hintLabels.first);
+ expect(compactStyle.fontSize, 18);
expect(
- compact.style!.color,
+ compactStyle.color,
terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
@@ -431,12 +1289,15 @@ void main() {
await openHarnessPicker(tester);
final reads = app.localReads;
for (final (prefix, label) in [
- ('@', 'New Machine'),
- (':', 'New Model'),
+ ('@', 'Add machine'),
+ (':', '[ Add ]'),
]) {
await tester.enterText(field, prefix);
await tester.pump();
- expect(search(tester).rows.first.title, label);
+ expect(
+ search(tester).rows.singleWhere((row) => row.isCreate).title,
+ label,
+ );
expect(search(tester).selected!.isCreate, isFalse);
expect(tester.widget<TextField>(field).controller!.text, prefix);
await tester.enterText(field, '${prefix}missing');
@@ -496,11 +1357,12 @@ void main() {
expect(controller.hasPreview, isFalse);
await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
final commandField = find.byKey(const ValueKey('resource-command-input'));
- await tester.enterText(commandField, 'download');
+ await tester.enterText(commandField, 'get');
await tester.pump();
- expect(find.textContaining('Download and start “'), findsOneWidget);
+ expect(find.text('Get'), findsOneWidget);
await key(tester, LogicalKeyboardKey.enter);
- expect(app.actions, [(machine: 'm', model: 'qwen', start: true)]);
+ expect(app.actions, isEmpty);
+ expect(app.downloads, [(machine: 'm', model: 'qwen')]);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
expect(controller.isModelMode, isTrue);
await key(tester, LogicalKeyboardKey.escape);
@@ -620,42 +1482,42 @@ void main() {
},
);
- testWidgets(
- 'machine Enter always opens its sessions, even before connection',
- (tester) async {
- final app = await fixture();
- await configured.mount(tester, app, MemoryKeymap());
- await openHarnessPicker(tester);
- for (final online in [false, true]) {
- app.stateOf('m')!
- ..nodeOnline = online
- ..needsLink = true;
- app.notifyListeners();
- await tester.enterText(field, '@');
- await tester.pump();
- final origin = search(tester);
- origin.move(
- origin.rows.indexWhere((row) => row.id == 'machine:m') -
- origin.cursor,
- );
- await tester.pump();
- final inputPosition = tester.getTopLeft(field);
- await key(tester, LogicalKeyboardKey.enter);
- expect(search(tester), same(origin));
- expect(origin.canGoBack, isTrue);
- expect(origin.scopedMachineId, 'm');
- expect(tester.getTopLeft(field), inputPosition);
- expect(find.text(origin.title), findsNothing);
- expect(find.byType(TextField), findsOneWidget);
- expect(app.actions, isEmpty);
- await capture(tester, 'machine-sessions');
- await key(tester, LogicalKeyboardKey.escape);
- expect(origin.isMachineMode, isTrue);
- }
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- },
- );
+ testWidgets('machine Enter manages in place, even before connection', (
+ tester,
+ ) async {
+ final app = await fixture();
+ await configured.mount(tester, app, MemoryKeymap());
+ await openHarnessPicker(tester);
+ for (final online in [false, true]) {
+ app.stateOf('m')!
+ ..nodeOnline = online
+ ..needsLink = true;
+ app.notifyListeners();
+ await tester.enterText(field, '@');
+ await tester.pump();
+ final origin = search(tester);
+ origin.move(
+ origin.rows.indexWhere((row) => row.id == 'machine:m') - origin.cursor,
+ );
+ await tester.pump();
+ final inputPosition = tester.getTopLeft(field);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(search(tester), same(origin));
+ expect(origin.canGoBack, isFalse);
+ expect(origin.isMachineMode, isTrue);
+ expect(origin.managing, isTrue);
+ expect(origin.scopedMachineId, isNull);
+ expect(tester.getTopLeft(field), inputPosition);
+ expect(find.text(origin.title), findsNothing);
+ expect(find.byType(TextField), findsOneWidget);
+ expect(app.actions, isEmpty);
+ await capture(tester, 'machine-management');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(origin.isMachineMode, isTrue);
+ }
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
testWidgets(
'action cancellation preserves search and stale targets cannot run',
@@ -683,7 +1545,7 @@ void main() {
shift: true,
);
final commands = find.byKey(const ValueKey('resource-command-input'));
- await tester.enterText(commands, 'download');
+ await tester.enterText(commands, 'get');
await tester.pump();
expect(search(tester).rows, hasLength(1));
await key(tester, LogicalKeyboardKey.escape);
@@ -698,7 +1560,7 @@ void main() {
ctrl: !mac,
shift: true,
);
- await tester.enterText(commands, 'download');
+ await tester.enterText(commands, 'get');
await tester.pump();
origin.move(1);
await tester.pump();
@@ -728,7 +1590,21 @@ void main() {
await tester.pump();
await key(tester, LogicalKeyboardKey.arrowUp);
await key(tester, LogicalKeyboardKey.enter);
- expect(find.text('Link another machine'), findsWidgets);
+ expect(find.byType(MachinePickerForm), findsNothing);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Add machine · App'), findsOneWidget);
+ expect(find.byType(Dialog), findsNothing);
+ await capture(tester, 'machine-setup-app-inline');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Add machine · CLI'), findsOneWidget);
+ await capture(tester, 'machine-setup-cli-inline');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
await key(tester, LogicalKeyboardKey.escape);
expect(search(tester).isMachineMode, isTrue);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
@@ -740,10 +1616,28 @@ void main() {
);
await tester.pump();
await key(tester, LogicalKeyboardKey.enter);
+ expect(controller.managing, isFalse);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(controller.managing, isTrue);
+ expect(find.byType(ApiPickerForm), findsNothing);
+ await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
- expect(find.byType(ApiConnectionsPanel), findsOneWidget);
+ expect(find.byType(ApiPickerForm), findsOneWidget);
expect(find.text('https://api.deepseek.com'), findsWidgets);
- Navigator.of(tester.element(find.byType(ApiConnectionsPanel))).pop();
+ expect(find.byType(Dialog), findsNothing);
+ final name = find.byKey(const ValueKey('api-form-input:name'));
+ await tester.enterText(name, 'Draft API');
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(controller.managing, isFalse);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(tester.widget<TextField>(name).focusNode!.hasFocus, isTrue);
+ expect(tester.widget<TextField>(name).controller!.text, 'Draft API');
+ await capture(tester, 'api-edit-inline');
+ await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(search(tester).selected!.modelId, 'model:api:deepseek-api');
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
@@ -791,19 +1685,23 @@ void main() {
grid.AppTheme.palette.value,
terminalThemeStore.value,
);
- final previewText = tester.widgetList<Text>(
- find.descendant(
- of: find.byType(SwarmResourcePreview),
- matching: find.byType(Text),
- ),
+ final previewText = find.descendant(
+ of: find.byType(SwarmResourcePreview),
+ matching: find.byType(Text),
);
- expect(previewText, isNotEmpty);
- for (final text in previewText) {
- expect(text.style!.fontSize, 18);
- expect(text.style!.height, 1.4);
+ expect(previewText, findsWidgets);
+ for (final element in previewText.evaluate()) {
+ final text = element.widget as Text;
+ final style = DefaultTextStyle.of(element).style.merge(text.style);
+ expect(style.fontSize, 18);
+ expect(style.height, 1.4);
expect(
- text.style!.color,
- isIn([theme.foreground, theme.foreground.withValues(alpha: .54)]),
+ style.color,
+ isIn([
+ theme.foreground,
+ theme.foreground.withValues(alpha: .54),
+ theme.foreground.withValues(alpha: .28),
+ ]),
);
}
expect(controller.selected!.id, selected);
@@ -814,7 +1712,7 @@ void main() {
await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
final commandField = find.byKey(const ValueKey('resource-command-input'));
- await tester.enterText(commandField, 'start');
+ await tester.enterText(commandField, 'get');
await tester.pumpAndSettle();
final commandSearch = search(tester);
final commandId = commandSearch.selected!.id;
@@ -844,7 +1742,7 @@ void main() {
tester.widget<TextField>(commandField).controller,
same(commandEditor),
);
- expect(commandEditor.text, 'start');
+ expect(commandEditor.text, 'get');
expect(
tester.widget<TextField>(commandField).focusNode!.hasFocus,
isTrue,
@@ -889,7 +1787,7 @@ void main() {
('Checkout', 'harnesses'),
('@', 'machines'),
('#', 'projects'),
- (':', 'models'),
+ (':qwen', 'models'),
(':deepseek', 'api'),
('*', 'store'),
]) {
@@ -935,12 +1833,16 @@ void main() {
);
}
for (var i = 1; i < visibleRows.length; i++) {
+ final sectionBreak =
+ controller.isModelMode &&
+ controller.modelSection(visibleRows[i]) !=
+ controller.modelSection(visibleRows[i - 1]);
expect(
tester.getTopLeft(find.byKey(ValueKey(visibleRows[i].id))).dy -
tester
.getTopLeft(find.byKey(ValueKey(visibleRows[i - 1].id)))
.dy,
- closeTo(cell.height, .01),
+ closeTo(cell.height * (sectionBreak ? 3 : 1), .01),
);
}
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
@@ -953,7 +1855,9 @@ void main() {
expect(
find.descendant(
of: preview,
- matching: find.text(controller.createDescription),
+ matching: find.text(
+ controller.createDescription.split('\n').first,
+ ),
),
findsOneWidget,
);
@@ -1006,12 +1910,17 @@ void main() {
findsOneWidget,
);
expect(
- find.descendant(of: preview, matching: find.text(selected.detail)),
+ find.descendant(
+ of: preview,
+ matching: find.text(
+ selected.isMachine ? '1 harness' : selected.detail,
+ ),
+ ),
findsOneWidget,
);
expect(
find.descendant(of: preview, matching: find.text('Checkout retries')),
- findsOneWidget,
+ selected.isMachine ? findsNothing : findsOneWidget,
);
expect(tester.takeException(), isNull);
}
diff --git a/desktop/test/resource_preview_actions_test.dart b/desktop/test/resource_preview_actions_test.dart
index ddaa8937b..05110c203 100644
--- a/desktop/test/resource_preview_actions_test.dart
+++ b/desktop/test/resource_preview_actions_test.dart
@@ -4,13 +4,14 @@ import 'package:harness/auth/cli_link.dart';
import 'package:harness/core/dsh_catalog.dart';
import 'package:harness/core/machine_resources.dart';
import 'package:harness/core/models.dart';
-import 'package:harness/models/api_connections_panel.dart';
+import 'package:harness/widgets/api_picker_form.dart';
import 'package:harness/models/model_search_catalog.dart';
import 'package:harness/state/harness_sessions.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/usage/models_menu_controller.dart';
import 'package:harness/widgets/swarm_resource_preview.dart';
+import 'package:harness/widgets/terminal_text_action.dart';
import 'support/model_manager.dart';
import 'support/real_fonts.dart';
@@ -93,7 +94,6 @@ void main() {
late SwarmSearchController search;
late SearchPreviewControls controls;
final choices = <SwarmSearchSelection>[];
- int managerOpens = 0;
int refocuses = 0;
final modals = <bool>[];
@@ -113,6 +113,11 @@ void main() {
gridName: 'home',
models: [],
grids: [
+ GridSection(
+ name: 'home',
+ own: true,
+ models: [GridModel(id: 'qwen3.8-27b', node: 'mac.lan')],
+ ),
GridSection(
name: 'Team',
own: false,
@@ -133,7 +138,11 @@ void main() {
await app.modelManager.refresh();
await app.modelManager.apis.refresh();
subscriptions = _Subscriptions();
- catalog = ModelSearchCatalog(app.modelManager, subscriptions);
+ catalog = ModelSearchCatalog(
+ app.modelManager,
+ subscriptions,
+ pollHosts: false,
+ );
search = SwarmSearchController(
app,
const [],
@@ -145,7 +154,7 @@ void main() {
controls = SearchPreviewControls();
choices.clear();
modals.clear();
- managerOpens = refocuses = 0;
+ refocuses = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
@@ -154,7 +163,6 @@ void main() {
controls: controls,
onChoose: choices.add,
onRefocus: () => refocuses++,
- onManageModels: () async => managerOpens++,
onModalChanged: modals.add,
onCommands: () {},
),
@@ -177,30 +185,82 @@ void main() {
await tester.pumpAndSettle();
}
- Future<void> closeDialog(WidgetTester tester) async {
- Navigator.of(
- tester.element(find.byType(SwarmResourcePreview, skipOffstage: false)),
- ).pop();
- await tester.pumpAndSettle();
- expect(modals.last, isFalse);
+ Future<void> closeApiEditor(WidgetTester tester) async {
+ await invoke(tester, 'picker.cancel');
+ expect(find.byType(ApiPickerForm), findsNothing);
+ expect(modals, isEmpty);
expect(refocuses, greaterThan(0));
}
- testWidgets('shared and subscription metadata opens the terminal manager', (
+ testWidgets('shared and subscription management stays in the picker', (
tester,
) async {
await mount(tester, ':Shared Qwen');
expect(find.text('Shared · Team · Team computer'), findsOneWidget);
- expect(find.text('Available'), findsOneWidget);
+ expect(find.text('Available'), findsNothing);
await invoke(tester, 'picker.accept');
- expect(managerOpens, 1);
+ expect(choices, isEmpty);
search.setQuery(':Codex subscription');
+ search.setModelSelection('claude', app.inventory, machineId: 'm');
await tester.pumpAndSettle();
- expect(find.text('Account Fixture account'), findsOneWidget);
+ expect(find.text('Codex subscription · Fixture account'), findsOneWidget);
expect(find.text('10% used'), findsOneWidget);
expect(find.text('Usage available'), findsOneWidget);
+ final before = refocuses;
+ await invoke(tester, 'picker.accept');
+ expect(choices, isEmpty);
+ expect(refocuses, before);
+ expect(search.managing, isFalse);
+ await invoke(tester, 'picker.complete');
+ expect(search.managing, isTrue);
+ expect(
+ tester
+ .widget<TerminalTextAction>(
+ find.byKey(const ValueKey('resource-action:picker.refresh')),
+ )
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
await invoke(tester, 'picker.accept');
- expect(managerOpens, 2);
+ expect(subscriptions.refreshes, 1);
+ expect(app.actions, isEmpty);
+ });
+
+ testWidgets('own-machine models remain visible when local discovery fails', (
+ tester,
+ ) async {
+ await mount(tester, ':mac.lan');
+ expect(find.text('qwen3.8-27b'), findsOneWidget);
+ expect(find.text('On your machines · mac.lan'), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.accept')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.model_stop')),
+ findsNothing,
+ );
+ final selected = search.selected!.id;
+ app.localReadFails = true;
+ await invoke(tester, 'picker.refresh');
+ expect(search.selected!.id, selected);
+ expect(
+ find.textContaining('Local models · Models are unavailable'),
+ findsOneWidget,
+ );
+ search.setQuery(':Shared Qwen');
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining('Local models · Models are unavailable'),
+ findsOneWidget,
+ );
+ app.localReadFails = false;
+ await invoke(tester, 'picker.refresh');
+ expect(
+ find.byKey(const ValueKey('local-model-inventory-notice')),
+ findsNothing,
+ );
expect(app.actions, isEmpty);
});
@@ -208,21 +268,154 @@ void main() {
tester,
) async {
await mount(tester, ':Qwen3.8-27B', scenario: 'ready');
- expect(find.text('17.6 tokens/sec'), findsOneWidget);
- expect(find.text('42 requests / 86400 sec'), findsOneWidget);
+ expect(find.text('17.6 tok/s · 42 requests / 1d'), findsOneWidget);
await invoke(tester, 'picker.accept');
- expect(managerOpens, 1);
+ expect(choices, isEmpty);
final reads = app.localReads;
await invoke(tester, 'picker.refresh');
expect(app.localReads, greaterThan(reads));
expect(subscriptions.refreshes, 1);
expect(app.apiCalls.last, 'list');
- await invoke(tester, 'picker.resource_toggle');
+ await tester.tap(
+ find.byKey(const ValueKey('resource-action:picker.model_stop')),
+ );
+ await tester.pumpAndSettle();
expect(app.actions.single.start, isFalse);
await invoke(tester, 'picker.resource_toggle');
expect(app.actions, hasLength(1));
});
+ testWidgets('Grid hostname resolves to remote Harness controls in place', (
+ tester,
+ ) async {
+ await mount(tester, ':mac.lan');
+ final id = search.selected!.id;
+ app.machineStates['other']!.machine = const Machine(
+ machineId: 'other',
+ authMode: MachineAuthMode.remote,
+ name: 'M2',
+ hostname: 'mac.lan',
+ );
+ const modelId = 'local:Qwen3.8-27B-Q4_0.gguf';
+ final running = <String, dynamic>{
+ 'id': modelId,
+ 'name': 'qwen3.8-27b',
+ 'state': 'running',
+ 'canStart': false,
+ 'canStop': true,
+ 'sizeBytes': 16 * 1024 * 1024 * 1024,
+ 'tokensPerSecond': 17.6,
+ 'requests': 42,
+ 'windowSeconds': 86400,
+ };
+ app.machineInventories['other'] = {
+ 'models': [running],
+ 'busy': false,
+ };
+ catalog.setVisible(true);
+ await tester.pumpAndSettle();
+ expect(search.selected!.id, id);
+ expect(
+ search.rows.where((row) => row.title == 'qwen3.8-27b · Q4_0'),
+ hasLength(1),
+ );
+ expect(find.text('M2 · 16.0 GB'), findsOneWidget);
+ expect(find.text('17.6 tok/s · 42 requests / 1d'), findsOneWidget);
+ TerminalTextAction button(String action) => tester.widget(
+ find.byKey(ValueKey('resource-action:picker.model_$action')),
+ );
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.model_download')),
+ findsNothing,
+ );
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.model_start')),
+ findsNothing,
+ );
+ expect(button('stop').onPressed, isNotNull);
+ final originalLocal = app.localInventory;
+ await invoke(tester, 'picker.model_stop');
+ expect(app.actions, [(machine: 'other', model: modelId, start: false)]);
+ expect(app.localInventory, same(originalLocal));
+ expect(find.text('Stopping'), findsOneWidget);
+ expect(app.connection.creations, isEmpty);
+
+ // Stop removes the serving row, but its management row and selection stay.
+ app.machineInventories['other'] = {
+ 'models': [
+ {...running, 'state': 'downloaded', 'canStart': true, 'canStop': false},
+ ],
+ 'busy': false,
+ };
+ app.inventory = const GridModels(gridName: 'home', models: []);
+ await catalog.refresh(force: true);
+ await tester.pumpAndSettle();
+ expect(search.selected!.id, id);
+ search.setModelSelection('codex', app.inventory, machineId: 'm');
+ await tester.pump();
+ expect(button('start').onPressed, isNotNull);
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.model_stop')),
+ findsNothing,
+ );
+ app.machineStates['other']!.connectionStatus =
+ ConnectionStatus.disconnected;
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(button('start').onPressed, isNull);
+ expect(find.text('Connect to M2 to manage its models.'), findsOneWidget);
+ await invoke(tester, 'picker.model_start');
+ expect(app.actions, hasLength(1));
+ });
+
+ testWidgets(
+ 'older hosts prepare models with Get and explain their combined download and start',
+ (tester) async {
+ await mount(tester, ':Falcon');
+ app.machineStates['other']!.machine = const Machine(
+ machineId: 'other',
+ authMode: MachineAuthMode.remote,
+ name: 'M2',
+ hostname: 'mac.lan',
+ );
+ app.machineInventories['other'] = {
+ 'models': [
+ {
+ 'id': 'falcon-q4',
+ 'name': 'Falcon-H1R-7B',
+ 'quant': 'Q4_K_XL',
+ 'state': 'available',
+ 'canStart': true,
+ },
+ ],
+ };
+ catalog.setVisible(true);
+ await tester.pumpAndSettle();
+ TerminalTextAction button(String action) => tester.widget(
+ find.byKey(ValueKey('resource-action:picker.model_$action')),
+ );
+ expect(find.text('Downloads and starts on M2.'), findsOneWidget);
+ expect(find.textContaining('Update Harness'), findsNothing);
+ expect(button('download').label, 'Get');
+ expect(button('download').onPressed, isNotNull);
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.model_start')),
+ findsNothing,
+ );
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.model_stop')),
+ findsNothing,
+ );
+ await invoke(tester, 'picker.model_download');
+ expect(app.actions, [
+ (machine: 'other', model: 'falcon-q4', start: true),
+ ]);
+ expect(app.downloads, isEmpty);
+ expect(find.text('Downloading 42%'), findsOneWidget);
+ expect(find.text('Downloads and starts on M2.'), findsNothing);
+ },
+ );
+
testWidgets('empty and refreshing models never invent a result', (
tester,
) async {
@@ -236,7 +429,7 @@ void main() {
app.localReadFails = true;
await invoke(tester, 'picker.refresh');
expect(app.modelManager.error, isNotNull);
- expect(find.text(app.modelManager.error!), findsWidgets);
+ expect(find.textContaining(app.modelManager.error!), findsOneWidget);
expect(choices, isEmpty);
});
@@ -245,24 +438,25 @@ void main() {
(tester) async {
await mount(tester, ':DeepSeek');
await invoke(tester, 'picker.resource_remove');
- expect(find.text('Remove DeepSeek API?'), findsOneWidget);
- await tester.tap(find.text('Cancel'));
+ expect(find.text('Delete DeepSeek API?'), findsOneWidget);
+ expect(find.byType(Dialog), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('api-form:cancel')));
await tester.pumpAndSettle();
expect(app.apiCalls, ['list']);
expect(search.selected!.modelId, 'model:api:deepseek');
app.removeFails = true;
await invoke(tester, 'picker.resource_remove');
- await tester.tap(find.text('Remove'));
+ await tester.tap(find.byKey(const ValueKey('api-form:delete')));
await tester.pumpAndSettle();
expect(find.text('Try removal again'), findsOneWidget);
app.removeFails = false;
await invoke(tester, 'picker.resource_remove');
- await tester.tap(find.text('Remove'));
+ await tester.tap(find.byKey(const ValueKey('api-form:delete')));
await tester.pumpAndSettle();
expect(app.apiCalls.where((action) => action == 'remove'), hasLength(2));
expect(search.rows, isEmpty);
expect(find.text('No matching models'), findsOneWidget);
- expect(modals, [true, false, true, false, true, false]);
+ expect(modals, isEmpty);
},
);
@@ -271,13 +465,12 @@ void main() {
(tester) async {
await mount(tester, ':DeepSeek');
await invoke(tester, 'picker.resource_settings');
- expect(find.byType(ApiConnectionsPanel), findsOneWidget);
- await tester.tap(find.byTooltip('Back to APIs'));
- await tester.pumpAndSettle();
- await closeDialog(tester);
+ expect(find.byType(ApiPickerForm), findsOneWidget);
+ expect(find.byType(Dialog), findsNothing);
+ await closeApiEditor(tester);
await invoke(tester, 'picker.resource_add_api');
- expect(find.byType(ApiConnectionsPanel), findsOneWidget);
- await closeDialog(tester);
+ expect(find.byType(ApiPickerForm), findsOneWidget);
+ await closeApiEditor(tester);
expect(search.selected!.modelId, 'model:api:deepseek');
expect(app.apiCalls, ['list']);
},
@@ -289,8 +482,8 @@ void main() {
await mount(tester, ':missing', create: true);
expect(search.selected!.isCreate, isTrue);
await invoke(tester, 'picker.resource_add_api');
- expect(find.byType(ApiConnectionsPanel), findsOneWidget);
- await closeDialog(tester);
+ expect(find.byType(ApiPickerForm), findsOneWidget);
+ await closeApiEditor(tester);
expect(app.actions, isEmpty);
expect(choices, isEmpty);
});
@@ -320,10 +513,10 @@ void main() {
expect(find.textContaining('RAM 4.0 / 16 GB'), findsOneWidget);
await invoke(tester, 'picker.resource_settings');
expect(find.textContaining('password'), findsWidgets);
- await closeDialog(tester);
+ await invoke(tester, 'picker.cancel');
await invoke(tester, 'picker.resource_link');
- expect(find.text('Link another machine'), findsWidgets);
- await closeDialog(tester);
+ expect(search.query, '@');
+ search.setQuery('@This Mac');
final machine = app.machineStates['m']!;
machine.machine = const Machine(
machineId: 'm',
@@ -344,10 +537,10 @@ void main() {
await mount(tester, '@Other computer');
await invoke(tester, 'picker.resource_remove');
expect(app.deleted, isEmpty);
- await closeDialog(tester);
+ await invoke(tester, 'picker.cancel');
expect(app.deleted, isEmpty);
final original = app.machineStates.remove('other');
- expect(controls.invoke('picker.accept'), isFalse);
+ expect(controls.invoke('picker.resource_rename'), isFalse);
app.machineStates['other'] = original!;
},
);
@@ -357,14 +550,16 @@ void main() {
) async {
await mount(tester, '@Other computer');
await invoke(tester, 'picker.resource_rename');
- expect(find.text('Rename Machine'), findsOneWidget);
- await closeDialog(tester);
+ expect(find.text('Rename machine'), findsOneWidget);
+ expect(find.byType(Dialog), findsNothing);
+ await invoke(tester, 'picker.cancel');
app.machineStates['other']!.needsLink = true;
app.notifyListeners();
await tester.pump();
await invoke(tester, 'picker.resource_connect');
expect(find.textContaining('Other computer'), findsWidgets);
- await closeDialog(tester);
+ expect(find.byType(Dialog), findsNothing);
+ await invoke(tester, 'picker.cancel');
expect(app.deleted, isEmpty);
expect(choices, isEmpty);
expect(search.selected!.machineId, 'other');
diff --git a/desktop/test/shortcuts_test.dart b/desktop/test/shortcuts_test.dart
index 3c1b7e749..d3cc48bb7 100644
--- a/desktop/test/shortcuts_test.dart
+++ b/desktop/test/shortcuts_test.dart
@@ -260,12 +260,13 @@ void main() {
test('the terminal verbs tmux trained people on are all here', () {
expect(chordsFor(ShortcutAction.zoomPane), contains('⌘⏎'));
- expect(chordsFor(ShortcutAction.lastPane), contains('⌘;'));
+ // The previous-pane command remains available through remapping.
+ expect(chordsFor(ShortcutAction.lastPane), isEmpty);
expect(chordsFor(ShortcutAction.newSwarm), ['⌘T']);
expect(chordsFor(ShortcutAction.showLayout), ['⇧⌘L']);
expect(chordsFor(ShortcutAction.orchestrate), isEmpty);
expect(chordsFor(ShortcutAction.routeTask), ['⌘B']);
- expect(chordsFor(ShortcutAction.addAgent), ['⌘P']);
+ expect(chordsFor(ShortcutAction.addAgent), ['⌘O']);
expect(chordsFor(ShortcutAction.newAgent), ['⌘N']);
expect(chordsFor(ShortcutAction.showAttention), ['⇧⌘I']);
expect(chordsFor(ShortcutAction.findTerminal), ['⌘F']);
diff --git a/desktop/test/support/model_manager.dart b/desktop/test/support/model_manager.dart
index f675eb19f..46d4722fc 100644
--- a/desktop/test/support/model_manager.dart
+++ b/desktop/test/support/model_manager.dart
@@ -101,7 +101,51 @@ class ModelManagerTestApp extends AppNotifier {
final sent = <({String id, String machine, String task})>[];
Map<String, dynamic> localInventory = modelInventory();
+ final machineInventories = <String, Map<String, dynamic>>{};
+ final inventoryReads = <String>[];
+ Map<String, dynamic> inventoryFor(String machineId) =>
+ machineInventories[machineId] ??
+ (machineId == 'm' ? localInventory : {'models': <Object>[]});
+ void setInventoryFor(String machineId, Map<String, dynamic> value) {
+ if (machineId == 'm') {
+ localInventory = value;
+ } else {
+ machineInventories[machineId] = value;
+ }
+ }
+
final actions = <({String machine, String model, bool start})>[];
+ final downloads = <({String machine, String model})>[];
+
+ @override
+ Future<Map<String, dynamic>> downloadLocalModel(
+ String machineId,
+ String modelId,
+ ) async {
+ downloads.add((machine: machineId, model: modelId));
+ final inventory = inventoryFor(machineId);
+ final operation = <String, dynamic>{
+ 'id': 'download',
+ 'modelId': modelId,
+ 'action': 'download',
+ 'stage': 'downloading',
+ 'phase': 'running',
+ 'progress': .42,
+ };
+ setInventoryFor(machineId, {
+ ...inventory,
+ 'busy': true,
+ 'models': [
+ for (final raw in inventory['models'] as List)
+ if (raw['id'] == modelId)
+ {...raw as Map<String, dynamic>, 'operation': operation}
+ else
+ raw,
+ ],
+ });
+ return {'operation': operation};
+ }
+
bool localReadFails = false, actionReplyLost = false;
Completer<Map<String, dynamic>>? actionReply;
@override
@@ -110,13 +154,14 @@ class ModelManagerTestApp extends AppNotifier {
bool refresh = false,
}) async {
localReads++;
+ inventoryReads.add(machineId);
final held = localReply;
if (held != null) {
localReply = null;
return held.future;
}
if (localReadFails) throw StateError('offline');
- return localInventory;
+ return inventoryFor(machineId);
}
@override
@@ -126,6 +171,7 @@ class ModelManagerTestApp extends AppNotifier {
required bool start,
}) async {
actions.add((machine: machineId, model: modelId, start: start));
+ final inventory = inventoryFor(machineId);
if (actionReply != null) return actionReply!.future;
final operation = <String, dynamic>{
'id': 'operation',
@@ -135,17 +181,17 @@ class ModelManagerTestApp extends AppNotifier {
'phase': 'running',
if (start) 'progress': .42,
};
- localInventory = {
- ...localInventory,
+ setInventoryFor(machineId, {
+ ...inventory,
'busy': true,
'models': [
- for (final raw in localInventory['models'] as List)
+ for (final raw in inventory['models'] as List)
if (raw['id'] == modelId)
{...raw as Map<String, dynamic>, 'operation': operation}
else
raw,
],
- };
+ });
if (actionReplyLost) throw StateError('lost acknowledgement');
return {'operation': operation};
}
@@ -210,6 +256,7 @@ Map<String, dynamic> modelInventory({String scenario = 'first'}) {
return {
'memoryBytes': 64 * 1024 * 1024 * 1024,
'hardware': 'Apple M2 Max',
+ 'supportsDownload': true,
'busy': scenario == 'downloading',
'models': [
{
diff --git a/desktop/test/support/workspace_tools.dart b/desktop/test/support/workspace_tools.dart
index 9111b0719..8641e86aa 100644
--- a/desktop/test/support/workspace_tools.dart
+++ b/desktop/test/support/workspace_tools.dart
@@ -1,3 +1,4 @@
+import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -14,3 +15,18 @@ Future<void> openWorkspaceTool(WidgetTester tester, String tool) async {
await key(tester, shortcut, cmd: true);
await tester.pump(const Duration(milliseconds: 350));
}
+
+/// Detailed management is reached by name from the shared search surface.
+Future<void> openWorkspaceManagement(WidgetTester tester, String tool) async {
+ final command = switch (tool) {
+ 'machines' => 'Machine connection settings',
+ 'models' => 'Manage models',
+ _ => 'Manage harnesses',
+ };
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(field, '> $command');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 350));
+}
diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dart
index 4093c2339..01cb5caca 100644
--- a/desktop/test/swarm_screen_test.dart
+++ b/desktop/test/swarm_screen_test.dart
@@ -38,6 +38,7 @@ Future<void> mount(
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
+ debugShowCheckedModeBanner: false,
theme: grid.buildAppTheme(brightness: Brightness.dark),
home: SwarmScreen(
notifier: app,
@@ -516,7 +517,7 @@ void main() {
find.byKey(const ValueKey('harness-start-search')),
findsOneWidget,
);
- expect(find.byKey(const ValueKey('swarm-models-button')), findsOneWidget);
+ expect(find.byKey(const ValueKey('swarm-search-button')), findsNothing);
expect(find.text('Machines'), findsNothing);
await openHarnessPicker(tester);
await tester.pump();
diff --git a/desktop/test/swarm_search_render_test.dart b/desktop/test/swarm_search_render_test.dart
index 787088c4a..b10015da8 100644
--- a/desktop/test/swarm_search_render_test.dart
+++ b/desktop/test/swarm_search_render_test.dart
@@ -254,7 +254,11 @@ void main() {
)
.search!;
final previous = search.selected!.id;
- final visibleRows = find.byType(InkWell).evaluate().toSet();
+ final visibleRows = find.byType(InkWell).evaluate().where((element) {
+ final key = element.widget.key;
+ return key is ValueKey<String> && key.value.startsWith('agent:');
+ }).toSet();
+ expect(visibleRows, isNotEmpty);
var fields = 0;
var rows = 0;
debugOnRebuildDirtyWidget = (element, _) {
diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dart
index 3dd105ef2..94a8e4b2d 100644
--- a/desktop/test/workspace_status_test.dart
+++ b/desktop/test/workspace_status_test.dart
@@ -160,6 +160,7 @@ void main() {
final app = createApp(connectionForTest: (_) => connection);
addTearDown(app.dispose);
app.machineStates['m']!.nodeOnline = true;
+ app.modelManager.models = await app.readGridPicture('m');
app.machineStates['m']!.agents = [
Agent.fromJson({
'id': 'a0',
@@ -209,7 +210,12 @@ void main() {
await tester.tap(selectors);
}
await tester.pumpAndSettle();
- await tester.tap(find.text('Local-Test-Model'));
+ final modelSearch = find.byKey(const ValueKey('swarm-search-input'));
+ expect(modelSearch, findsOneWidget);
+ expect(tester.widget<TextField>(modelSearch).controller!.text, ':');
+ await tester.enterText(modelSearch, ':Local-Test-Model');
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(connection.retargets.single['agentId'], 'a0');
expect(connection.retargets.single['gridModel'], 'Local-Test-Model');
@@ -221,10 +227,22 @@ void main() {
await tester.tap(selectors);
}
await tester.pumpAndSettle();
- expect(find.text('Local-Test-Model'), findsOneWidget);
+ expect(modelSearch, findsOneWidget);
app.focusPane(second.id);
await tester.pumpAndSettle();
- expect(find.text('Local-Test-Model'), findsNothing);
+ if (modelSearch.evaluate().isNotEmpty) {
+ await tester.enterText(modelSearch, ':Local-Test-Model');
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(connection.retargets, hasLength(1));
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ }
+ // Dismissing the picker restores its originating pane. Move again
+ // before checking that a callback captured for that pane is stale.
+ app.focusPane(second.id);
+ await tester.pump();
stale();
await tester.pump();
expect(connection.retargets, hasLength(1));
@@ -884,22 +902,9 @@ void main() {
}
}
expect(tester.getSize(secondTab).width, lessThan(150));
- final harnesses = find.byKey(const ValueKey('swarm-harnesses-button'));
- final machines = find.byKey(const ValueKey('swarm-machines-button'));
- final models = find.byKey(const ValueKey('swarm-models-button'));
- final store = find.byKey(const ValueKey('swarm-store-button'));
- expect(harnesses, findsOneWidget);
- expect(machines, findsOneWidget);
- expect(models, findsOneWidget);
- expect(store, findsOneWidget);
- expect(find.byKey(const ValueKey('swarm-help-button')), findsNothing);
- final tools = [harnesses, machines, models, store];
- final symbols = ['>', '@', ':', '*'];
- for (var i = 0; i < tools.length; i++) {
- expect(
- find.descendant(of: tools[i], matching: find.text(symbols[i])),
- findsOneWidget,
- );
+ expect(find.byKey(const ValueKey('swarm-search-button')), findsNothing);
+ for (final old in ['harnesses', 'machines', 'models', 'store', 'help']) {
+ expect(find.byKey(ValueKey('swarm-$old-button')), findsNothing);
}
expect(
find.descendant(
@@ -923,68 +928,10 @@ void main() {
tester.view.physicalSize = Size(width, 800);
await tester.pump(const Duration(milliseconds: 100));
expect(tester.takeException(), isNull);
- final rects = tools.map(tester.getRect).toList();
- expect(tester.getRect(context).right, lessThan(rects.first.left));
- expect(rects.last.right, lessThan(width));
- final paragraphs = tools
- .map(
- (tool) => tester.renderObject<RenderParagraph>(
- find.descendant(of: tool, matching: find.byType(RichText)),
- ),
- )
- .toList();
- final baselines = paragraphs
- .map(
- (paragraph) => paragraph
- .localToGlobal(
- Offset(
- 0,
- paragraph.getDryBaseline(
- paragraph.constraints,
- TextBaseline.alphabetic,
- )!,
- ),
- )
- .dy,
- )
- .toList();
- for (var i = 0; i < rects.length; i++) {
- expect(rects[i].width, closeTo(rects.first.width, .01));
- expect(rects[i].height, closeTo(rects.first.height, .01));
- expect(rects[i].width, greaterThanOrEqualTo(28));
- expect(rects[i].center.dy, rects.first.center.dy);
- expect(baselines[i], closeTo(baselines.first, .01));
- if (i > 0) {
- expect(rects[i].left, closeTo(rects[i - 1].right, .01));
- expect(
- rects[i].center.dx - rects[i - 1].center.dx,
- closeTo(rects.first.width, .01),
- );
- }
- }
+ expect(tester.getRect(context).right, lessThan(width));
}
}
- final symbol = find.descendant(of: machines, matching: find.text('@'));
- Color? color() => DefaultTextStyle.of(tester.element(symbol)).style.color;
- final resting = color();
- FontWeight? weight() => tester.widget<Text>(symbol).style?.fontWeight;
- expect(weight(), FontWeight.normal);
- final pointer = await tester.createGesture(kind: PointerDeviceKind.mouse);
- await pointer.addPointer(location: Offset.zero);
- await pointer.moveTo(tester.getCenter(machines));
- await tester.pump(const Duration(milliseconds: 800));
- await tester.pump(const Duration(milliseconds: 200));
- expect(find.text('Machines'), findsOneWidget);
- expect(color(), resting);
- expect(weight(), FontWeight.bold);
- await pointer.removePointer();
- await tester.pumpAndSettle();
- final focus = Focus.of(tester.element(symbol));
- focus.requestFocus();
- await tester.pumpAndSettle();
- expect(focus.hasFocus, isTrue);
- expect(color(), resting);
- expect(weight(), FontWeight.bold);
+ await captureControls(tester, 'unified-search-toolbar', height: 100);
await tester.pump(const Duration(milliseconds: 100));
await tester.pumpWidget(const SizedBox());
},
diff --git a/desktop/tool/keymap_native_checks.swift b/desktop/tool/keymap_native_checks.swift
index 07717f3d6..e56c6592c 100644
--- a/desktop/tool/keymap_native_checks.swift
+++ b/desktop/tool/keymap_native_checks.swift
@@ -27,7 +27,7 @@ for (key, command) in [
("cmd+up", "pane.focus_above"), ("cmd+right", "pane.focus_right"),
("cmd+s", "app.store"), ("cmd+shift+l", "pane.layout"),
("cmd+b", "task.route"), ("cmd+t", "swarm.new"),
- ("cmd+p", "agent.open"), ("cmd+shift+p", "navigation.commands"),
+ ("cmd+p", "harnesses.list"), ("cmd+o", "agent.open"), ("cmd+shift+p", "navigation.commands"),
("cmd+r", "pane.split_right"), ("cmd+d", "pane.split_down"),
("cmd+n", "agent.new"),
("cmd+m", "machines.list"),
@@ -50,10 +50,13 @@ for context in HarnessNativeKeymap.contexts {
let models = defaults.match([stroke("cmd+i")], context: context).binding
try checkKeymap(models?.command == "models.list" && models?.menuAction == "models" && models?.hint == "⌘I",
"Command-I opens Models with the matching native action and hint from \(context)")
+ let directModels = defaults.match([stroke("cmd+semicolon")], context: context).binding
+ try checkKeymap(directModels == nil,
+ "Command-semicolon is unbound from \(context)")
try checkKeymap(defaults.match([stroke("cmd+u")], context: context).binding == nil,
"The former Machines shortcut is unbound")
- try checkKeymap(defaults.match([stroke("cmd+o")], context: context).binding == nil,
- "The former picker shortcut is unbound")
+ try checkKeymap(defaults.match([stroke("cmd+o")], context: context).binding?.command == "agent.open",
+ "Command-O opens the project picker")
try checkKeymap(defaults.match([stroke("cmd+shift+n")], context: context).binding?.command == "agent.clone",
"Shift-Command-N clones the harness in \(context)")
for number in 1...9 {
@@ -62,6 +65,9 @@ for context in HarnessNativeKeymap.contexts {
}
}
for context in HarnessNativeKeymap.contexts {
+ try checkKeymap(changed.match([stroke("cmd+i")], context: context).binding == nil &&
+ changed.match([stroke("cmd+y")], context: context).binding?.command == "models.list",
+ "Models respects shortcut remaps from \(context)")
try checkKeymap(changed.match([stroke("cmd+t")], context: context).binding == nil,
"Native context honors inherited unbinding")
let search = changed.match([stroke("cmd+o")], context: context).binding
@@ -80,12 +86,12 @@ try checkKeymap(changed.match([stroke("ctrl+j")], context: "picker").binding?.co
"Picker remapping wins")
try checkKeymap(defaults.match([stroke("ctrl+slash")], context: "picker").binding?.command == "picker.toggle_preview",
"Preview visibility stays on Control-/ while Command-I opens Models")
-for (key, command) in [("pageup", "picker.preview_page_up"), ("pagedown", "picker.preview_page_down")] {
+for (key, command) in [("pageup", "picker.page_up"), ("pagedown", "picker.page_down")] {
try checkKeymap(defaults.match([stroke(key)], context: "picker").binding?.command == command,
- "Preview paging follows the exported Search binding")
+ "Result paging follows the exported Search binding")
for context in ["workspace", "terminal"] {
try checkKeymap(defaults.match([stroke(key)], context: context).binding == nil,
- "Preview paging leaves \(context) input alone")
+ "Result paging leaves \(context) input alone")
}
}
@@ -121,8 +127,8 @@ try checkKeymap(send("cmd+p", executable: false).handled && send("cmd+p", execut
"An unavailable mapped action cannot fall through as input")
try checkKeymap(send("cmd+p", repeated: true).command == nil, "Search does not repeat")
try checkKeymap(send("ctrl+j", repeated: true).command == "picker.previous", "Result movement repeats")
-try checkKeymap(send("pagedown", repeated: true).command == "picker.preview_page_down",
- "Holding a preview paging key continues scrolling")
+try checkKeymap(send("pagedown", repeated: true).command == "picker.page_down",
+ "Holding a result paging key continues scrolling")
_ = send("cmd+k")
dispatcher.suspend()
try checkKeymap(dispatcher.pending.isEmpty && !dispatcher.release(1), "Window blur clears pending and held keys")
@@ -131,6 +137,8 @@ try checkKeymap(send("cmd+t").command == "swarm.new", "Reload installs the new r
try checkKeymap(HarnessKeyStroke.fromCharacters("H", modifiers: [.command, .capsLock]) == stroke("cmd+h"),
"Caps Lock does not change a Command binding")
+try checkKeymap(HarnessKeyStroke.fromCharacters(";", modifiers: [.command]) == stroke("cmd+semicolon"),
+ "Command-semicolon remains a valid remappable key")
try checkKeymap(HarnessKeyStroke.fromCharacters("1", modifiers: [.command, .shift]) == stroke("cmd+shift+1"),
"Shift stays in modifiers after layout translation")
try checkKeymap(HarnessKeyStroke.fromCharacters("\u{f702}", modifiers: .command) == stroke("cmd+left"),
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index 7c256c290..acf84d370 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -245,13 +245,14 @@ private extension SwarmTabStrip {
"Numbered tabs use 13 pt SF Mono regular")
try checkTitlebar(tabs[0].drawnFont == tabs[1].drawnFont && contextButton.font == tabs[0].labelFont,
"Active tabs, inactive tabs, and pane context share one font")
- for control in [harnessesButton, machinesButton, modelsButton, storeButton] {
+ for control in [newButton] {
try checkTitlebar(control.font == contextButton.font && control.frame.midY == contextButton.frame.midY,
"Status symbols share the terminal font and centered text baseline")
}
try checkTitlebar(tabs[0].frame.width < tabs[1].frame.width,
"Each tab occupies its own text width and fixed cell gutters")
try checkTitlebar(tabs[0].menu?.font == menuFont, "Native context menus retain the system menu font")
+
}
func checkStartupPalette(_ expected: SwarmNativePalette) throws {
@@ -402,7 +403,7 @@ private extension SwarmTabStrip {
try checkTitlebar(!focusedModelButton.isHidden && focusedModelButton.isEnabled,
"Focused model has its own enabled status control")
try checkTitlebar(focusedModelButton.frame.maxX < contextButton.frame.minX &&
- focusedModelButton.frame.height == harnessesButton.frame.height,
+ focusedModelButton.frame.height == newButton.frame.height,
"Model sits before machine/repo with the shared control height")
try checkTitlebar(focusedModelButton.toolTip == "Switch model · Subscription or local models",
"Model hint explains switching without repeating the visible name")
@@ -443,15 +444,15 @@ private extension SwarmTabStrip {
newButton.frame.maxX < contextButton.frame.minX, "Tabs are left of the right-aligned focused context")
try checkTitlebar(tabs[0].frame.width < 120 && tabs[0].displayLabel == "1:code",
"Short numbered labels use text-sized widths")
- try checkTitlebar(subviews.count == 9 && pullRequestButton.isHidden && focusedModelButton.isHidden,
- "Four management symbols join the status controls; help stays hidden")
- let controls = [harnessesButton, machinesButton, modelsButton, storeButton]
- for (control, symbol) in zip(controls, [">", "@", ":", "*"]) {
+ try checkTitlebar(subviews.count == 5 && pullRequestButton.isHidden && focusedModelButton.isHidden,
+ "Context links fill the bar; standalone search and management controls are absent")
+ let controls = [newButton]
+ for (control, symbol) in zip(controls, ["+"]) {
try checkTitlebar(control.image == nil && control.title == symbol && !control.isBordered,
"Management controls are plain terminal text without a resting button well")
- try checkTitlebar(control.frame.size == harnessesButton.frame.size && control.frame.width >= 28,
- "All symbols have equally sized, generous click targets")
- try checkTitlebar(control.toolTip == control.accessibilityLabel() && control.toolTip?.isEmpty == false,
+ try checkTitlebar(control.frame.height >= 28 && control.frame.width > workspaceBarTextWidth(symbol, font: barFont),
+ "The new-tab control keeps the shared click height and padding around its text")
+ try checkTitlebar(control.accessibilityLabel() == "New Tab" && control.toolTip?.contains("New Tab") == true,
"Every symbol explains its action through a tooltip and accessible name")
let resting = control.renderedPixels()
let event = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],
@@ -494,11 +495,6 @@ private extension SwarmTabStrip {
try checkActiveVisible()
try checkTitlebar(newButton.frame.maxX < contextButton.frame.minX &&
contextButton.frame.maxX <= bounds.width, "Narrow windows have no overlapping controls")
- try checkTitlebar(contextButton.frame.maxX < harnessesButton.frame.minX &&
- harnessesButton.frame.maxX <= machinesButton.frame.minX &&
- machinesButton.frame.maxX <= modelsButton.frame.minX &&
- modelsButton.frame.maxX <= storeButton.frame.minX && storeButton.frame.maxX <= bounds.width,
- "Management symbols remain ordered at the right edge in narrow windows")
let original = tabs[0]
let reversed = Array(rows.reversed())
update(state(reversed, active: "swarm-0"))
@@ -514,24 +510,15 @@ private extension SwarmTabStrip {
events.removeAll()
contextButton.performClick(nil)
newButton.performClick(nil)
- harnessesButton.performClick(nil)
- machinesButton.performClick(nil)
- modelsButton.performClick(nil)
- storeButton.performClick(nil)
original.clickBothActions()
- try checkTitlebar(events == ["new", "harnessControls", "machineControls", "modelControls", "store", "select", "close"], "Visible controls dispatch their actions once")
+ try checkTitlebar(events == ["new", "select", "close"], "Visible controls dispatch their actions once")
events.removeAll()
update(state(rows, active: "swarm-0", enabled: false))
- try checkTitlebar(!contextButton.isEnabled && !newButton.isEnabled &&
- !harnessesButton.isEnabled && !machinesButton.isEnabled && !modelsButton.isEnabled && !storeButton.isEnabled,
+ try checkTitlebar(!contextButton.isEnabled && !newButton.isEnabled,
"Modal state disables status-bar actions")
try original.checkEnabled(false)
contextButton.performClick(nil)
newButton.performClick(nil)
- harnessesButton.performClick(nil)
- machinesButton.performClick(nil)
- modelsButton.performClick(nil)
- storeButton.performClick(nil)
original.clickBothActions()
try checkTitlebar(events.isEmpty, "Disabled controls cannot act behind a modal")
update(["tabs": rows, "activeId": "swarm-0", "enabled": true])
@@ -590,17 +577,6 @@ private extension SwarmTabStrip {
messenger.finishNextReply()
try checkTitlebar(window.firstResponder === window.contentInput && messenger.calls.last?.method == "new",
"New swarm returns keyboard ownership to the workspace")
- for (control, method) in zip([harnessesButton, machinesButton, modelsButton, storeButton],
- ["harnessControls", "machineControls", "modelControls", "store"]) {
- let resting = control.renderedPixels()
- try checkTitlebar(window.makeFirstResponder(control), "A status symbol accepts keyboard focus")
- try checkTitlebar(control.hasKeyboardFocus && control.renderedPixels() != resting,
- "Keyboard focus visibly highlights each status symbol")
- control.performClick(nil)
- messenger.finishNextReply()
- try checkTitlebar(window.firstResponder === window.contentInput && messenger.calls.last?.method == method,
- "Each status action gives keyboard ownership to its Flutter destination")
- }
let current = tabs[0].accessibilityChildren()!.first as! NSButton
window.makeFirstResponder(current)
current.performClick(nil)
@@ -673,7 +649,7 @@ private extension SwarmTabStrip {
try checkTitlebar(moves.isEmpty, "Rejected drag emits no reorder")
}
info.draggingLocation = convert(NSPoint(x: newButton.frame.midX, y: 20), to: nil)
- try rejected("Search is not a tab drop target")
+ try rejected("New Tab is not a tab drop target")
info.draggingLocation = document.convert(NSPoint(x: tabs[0].frame.midX, y: 20), to: nil)
info.draggingSource = SwarmTabButton(id: "drag-3")
try rejected("A foreign tab with a matching ID cannot reorder this strip")
@@ -802,7 +778,10 @@ private extension SwarmTitlebar {
"Command-N and Command-T reach creation and New Tab")
try checkTitlebar(main.defersToInput(event("p", 35, .command)), "Command-P reaches Open Harness")
try checkTitlebar(main.defersToInput(event("p", 35, [.command, .shift])), "Command-Shift-P reaches commands")
- try checkTitlebar(!main.defersToInput(event("o", 31, .command)), "Command-O is no longer claimed")
+ try checkTitlebar(main.defersToInput(event("o", 31, .command)), "Command-O reaches the project picker")
+ try checkTitlebar(!main.defersToInput(event(";", 41, .command)) &&
+ !main.performKeyEquivalent(with: event(";", 41, .command)),
+ "Command-semicolon no longer opens Models")
try checkTitlebar(main.defersToInput(event("i", 34, .command)) &&
!main.performKeyEquivalent(with: event("i", 34, .command)),
"Command-I reaches Flutter exactly once")
@@ -831,7 +810,7 @@ private extension SwarmTitlebar {
}
actionsEnabled = true
// Orchestrator has no default chord now. Exercise an explicit user binding;
- // Cmd-O opens projects; Cmd-P opens commands through the exported default keymap.
+ // Cmd-O opens projects; Cmd-P opens search through the exported default keymap.
let viewerMap = HarnessNativeKeymap(["version": 1, "contexts": [
"workspace": [["keys": ["cmd+y"], "command": "project.orchestrate", "hint": "⌘Y", "repeatable": false]],
"terminal": [], "picker": [], "project": [],