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.

Simplify machine setup and unify the workspace toolbar (#278)

Dee306cbfdd0002
diff --git a/.github/assets/machines/README.md b/.github/assets/machines/README.md
new file mode 100644
index 000000000..e586a7ea8
--- /dev/null
+++ b/.github/assets/machines/README.md
@@ -0,0 +1,22 @@
+# Machines UI review
+
+The screenshot is rendered from the production Machines panel and toolbar with in-memory fixtures, not a signed-in account. The toolbar presents **Machines · Models · Harnesses**, followed by Harness Store. All three marks are monochrome SVGs shared by Flutter and AppKit: muted gray normally, brighter on hover or while open, and white when carrying a notification.
+
+Machines counts unseen online computers ready to connect; optional password setup never adds a badge. Models counts completed model starts/downloads. Opening a panel acknowledges its own badge. Newly added model catalog entries receive a quiet **New** label inside Models instead of a toolbar notification.
+
+To reproduce the visual review from `desktop`:
+
+```sh
+HARNESS_MACHINES_CAPTURE_DIR=/tmp/harness-machines-review flutter test test/machines_panel_test.dart
+```
+
+To check the new feature's executable-line coverage:
+
+```sh
+flutter test --coverage test/machines_panel_test.dart test/machine_resources_test.dart test/machines_manager_test.dart test/boot_flow_widget_test.dart test/toolbar_notices_test.dart
+node tool/check_machines_coverage.mjs
+```
+
+This gate covers the four new files: the panel, SVG widget, resource model, and toolbar notification controller. It does not assert whole-application coverage or replace testing on two physical computers.
+
+For a disposable interactive review, build `tool/machines_preview.dart` and launch its executable with `FLUTTER_TEST=1`. Use `MACHINES_PREVIEW_EMPTY=1` for the first-computer experience, or `MACHINES_PREVIEW_GUEST=1` for sign-in. F6 simulates a newly discovered Mac mini; its fixture password is `123456`. F7 simulates a model becoming ready; F8 adds a model to the catalog. Account edits, links, password operations, model operations, and resource values in this entrypoint remain in memory. Copy and Download use the actual system clipboard/browser. Restore the regular build afterward with `flutter build macos --debug --target lib/main.dart`.
diff --git a/.github/assets/machines/machines-panel.png b/.github/assets/machines/machines-panel.png
new file mode 100644
index 000000000..56dc0ade5
Binary files /dev/null and b/.github/assets/machines/machines-panel.png differ
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index b075a989c..65b5607fc 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -13,6 +13,7 @@ import { stoppedAgents } from './lib/stoppedAgents.js'
import { AgentStopError } from './lib/stopAgentService.js'
import * as mediaPreview from './lib/mediaPreview.js'
import * as gitProject from './lib/gitProject.js'
+import * as machineResources from './lib/machineResources.js'
import * as projectFolder from './lib/projectFolder.js'
import * as projectPreview from './lib/projectPreview.js'
import * as storeCatalog from './dsh/catalog.js'
@@ -834,6 +835,79 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('serves machine stats locally without blocking the next RPC while sampling', async () => {
+ let finish!: (value: machineResources.MachineResources) => void
+ const read = vi.spyOn(machineResources, 'readMachineResources').mockImplementation(
+ () => new Promise(resolve => { finish = resolve }),
+ )
+ const socket = new BackendSocket('token')
+ socket.runtimeModelsProvider = async () => []
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:stats', {
+ sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true,
+ })
+ socket.handleLocalFrame('local:stats', { type: 'machine_resources', payload: { requestId: 'stats' } })
+ socket.handleLocalFrame('local:stats', { type: 'models_list', payload: { requestId: 'models' } })
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'models_list_result', payload: { requestId: 'models', models: [] },
+ }))
+ expect(read).toHaveBeenCalledTimes(1)
+ expect(frames.some(frame => frame.type === 'machine_resources_result')).toBe(false)
+ finish({ cpuPercent: 18, memoryUsedBytes: 10, memoryTotalBytes: 32 })
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'machine_resources_result',
+ payload: { requestId: 'stats', cpuPercent: 18, memoryUsedBytes: 10, memoryTotalBytes: 32 },
+ }))
+ read.mockRejectedValueOnce(new Error('unavailable'))
+ socket.handleLocalFrame('local:stats', { type: 'machine_resources', payload: { requestId: 'retry' } })
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'machine_resources_result', payload: { requestId: 'retry', error: 'UNAVAILABLE' },
+ }))
+ await socket.unregisterLocalClient('local:stats')
+ await socket.stop()
+ })
+
+ it('returns remote machine stats only in a targeted encrypted reply', async () => {
+ const reading = { cpuPercent: 18, memoryUsedBytes: 10, memoryTotalBytes: 32 }
+ vi.spyOn(machineResources, 'readMachineResources').mockResolvedValue(reading)
+ const socket = new BackendSocket('token')
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+ vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({
+ type: 'machine_resources', payload: { requestId: 'stats' },
+ })
+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)
+ const sealed = { type: 'machine_resources_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } }
+ const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue(sealed)
+ ws.message({
+ t: 'down', connId: 'paired',
+ frame: { type: 'machine_resources', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } },
+ })
+ await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('paired', 'machine_resources_result', 'stats', reading))
+ expect(parseSent(ws)).toContainEqual(expect.objectContaining({ targetConnId: 'paired', frame: sealed }))
+ expect(ws.sent.some(frame => frame.includes('memoryUsedBytes'))).toBe(false)
+ await socket.stop()
+ })
+
+ it('rejects unpaired plaintext stats requests before sampling the machine', async () => {
+ const read = vi.spyOn(machineResources, 'readMachineResources')
+ const socket = new BackendSocket('token')
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+ ws.message({
+ t: 'down', connId: 'unpaired',
+ frame: { type: 'machine_resources', payload: { requestId: 'stats' } },
+ })
+ await vi.waitFor(() => expect(parseSent(ws)).toContainEqual(expect.objectContaining({
+ targetConnId: 'unpaired',
+ frame: { type: 'machine_resources_result', payload: { requestId: 'stats', error: 'E2EE_REQUIRED' } },
+ })))
+ expect(read).not.toHaveBeenCalled()
+ await socket.stop()
+ })
+
it('dsh_remove uninstalls through the daemon and refuses a malformed id', async () => {
const socket = new BackendSocket('token')
const frames: Array<Record<string, unknown>> = []
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 0f9d75caa..6fc719c59 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -40,6 +40,7 @@ import { deriveHarnessGridName } from './lib/gridDerive.js'
import { AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'
import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'
import { probeEngines } from './lib/engineProbe.js'
+import { readMachineResources } from './lib/machineResources.js'
import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from './lib/projectFolder.js'
@@ -1527,6 +1528,12 @@ export class BackendSocket {
try {
switch (type) {
+ case 'machine_resources':
+ // Sampling CPU must not hold up typing or other machine requests.
+ void readMachineResources()
+ .then(resources => reply(type, requestId, { ...resources }))
+ .catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))
+ return
case 'grid_fleet_models_list':
case 'grid_fleet_model_start':
case 'grid_fleet_model_stop': {
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index a35cf8d36..ab9fa78f0 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -14,7 +14,9 @@ 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'])
const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))
+const MACHINE_REQUESTS = new Set(['git_project_info', 'git_pull_request', 'machine_resources'])
+const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
export const encryptDownFrame = (type: string): boolean =>
- isEncryptedDownType(type) || (type === 'git_project_info' || type === 'git_pull_request') || FLEET_REQUESTS.has(type) || SHARE_REQUEST_TYPES.has(type) || VIEWER_DOWN_TYPES.has(type)
+ isEncryptedDownType(type) || MACHINE_REQUESTS.has(type) || FLEET_REQUESTS.has(type) || SHARE_REQUEST_TYPES.has(type) || VIEWER_DOWN_TYPES.has(type)
export const encryptRpcResult = (type: string): boolean =>
- ENCRYPTED_RPC_RESULT_TYPES.has(type) || (type === 'git_project_info_result' || type === 'git_pull_request_result') || FLEET_RESULTS.has(type) || SHARE_RESULT_TYPES.has(type)
+ ENCRYPTED_RPC_RESULT_TYPES.has(type) || MACHINE_RESULTS.has(type) || FLEET_RESULTS.has(type) || SHARE_RESULT_TYPES.has(type)
diff --git a/cli/src/lib/machineResources.spec.ts b/cli/src/lib/machineResources.spec.ts
new file mode 100644
index 000000000..32b3de722
--- /dev/null
+++ b/cli/src/lib/machineResources.spec.ts
@@ -0,0 +1,124 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cpus, freemem, totalmem } from 'node:os'
+import { readFile } from 'node:fs/promises'
+import { setTimeout as delay } from 'node:timers/promises'
+import { createMachineResourcesReader } from './machineResources.js'
+import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'
+
+vi.mock('node:os', () => ({ cpus: vi.fn(), freemem: vi.fn(), totalmem: vi.fn() }))
+vi.mock('node:fs/promises', () => ({ readFile: vi.fn() }))
+vi.mock('node:timers/promises', () => ({ setTimeout: vi.fn(async () => {}) }))
+
+describe('OS resource sampling', () => {
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', platform)
+ vi.clearAllMocks()
+ })
+
+ for (const system of ['darwin', 'linux']) {
+ for (const proc of ['available', 'missing', 'denied']) {
+ it(`${system}: ${proc} available-memory information`, async () => {
+ Object.defineProperty(process, 'platform', { ...platform, value: system })
+ vi.mocked(totalmem).mockReturnValue(8 * 1024 ** 3)
+ vi.mocked(freemem).mockReturnValue(1024 ** 3)
+ vi.mocked(readFile).mockReset()
+ if (proc === 'denied') vi.mocked(readFile).mockRejectedValue(new Error('EACCES'))
+ else vi.mocked(readFile).mockResolvedValue(proc === 'available'
+ ? 'MemFree: 1048576 kB\nMemAvailable: 4194304 kB\n' : 'MemFree: 1048576 kB\n')
+ const cpu = (idle: number, user: number) => ({
+ model: 'fixture', speed: 3200, times: { user, idle, nice: 0, sys: 0, irq: 0 },
+ })
+ vi.mocked(cpus).mockReset()
+ vi.mocked(cpus).mockReturnValueOnce([cpu(100, 50), cpu(100, 50)])
+ .mockReturnValue([cpu(200, 150), cpu(200, 150)])
+ expect(await createMachineResourcesReader()()).toEqual({
+ cpuPercent: 50,
+ memoryUsedBytes: (system === 'linux' && proc === 'available' ? 4 : 7) * 1024 ** 3,
+ memoryTotalBytes: 8 * 1024 ** 3,
+ })
+ expect(delay).toHaveBeenCalledWith(200)
+ expect(readFile).toHaveBeenCalledTimes(system === 'linux' ? 1 : 0)
+ })
+ }
+ }
+})
+
+function fixture() {
+ return {
+ cpuTimes: vi.fn()
+ .mockReturnValueOnce({ idle: 100, total: 200 })
+ .mockReturnValue({ idle: 250, total: 400 }),
+ memory: vi.fn(async () => ({ total: 32 * 1024 ** 3, available: 12 * 1024 ** 3 })),
+ wait: vi.fn(async () => {}),
+ now: vi.fn(() => 1000),
+ }
+}
+
+describe('on-demand machine resources', () => {
+ it('measures CPU over a sample interval and memory in bytes', async () => {
+ expect(await createMachineResourcesReader(fixture())()).toEqual({
+ cpuPercent: 25,
+ memoryUsedBytes: 20 * 1024 ** 3,
+ memoryTotalBytes: 32 * 1024 ** 3,
+ })
+ })
+
+ it.each([
+ { idle: 100, total: 200 }, // No elapsed CPU time.
+ { idle: 10, total: 20 }, // Counters reset or a CPU disappeared.
+ { idle: 99, total: 400 },
+ { idle: 400, total: 400 },
+ { idle: NaN, total: Infinity },
+ ])('does not turn invalid CPU counters into fake zero usage: %o', async after => {
+ const deps = fixture()
+ deps.cpuTimes.mockReturnValue(after)
+ expect(await createMachineResourcesReader(deps)()).toMatchObject({ cpuPercent: null })
+ })
+
+ it.each([
+ { total: 0, available: 0 },
+ { total: 100, available: -1 },
+ { total: 100, available: 101 },
+ { total: NaN, available: 1 },
+ { total: 100, available: Infinity },
+ ])('leaves invalid memory readings unknown: %o', async memory => {
+ const deps = fixture()
+ deps.memory.mockResolvedValue(memory)
+ expect(await createMachineResourcesReader(deps)()).toEqual({
+ cpuPercent: 25, memoryUsedBytes: null, memoryTotalBytes: null,
+ })
+ })
+
+ it('coalesces concurrent requests, then reuses only fresh samples', async () => {
+ const deps = fixture()
+ let complete!: () => void
+ deps.wait.mockImplementationOnce(() => new Promise<void>(resolve => { complete = resolve }))
+ const read = createMachineResourcesReader(deps)
+ const first = read()
+ expect(read()).toBe(first)
+ expect(deps.wait).toHaveBeenCalledTimes(1)
+ complete()
+ const reading = await first
+ deps.now.mockReturnValue(2999)
+ expect(await read()).toBe(reading)
+ expect(deps.wait).toHaveBeenCalledTimes(1)
+ deps.now.mockReturnValue(3000)
+ await read()
+ expect(deps.wait).toHaveBeenCalledTimes(2)
+ })
+
+ it('allows retry after a failed sample', async () => {
+ const deps = fixture()
+ deps.memory.mockRejectedValueOnce(new Error('unavailable'))
+ const read = createMachineResourcesReader(deps)
+ await expect(read()).rejects.toThrow('unavailable')
+ await expect(read()).resolves.toMatchObject({ memoryTotalBytes: 32 * 1024 ** 3 })
+ expect(deps.wait).toHaveBeenCalledTimes(2)
+ })
+
+ it('encrypts both the request and response between machines', () => {
+ expect(encryptDownFrame('machine_resources')).toBe(true)
+ expect(encryptRpcResult('machine_resources_result')).toBe(true)
+ })
+})
diff --git a/cli/src/lib/machineResources.ts b/cli/src/lib/machineResources.ts
new file mode 100644
index 000000000..99f36b83f
--- /dev/null
+++ b/cli/src/lib/machineResources.ts
@@ -0,0 +1,67 @@
+import { cpus, freemem, totalmem } from 'node:os'
+import { readFile } from 'node:fs/promises'
+import { setTimeout as delay } from 'node:timers/promises'
+
+export interface MachineResources {
+ cpuPercent: number | null
+ memoryUsedBytes: number | null
+ memoryTotalBytes: number | null
+}
+
+type CpuTimes = { idle: number; total: number }
+function cpuTimes(): CpuTimes {
+ return cpus().reduce((sum, cpu) => ({
+ idle: sum.idle + cpu.times.idle,
+ total: sum.total + Object.values(cpu.times).reduce((a, b) => a + b, 0),
+ }), { idle: 0, total: 0 })
+}
+
+async function memory(): Promise<{ total: number; available: number }> {
+ const total = totalmem()
+ if (process.platform === 'linux') {
+ try {
+ // Reclaimable cache is available for work; MemFree alone counts it as used.
+ const info = await readFile('/proc/meminfo', 'utf8')
+ const available = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(info)?.[1]
+ if (available != null) return { total, available: Number(available) * 1024 }
+ } catch { /* Older/restricted hosts still have the portable OS reading. */ }
+ }
+ return { total, available: freemem() }
+}
+
+/** Demand-driven system readings. Concurrent panels share one sample, with no
+ * background timer or shell process while nobody is asking for machine stats. */
+export function createMachineResourcesReader(deps = {
+ cpuTimes, memory, wait: () => delay(200), now: Date.now,
+}): () => Promise<MachineResources> {
+ let cached: { at: number; value: MachineResources } | undefined
+ let pending: Promise<MachineResources> | undefined
+ async function sample(): Promise<MachineResources> {
+ const before = deps.cpuTimes()
+ await deps.wait()
+ const after = deps.cpuTimes()
+ const elapsed = after.total - before.total
+ const idle = after.idle - before.idle
+ const cpuPercent = Number.isFinite(elapsed) && Number.isFinite(idle)
+ && elapsed > 0 && idle >= 0 && idle <= elapsed
+ ? Math.round((1 - idle / elapsed) * 1000) / 10 : null
+ const mem = await deps.memory()
+ const validMemory = Number.isFinite(mem.total) && mem.total > 0
+ && Number.isFinite(mem.available) && mem.available >= 0 && mem.available <= mem.total
+ const value = {
+ cpuPercent,
+ memoryUsedBytes: validMemory ? mem.total - mem.available : null,
+ memoryTotalBytes: validMemory ? mem.total : null,
+ }
+ cached = { at: deps.now(), value }
+ return value
+ }
+ return () => {
+ if (pending) return pending
+ if (cached && deps.now() - cached.at < 2000) return Promise.resolve(cached.value)
+ pending = sample().finally(() => { pending = undefined })
+ return pending
+ }
+}
+
+export const readMachineResources = createMachineResourcesReader()
diff --git a/desktop/assets/harnesses.svg b/desktop/assets/harnesses.svg
new file mode 100644
index 000000000..9a8233e09
--- /dev/null
+++ b/desktop/assets/harnesses.svg
@@ -0,0 +1,8 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
+ <title>Harnesses</title>
+ <path d="M12 7V3M10 3h4M4 12H2v4h2m16-4h2v4h-2"/>
+ <rect x="4" y="7" width="16" height="13" rx="3"/>
+ <circle cx="8.5" cy="12" r="1" fill="#fff" stroke="none"/>
+ <circle cx="15.5" cy="12" r="1" fill="#fff" stroke="none"/>
+ <path d="M9 16.5h6"/>
+</svg>
diff --git a/desktop/assets/machines.svg b/desktop/assets/machines.svg
new file mode 100644
index 000000000..37e946168
--- /dev/null
+++ b/desktop/assets/machines.svg
@@ -0,0 +1,5 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
+ <title>Machines</title>
+ <rect x="3" y="4" width="18" height="13" rx="1.8"/>
+ <path d="M12 17v4M8 21h8"/>
+</svg>
diff --git a/desktop/assets/models.svg b/desktop/assets/models.svg
index d7aa64a23..619d4bf5e 100644
--- a/desktop/assets/models.svg
+++ b/desktop/assets/models.svg
@@ -1,37 +1,5 @@
-<svg version="1.1"
- xmlns="http://www.w3.org/2000/svg"
- width="256"
- height="256"
- viewBox="0 0 24 24"
- fill="none"
- stroke="#B5A0FF"
- stroke-width="1.8"
- stroke-linecap="round"
- stroke-linejoin="round"
->
- <!-- Lucide Brain: https://lucide.dev/icons/brain
-ISC License
-
-Copyright (c) 2026 Lucide Icons and Contributors
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted, provided that the above
-copyright notice and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- -->
- <path d="M12 18V5" />
- <path d="M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4" />
- <path d="M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5" />
- <path d="M17.997 5.125a4 4 0 0 1 2.526 5.77" />
- <path d="M18 18a4 4 0 0 0 2-7.464" />
- <path d="M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517" />
- <path d="M6 18a4 4 0 0 1-2-7.464" />
- <path d="M6.003 5.125a4 4 0 0 0-2.526 5.77" />
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
+ <title>Models</title>
+ <path d="M12 5.3C12 3.6 10.7 2.5 9.2 2.5 7.6 2.5 6.3 3.6 6.1 5.1 4.3 5.3 3 6.7 3 8.4c0 .7.2 1.3.6 1.9C2.6 11 2 12.1 2 13.3c0 1.8 1.2 3.2 2.8 3.5C4.7 19.2 6.3 21 8.5 21c2 0 3.5-1.4 3.5-3.3 0 1.9 1.5 3.3 3.5 3.3 2.2 0 3.8-1.8 3.7-4.2 1.6-.3 2.8-1.7 2.8-3.5 0-1.2-.6-2.3-1.6-3 .4-.6.6-1.2.6-1.9 0-1.7-1.3-3.1-3.1-3.3-.2-1.5-1.5-2.6-3.1-2.6-1.5 0-2.8 1.1-2.8 2.8Z"/>
+ <path d="M12 5.3v12.4M6.1 5.1c0 1.3.6 2.3 1.7 2.8m10.1-2.8c0 1.3-.6 2.3-1.7 2.8M3.6 10.3c1.3-.5 2.6-.3 3.5.6m13.3-.6c-1.3-.5-2.6-.3-3.5.6M4.8 16.8c1.4.1 2.4-.6 2.9-1.7m11.5 1.7c-1.4.1-2.4-.6-2.9-1.7"/>
</svg>
diff --git a/desktop/integration_test/native_workspace_e2e_test.dart b/desktop/integration_test/native_workspace_e2e_test.dart
index 2d713a0df..c87f86d12 100644
--- a/desktop/integration_test/native_workspace_e2e_test.dart
+++ b/desktop/integration_test/native_workspace_e2e_test.dart
@@ -49,7 +49,6 @@ import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/widgets/new_harness_box.dart';
import 'package:harness/widgets/environment_setup_screen.dart';
-import 'package:harness/widgets/link_machine_screen.dart';
import 'package:harness/widgets/terminal_find_bar.dart';
import 'package:harness/ws/ws_conn.dart';
@@ -1672,6 +1671,7 @@ void main() {
authSession: AuthSession(),
configStore: null,
peerLinks: links,
+ cliLink: PasswordCli(),
)..hasNavigationRail = false;
seedMixedAgents(app);
final input = <TerminalBinaryFrame>[];
@@ -1693,18 +1693,15 @@ void main() {
),
);
await tester.pump(const Duration(milliseconds: 200));
- final field = find.byKey(const Key('remote-password-connect-field'));
- // The initial workspace schedules this dialog after its first frame;
- // allow the new route's autofocus request to settle as well.
+ final field = find.byKey(const ValueKey('connect-password-studio-input'));
await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
await tester.enterText(field, 'fixture password');
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pump();
expect(links.requests, ['studio']);
expect(tester.widget<TextField>(field).readOnly, isTrue);
- expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
-
links.replies.first.complete(
const CliLinkConnectResult(error: 'Incorrect password'),
);
@@ -1715,30 +1712,14 @@ void main() {
await key(tester, LogicalKeyboardKey.enter);
expect(links.requests, ['studio', 'studio']);
await key(tester, LogicalKeyboardKey.escape);
- await tester.pump(const Duration(milliseconds: 80));
- expect(find.byType(LinkMachineScreen), findsNothing);
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
expect(app.focusedPane, same(pane));
expect(input, isEmpty);
await key(tester, LogicalKeyboardKey.arrowLeft);
- await tester.pump(const Duration(milliseconds: 20));
expect(input.single.bytes, [27, 91, 68]);
input.clear();
-
- // Use the real command and machine chooser to revisit the pending link.
- await key(tester, LogicalKeyboardKey.keyP, cmd: true);
- await tester.enterText(
- find.byKey(const ValueKey('swarm-search-input')),
- '> link machine',
- );
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- final machineSearch = find.byKey(const Key('link-machine-search'));
- expect(
- tester.widget<TextField>(machineSearch).focusNode!.hasFocus,
- isTrue,
- );
- await tester.enterText(machineSearch, 'office');
- await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.keyM, cmd: true);
await tester.pumpAndSettle();
expect(tester.widget<TextField>(field).readOnly, isTrue);
expect(tester.widget<TextField>(field).controller!.text, isEmpty);
@@ -1747,23 +1728,13 @@ void main() {
links.replies.last.complete(
const CliLinkConnectResult(linkedMachineId: 'studio'),
);
- await tester.pump(const Duration(milliseconds: 80));
- await tester.pump();
- expect(find.byType(LinkMachineScreen), findsNothing);
+ await tester.pumpAndSettle();
expect(app.machineStates['studio']!.needsLink, isFalse);
+ expect(field, findsNothing);
expect(pane.session, same(session));
expect(input, isEmpty);
- await tester.pumpAndSettle();
- expect(
- tester.widget<TextField>(machineSearch).controller!.text,
- 'office',
- );
- expect(
- tester.widget<TextField>(machineSearch).focusNode!.hasFocus,
- isTrue,
- );
await key(tester, LogicalKeyboardKey.escape);
- await tester.pump(const Duration(milliseconds: 80));
+ await tester.pumpAndSettle();
await key(tester, LogicalKeyboardKey.arrowRight);
await tester.pump(const Duration(milliseconds: 20));
expect(input.single.bytes, [27, 91, 67]);
@@ -1785,6 +1756,7 @@ void main() {
cliLink: cli,
)..hasNavigationRail = false;
seedMixedAgents(app);
+ app.machineStates['m']!.localOnly = true;
final input = <TerminalBinaryFrame>[];
final session = terminal('a0', input);
final pane = app.adoptSessionForTest(session);
@@ -1802,46 +1774,33 @@ void main() {
),
);
await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.keyP, cmd: true);
- await tester.enterText(
- find.byKey(const ValueKey('swarm-search-input')),
- '> link machine',
- );
- await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.keyM, cmd: true);
await tester.pumpAndSettle();
- final search = find.byKey(const Key('link-machine-search'));
- await tester.enterText(search, 'password');
- await key(tester, LogicalKeyboardKey.enter);
+ await tester.tap(find.text('Set password'));
await tester.pumpAndSettle();
- final password = find.byKey(const Key('remote-password-field'));
- final confirm = find.byKey(const Key('remote-password-confirm-field'));
+ final password = find.byKey(const ValueKey('make-available-password'));
expect(tester.widget<TextField>(password).focusNode!.hasFocus, isTrue);
await tester.enterText(password, 'fixture password');
- await tester.testTextInput.receiveAction(TextInputAction.next);
- await tester.pump();
- expect(tester.widget<TextField>(confirm).focusNode!.hasFocus, isTrue);
- await tester.enterText(confirm, 'fixture password');
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pumpAndSettle();
expect(cli.passwords, ['fixture password']);
- expect(tester.widget<TextField>(confirm).focusNode!.hasFocus, isTrue);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(tester.widget<TextField>(search).controller!.text, 'password');
- await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.keyM, cmd: true);
await tester.pumpAndSettle();
- expect(find.text('Setting password…'), findsOneWidget);
+ expect(find.text('Saving password…'), findsOneWidget);
expect(cli.passwords, hasLength(1));
cli.setReply!.complete(cli.setResult);
await tester.pumpAndSettle();
- expect(find.text('Remote password is set'), findsOneWidget);
- await key(tester, LogicalKeyboardKey.enter);
+ expect(find.text('Change password'), findsOneWidget);
+ await tester.tap(find.text('Change password'));
await tester.pumpAndSettle();
expect(tester.widget<TextField>(password).focusNode!.hasFocus, isTrue);
expect(tester.widget<TextField>(password).controller!.text, isEmpty);
- await key(tester, LogicalKeyboardKey.escape); // Cancel editing.
- await key(tester, LogicalKeyboardKey.escape); // Return to chooser.
- await key(tester, LogicalKeyboardKey.escape); // Return to terminal.
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(find.text('Change password'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(app.focusedPane, same(pane));
expect(pane.session, same(session));
@@ -1855,100 +1814,89 @@ void main() {
},
);
- testWidgets(
- 'native machine management keeps query, pending edits and terminal ownership',
- (tester) async {
- final api = MachineApi()
- ..renameReply = Completer<String?>()
- ..deleteReply = Completer<void>();
- final app = createApp()..api = api;
- seedMixedAgents(app);
- final input = <TerminalBinaryFrame>[];
- final session = terminal('a0', input);
- final pane = app.adoptSessionForTest(session);
- final projects = SwarmProjectStore();
- addTearDown(app.dispose);
- addTearDown(projects.dispose);
- await tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: SwarmScreen(
- notifier: app,
- nativeTabs: true,
- projectStore: projects,
- ),
+ testWidgets('native Machines keeps pending edits and terminal ownership', (
+ tester,
+ ) async {
+ final api = MachineApi()
+ ..renameReply = Completer<String?>()
+ ..deleteReply = Completer<void>();
+ final app = createApp()..api = api;
+ seedMixedAgents(app);
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ final pane = app.adoptSessionForTest(session);
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.keyM, cmd: true);
+ await tester.pumpAndSettle();
+ Future<void> action(String label) async {
+ final options = find.byTooltip(
+ 'Options for ${app.stateOf('studio')!.machine.displayName}',
);
+ await tester.ensureVisible(options);
+ await tester.tap(options);
await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.keyP, cmd: true);
- await tester.enterText(
- find.byKey(const ValueKey('swarm-search-input')),
- '> machines manager',
- );
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- final search = find.byKey(const Key('machines-manager-search'));
- expect(tester.widget<TextField>(search).focusNode!.hasFocus, isTrue);
- tester.testTextInput.enterText('office');
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- // Type through the existing native editing connection after the mode switch.
- tester.testTextInput.enterText('rename');
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- final rename = find.byKey(const Key('machine-rename-input'));
- expect(tester.widget<TextField>(rename).focusNode!.hasFocus, isTrue);
- tester.testTextInput.enterText('Office builder');
- await tester.testTextInput.receiveAction(TextInputAction.done);
- await tester.pumpAndSettle();
- expect(api.renames, [('studio', 'Office builder')]);
- expect(tester.widget<TextField>(rename).focusNode!.hasFocus, isTrue);
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- expect(tester.widget<TextField>(search).controller!.text, 'rename');
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(tester.widget<TextField>(rename).readOnly, isTrue);
- expect(api.renames, hasLength(1));
- api.renameReply!.complete('Office builder');
- await tester.pumpAndSettle();
- expect(find.text('Office builder'), findsOneWidget);
- tester.testTextInput.enterText('delete');
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.enter); // Cancel is the default.
- await tester.pumpAndSettle();
- expect(api.deletes, isEmpty);
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.tab);
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(api.deletes, ['studio']);
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.enter);
+ await tester.tap(find.text(label));
await tester.pumpAndSettle();
- expect(find.text('Deleting machine…'), findsOneWidget);
- expect(api.deletes, hasLength(1));
- api.deleteReply!.complete();
- await tester.pumpAndSettle();
- expect(app.stateOf('studio'), isNull);
- expect(find.text('Machines Manager'), findsOneWidget);
- expect(tester.widget<TextField>(search).controller!.text, 'office');
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- expect(app.focusedPane, same(pane));
- expect(pane.session, same(session));
- expect(input, isEmpty);
- await key(tester, LogicalKeyboardKey.arrowLeft);
- await tester.pump(const Duration(milliseconds: 20));
- expect(input.single.bytes, [27, 91, 68]);
- expect(tester.takeException(), isNull);
- await tester.pumpWidget(const SizedBox());
- await tester.pump(const Duration(milliseconds: 100));
- },
- );
+ }
+
+ await action('Rename');
+ final rename = find.byKey(const Key('machine-rename-input'));
+ expect(tester.widget<TextField>(rename).focusNode!.hasFocus, isTrue);
+ tester.testTextInput.enterText('Office builder');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(api.renames, [('studio', 'Office builder')]);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ await action('Rename');
+ expect(tester.widget<TextField>(rename).readOnly, isTrue);
+ expect(api.renames, hasLength(1));
+ api.renameReply!.complete('Office builder');
+ await tester.pumpAndSettle();
+ expect(find.text('Office builder'), findsOneWidget);
+ await action('Remove from account…');
+ await key(tester, LogicalKeyboardKey.enter); // Cancel is the default.
+ await tester.pumpAndSettle();
+ expect(api.deletes, isEmpty);
+ await action('Remove from account…');
+ await tester.tap(find.byKey(const Key('machine-delete-confirm')));
+ await tester.pumpAndSettle();
+ expect(api.deletes, ['studio']);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await action('Remove from account…');
+ expect(find.text('Deleting machine…'), findsOneWidget);
+ expect(api.deletes, hasLength(1));
+ api.deleteReply!.complete();
+ await tester.pumpAndSettle();
+ expect(app.stateOf('studio'), isNull);
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(app.focusedPane, same(pane));
+ expect(pane.session, same(session));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 68]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ });
testWidgets(
'native rename prompts keep pending work and return terminal input',
(tester) async {
diff --git a/desktop/lib/core/machine_resources.dart b/desktop/lib/core/machine_resources.dart
new file mode 100644
index 000000000..8514c31bf
--- /dev/null
+++ b/desktop/lib/core/machine_resources.dart
@@ -0,0 +1,30 @@
+/// Optional host readings from a linked machine, never inferred from harness activity.
+class MachineResources {
+ const MachineResources({
+ this.cpuPercent,
+ this.memoryUsedBytes,
+ this.memoryTotalBytes,
+ });
+
+ final double? cpuPercent, memoryUsedBytes, memoryTotalBytes;
+
+ factory MachineResources.fromJson(Map<String, dynamic> json) {
+ double? number(String key) {
+ final value = json[key];
+ return value is num && value.isFinite && value >= 0
+ ? value.toDouble()
+ : null;
+ }
+
+ final cpu = number('cpuPercent');
+ final used = number('memoryUsedBytes');
+ final total = number('memoryTotalBytes');
+ final memoryValid =
+ used != null && total != null && total > 0 && used <= total;
+ return MachineResources(
+ cpuPercent: cpu != null && cpu <= 100 ? cpu : null,
+ memoryUsedBytes: memoryValid ? used : null,
+ memoryTotalBytes: memoryValid ? total : null,
+ );
+ }
+}
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 55eb3cccc..e790e5e73 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -395,7 +395,7 @@ class Agent {
(engine == 'claude' || engine == 'codex') &&
sessionId?.isNotEmpty == true;
- /// Whether Harness Monitor may pause this harness and bring it back.
+ /// Whether the Harnesses panel may pause this harness and bring it back.
///
/// Every engine can, and the daemon says so per engine through [resumeMode]
/// — a client that kept its own allow-list is how the two drifted, with
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index 62b637dd2..ff545a742 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -17,6 +17,7 @@ const Set<String> encryptedDownTypes = {
'grid_fleet_capabilities',
'grid_fleet_run',
'grid_fleet_cancel',
+ 'machine_resources',
'grid_fleet_models_list',
'grid_fleet_model_start',
'grid_fleet_model_stop',
diff --git a/desktop/lib/models/models_panel.dart b/desktop/lib/models/models_panel.dart
index 0b52c43de..dff258195 100644
--- a/desktop/lib/models/models_panel.dart
+++ b/desktop/lib/models/models_panel.dart
@@ -18,10 +18,12 @@ class ModelsPanel extends StatefulWidget {
required this.subscriptions,
required this.onClose,
required this.onManage,
+ this.newModelIds = const {},
});
final ModelManagerController controller;
final ModelsMenuController subscriptions;
final VoidCallback onClose, onManage;
+ final Set<String> newModelIds;
@override
State<ModelsPanel> createState() => _ModelsPanelState();
}
@@ -347,7 +349,7 @@ class _ModelsPanelState extends State<ModelsPanel> {
foregroundColor: AppPalette.textSecondary,
textStyle: AppType.monoMeta(),
),
- child: const Text('Model Manager'),
+ child: const Text('Manage models'),
),
],
),
@@ -424,17 +426,32 @@ class _ModelsPanelState extends State<ModelsPanel> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Tooltip(
- message: model.name,
- child: Text(
- model.name,
- style: AppType.label(
- color: AppPalette.textPrimary,
- height: 1.3,
+ Row(
+ children: [
+ Flexible(
+ child: Tooltip(
+ message: model.name,
+ child: Text(
+ model.name,
+ style: AppType.label(
+ color: AppPalette.textPrimary,
+ height: 1.3,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
+ if (widget.newModelIds.contains(model.id)) ...[
+ const SizedBox(width: 8),
+ Text(
+ 'New',
+ style: AppType.monoMeta(
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ],
+ ],
),
const SizedBox(height: 6),
Text(
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index c510cfdd6..16bbfccfe 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -15,7 +15,6 @@ import '../core/project_folder.dart';
import '../core/test_run.dart';
import '../logging/debug_surface.dart';
import '../models/models_panel.dart';
-import '../models/model_mark.dart';
import '../settings/settings_screen.dart';
import '../settings/settings_section.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -47,13 +46,14 @@ import '../widgets/engine_identity.dart';
import '../store/store_mark.dart';
import '../store/store_screen.dart';
import '../widgets/harness_start_page.dart';
-import '../widgets/link_machine_screen.dart';
+import '../widgets/machines_panel.dart';
+import '../widgets/toolbar_icon.dart';
+import '../state/toolbar_notices.dart';
import '../widgets/machine_actions.dart';
import '../widgets/rename_agent_dialog.dart';
import '../widgets/delete_agent_dialog.dart';
import '../widgets/fork_agent_dialog.dart';
import '../widgets/restart_agent_action.dart';
-import '../widgets/machines_manager.dart';
import '../widgets/new_agent_dialog.dart';
import '../widgets/box_chrome.dart';
import '../widgets/new_harness_box.dart';
@@ -143,6 +143,8 @@ class _SwarmScreenState extends State<SwarmScreen>
StreamSubscription<void>? _modelsRequests;
final _shellFocus = FocusNode(debugLabel: 'Swarm shell');
final _sessionsButton = GlobalKey();
+ MachinesPanelHandle? _machinesPanel;
+ final _toolbarNotices = ToolbarNotices();
OverlayEntry? _sessionsOverlay;
VoidCallback? _unregisterSessions;
OverlayEntry? _modelsOverlay;
@@ -240,6 +242,9 @@ class _SwarmScreenState extends State<SwarmScreen>
// Its own notifier, so marking one agent does not rebuild the workspace —
// which means the badge has to ask for its own redraw.
app.agentUnread.addListener(_unreadChanged);
+ app.addListener(_syncToolbarNotices);
+ _toolbarNotices.addListener(_toolbarNoticesChanged);
+ _syncToolbarNotices();
unawaited(
_learning.load().then((_) {
if (mounted) _observeLearning();
@@ -307,6 +312,10 @@ class _SwarmScreenState extends State<SwarmScreen>
@override
void dispose() {
+ app.removeListener(_syncToolbarNotices);
+ _toolbarNotices.removeListener(_toolbarNoticesChanged);
+ _toolbarNotices.dispose();
+ _machinesPanel?.close(restoreFocus: false);
app.modelManager.removeListener(_modelManagerChanged);
app.modelManager.setPanelVisible(false);
_modelsRequests?.cancel();
@@ -408,8 +417,11 @@ class _SwarmScreenState extends State<SwarmScreen>
mounted && _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen;
void _runShortcut(String id) {
- if (_sessionsOverlay != null) _closeSessions();
- if (_modelsOverlay != null) _closeModels();
+ if (id != 'machines.list' && id != 'machine.link') {
+ _machinesPanel?.close(restoreFocus: false);
+ }
+ if (_sessionsOverlay != null) _closeSessions(restoreFocus: false);
+ if (_modelsOverlay != null) _closeModels(restoreFocus: false);
if (id != 'navigation.command_bar') _closeCommandBar();
if (id == 'agent.new' && _search != null) {
final target = _search!.targetId;
@@ -542,6 +554,45 @@ class _SwarmScreenState extends State<SwarmScreen>
/// still separates the two — its "Needs input" tab is exactly [_attention].
int get _unread => app.agentUnread.count;
+ void _syncToolbarNotices() {
+ final local = app.localMachineState?.machine.machineId;
+ final models = app.modelManager;
+ final profile = app.currentUser;
+ final scope = app.isGuest
+ ? 'local:$local'
+ : 'account:${profile?.id ?? profile?.email ?? local}';
+ _toolbarNotices.sync(
+ scope: scope,
+ machines: {
+ if (!app.isGuest)
+ for (final machine in app.machineStates.values)
+ if (!machine.isLocalMachine &&
+ !machine.machine.isShared &&
+ machine.needsLink &&
+ machine.nodeOnline == true)
+ machine.machine.machineId,
+ },
+ readyModels: {
+ for (final model in models.localModels)
+ if (local != null &&
+ model.running &&
+ model.operation?.started == true)
+ '$local/${model.operation!.id}',
+ },
+ catalog: models.localModels.map((model) => model.id).toSet(),
+ catalogLoaded: models.loaded,
+ machinesVisible: _machinesPanel != null,
+ modelsVisible: _modelsOverlay != null,
+ );
+ }
+
+ void _toolbarNoticesChanged() {
+ if (!mounted) return;
+ _modelsOverlay?.markNeedsBuild();
+ if (_native) _syncNative();
+ setState(() {});
+ }
+
void _unreadChanged() {
if (!mounted) return;
setState(() {});
@@ -580,6 +631,7 @@ class _SwarmScreenState extends State<SwarmScreen>
}
void _paletteChanged() {
+ _machinesPanel?.rebuild();
_searchOverlay?.markNeedsBuild();
if (_native) _syncNative();
}
@@ -649,6 +701,9 @@ class _SwarmScreenState extends State<SwarmScreen>
// key it does not know.
'unread': _unread,
'sessionsOpen': _sessionsOverlay != null,
+ 'machinesOpen': _machinesPanel != null,
+ 'machineNotices': _toolbarNotices.machineCount,
+ 'modelNotices': _toolbarNotices.modelCount,
'modelsOpen': _modelsOverlay != null,
'localModelReady': app.modelManager.readyModel != null,
'runningSessions': harnessSessions(app)
@@ -934,6 +989,11 @@ class _SwarmScreenState extends State<SwarmScreen>
await WidgetsBinding.instance.endOfFrame;
return;
}
+ if (call.method == 'machineList' || call.method == 'linkMachine') {
+ unawaited(_openMachines());
+ await WidgetsBinding.instance.endOfFrame;
+ return;
+ }
if (call.method == 'models') {
_toggleModels();
await WidgetsBinding.instance.endOfFrame;
@@ -1073,18 +1133,8 @@ class _SwarmScreenState extends State<SwarmScreen>
if (app.focusedPaneId != null) app.togglePinPane(app.focusedPaneId!);
case 'addProject':
await _addProject();
- case 'linkMachine':
- await _dialog(() => showSwarmLinkDialog(context, app, keymap: _keymap));
case 'manageMachines':
await _manageMachines();
- // BRIDGE, until the Machines menu goes: the old list, so nothing is lost
- // between this release and that one. When the menu is removed, delete
- // this case, `machines.list` below, machines_manager.dart and its test,
- // and the `machineList` action in SwarmTitlebar.swift + keymap_commands.
- case 'machineList':
- unawaited(
- _dialog(() => showMachinesManager(context, app, keymap: _keymap)),
- );
case 'refreshMachines':
unawaited(app.retryMachines());
case 'machineDestination':
@@ -1350,6 +1400,63 @@ class _SwarmScreenState extends State<SwarmScreen>
}
}
+ Future<void> _openMachines({String? initialMachineId}) async {
+ if (_machinesPanel case final panel?) {
+ panel.close();
+ return;
+ }
+ if (!_shortcutsEnabled || _newHarness?.requestDismiss() == false) return;
+ _closeNewHarness(restoreFocus: false);
+ _closeSearch(restoreFocus: false);
+ _closeCommandBar(restoreFocus: false);
+ dismissTransientMenus();
+ _preparePaneFocus();
+ final panel = openMachinesPanel(
+ context,
+ app,
+ keymap: _keymap,
+ initialMachineId: initialMachineId,
+ toolbarHeight: _native ? 0 : _tabBarHeight,
+ );
+ _machinesPanel = panel;
+ _syncToolbarNotices();
+ if (_native) _syncNative();
+ setState(() {});
+ final destination = await panel.closed;
+ if (!mounted || !identical(_machinesPanel, panel)) return;
+ _machinesPanel = null;
+ _syncToolbarNotices();
+ if (_native) _syncNative();
+ setState(() {});
+ // Let the removed panel release its focus before opening work.
+ await WidgetsBinding.instance.endOfFrame;
+ if (!mounted) return;
+ final machine = destination == null ? null : app.stateOf(destination);
+ if (machine != null) {
+ if (machine.agents.isEmpty && !machine.machine.isShared) {
+ await _newAgent(
+ machineId: destination,
+ placement: HarnessPlacement.currentTab,
+ );
+ } else {
+ _openSearch(
+ adding: true,
+ query: '@',
+ placement: HarnessPlacement.currentTab,
+ );
+ final machineRow = _search?.rows
+ .where((row) => row.isMachine && row.machineId == destination)
+ .firstOrNull;
+ if (machineRow != null) _search!.submit(machineRow);
+ }
+ } else if (panel.restoreFocus && _shortcutsEnabled) {
+ _shellFocus.requestFocus();
+ final pane = app.focusedPane;
+ if (pane != null) app.focusPane(pane.id, reveal: true);
+ await _ensureEmptyEntry();
+ }
+ }
+
Future<void> _openProduct(String engine, String machineId, {String? task}) =>
_newAgent(
source: _NewHarnessSource.product,
@@ -1415,11 +1522,7 @@ class _SwarmScreenState extends State<SwarmScreen>
// joins its worktree rather than being where Start begins.
final initialFolder = folder ?? paneProject?.cwd;
if (id == null) {
- await _dialog(
- () => showSwarmLinkDialog(context, app, keymap: _keymap),
- restoreEntry: false,
- );
- await _ensureEmptyEntry();
+ await _openMachines();
return;
}
if (!newHarnessOpensInBox) {
@@ -1856,7 +1959,7 @@ class _SwarmScreenState extends State<SwarmScreen>
app.machineStates.values.firstOrNull
: app.stateOf(focused.machineId);
if (machine == null) {
- await _dialog(() => showSwarmLinkDialog(context, app, keymap: _keymap));
+ await _openMachines();
return;
}
final machineId = machine.machine.machineId;
@@ -2003,6 +2106,7 @@ class _SwarmScreenState extends State<SwarmScreen>
}
void _modelManagerChanged() {
+ _syncToolbarNotices();
if (_native && mounted) _syncNative();
}
@@ -2042,6 +2146,7 @@ class _SwarmScreenState extends State<SwarmScreen>
builder: (context, constraints) => Stack(
children: [
Positioned.fill(
+ top: _native ? 0 : _tabBarHeight,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _closeModels,
@@ -2072,6 +2177,7 @@ class _SwarmScreenState extends State<SwarmScreen>
],
),
child: ModelsPanel(
+ newModelIds: _toolbarNotices.newModelIds,
controller: app.modelManager,
subscriptions: _modelsMenu!,
onClose: _closeModels,
@@ -2085,7 +2191,10 @@ class _SwarmScreenState extends State<SwarmScreen>
),
);
Overlay.of(context).insert(_modelsOverlay!);
- _unregisterModels = registerTransientMenu(_closeModels);
+ _syncToolbarNotices();
+ _unregisterModels = registerTransientMenu(
+ () => _closeModels(restoreFocus: false),
+ );
if (_native) _syncNative();
setState(() {});
}
@@ -2097,6 +2206,7 @@ class _SwarmScreenState extends State<SwarmScreen>
_modelsOverlay?.remove();
_modelsOverlay?.dispose();
_modelsOverlay = null;
+ _syncToolbarNotices();
app.modelManager.setPanelVisible(false);
if (!mounted) return;
if (_native) _syncNative();
@@ -2125,6 +2235,7 @@ class _SwarmScreenState extends State<SwarmScreen>
builder: (context, constraints) => Stack(
children: [
Positioned.fill(
+ top: _native ? 0 : _tabBarHeight,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _closeSessions,
@@ -2186,7 +2297,9 @@ class _SwarmScreenState extends State<SwarmScreen>
),
);
overlay.insert(_sessionsOverlay!);
- _unregisterSessions = registerTransientMenu(_closeSessions);
+ _unregisterSessions = registerTransientMenu(
+ () => _closeSessions(restoreFocus: false),
+ );
if (_native) _syncNative();
setState(() {});
}
@@ -2691,6 +2804,7 @@ class _SwarmScreenState extends State<SwarmScreen>
machine.isLocalMachine ||
_dialogOpen ||
_commandBarOpen ||
+ _machinesPanel != null ||
_search != null ||
app.isLinkPromptDismissed(machine.machine.machineId) ||
_linkDialogMachineId != null) {
@@ -2699,13 +2813,7 @@ class _SwarmScreenState extends State<SwarmScreen>
_linkDialogMachineId = machine.machine.machineId;
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (mounted) {
- await _dialog(
- () => showLinkMachineScreenDialog(
- context,
- app,
- machine.machine.machineId,
- ),
- );
+ await _openMachines(initialMachineId: machine.machine.machineId);
}
_linkDialogMachineId = null;
});
@@ -2796,11 +2904,9 @@ class _SwarmScreenState extends State<SwarmScreen>
'agent.fork': _forkAgent,
// `agent.restart` and `agent.clone` come from `_actionHandlers` above:
// both carry a ShortcutAction, so the loop already binds them.
- 'machine.link': () =>
- _dialog(() => showSwarmLinkDialog(context, app, keymap: _keymap)),
+ 'machine.link': _openMachines,
'machines.manage': _manageMachines,
- 'machines.list': () =>
- _dialog(() => showMachinesManager(context, app, keymap: _keymap)),
+ 'machines.list': _openMachines,
'project.add': _addProject,
'keyboard.open_config': () => openKeyboardConfig(context),
'keyboard.quick_start': _startQuickStart,
@@ -3459,6 +3565,39 @@ class _SwarmScreenState extends State<SwarmScreen>
});
}
+ ButtonStyle _toolbarIconStyle(int notices) => ButtonStyle(
+ iconColor: WidgetStateProperty.resolveWith((states) {
+ if (notices > 0) return const Color(0xfff5f5f5);
+ if (states.contains(WidgetState.hovered) ||
+ states.contains(WidgetState.focused) ||
+ states.contains(WidgetState.pressed) ||
+ states.contains(WidgetState.selected)) {
+ return const Color(0xffd6d6d6);
+ }
+ return const Color(0xff999999);
+ }),
+ );
+
+ Widget _toolbarBadge({
+ Key? key,
+ required int count,
+ required String label,
+ required Widget child,
+ }) => Badge(
+ key: key,
+ isLabelVisible: count > 0,
+ backgroundColor: const Color(0xffcf4038),
+ textColor: Colors.white,
+ largeSize: 13,
+ alignment: Alignment.topRight,
+ label: Text(
+ count > 99 ? '99+' : '$count',
+ semanticsLabel: label,
+ style: const TextStyle(fontSize: 9, fontWeight: FontWeight.w600),
+ ),
+ child: child,
+ );
+
Widget _tabStrip() => LayoutBuilder(
builder: (context, constraints) {
final compactTools =
@@ -3619,74 +3758,82 @@ class _SwarmScreenState extends State<SwarmScreen>
icon: const Icon(Icons.add, size: 18, semanticLabel: 'New Tab'),
),
IconButton(
- key: _sessionsButton,
- tooltip: 'Harness Monitor',
- onPressed: _toggleSessions,
- isSelected: _sessionsOverlay != null,
- icon: Badge(
- key: const ValueKey('swarm-unread-badge'),
- isLabelVisible: _unread > 0,
- backgroundColor: const Color(0xffcf4038),
- textColor: Colors.white,
- largeSize: 13,
- alignment: Alignment.topRight,
- label: Text(
- _unread > 99 ? '99+' : '$_unread',
- semanticsLabel:
- '$_unread ${_unread == 1 ? 'harness has' : 'harnesses have'} news you have not seen',
- style: const TextStyle(
- fontSize: 9,
- fontWeight: FontWeight.w600,
- ),
- ),
- child: Image.asset(
- 'assets/harnesses.png',
- width: 24,
- height: 24,
- filterQuality: FilterQuality.high,
- semanticLabel: 'Harness Monitor',
- ),
+ key: const ValueKey('swarm-machines-button'),
+ tooltip: 'Machines ${_keymap.hint('machines.list') ?? ''}'.trim(),
+ onPressed: _openMachines,
+ isSelected: _machinesPanel != null,
+ style: _toolbarIconStyle(_toolbarNotices.machineCount),
+ icon: _toolbarBadge(
+ key: const ValueKey('swarm-machines-badge'),
+ count: _toolbarNotices.machineCount,
+ label:
+ '${_toolbarNotices.machineCount} new ${_toolbarNotices.machineCount == 1 ? 'computer' : 'computers'} ready to connect',
+ child: const ToolbarIcon(name: 'Machines'),
),
),
- const SizedBox(width: 6),
IconButton(
key: const ValueKey('swarm-models-button'),
- tooltip: 'AI Models',
+ tooltip: 'Models',
onPressed: _toggleModels,
isSelected: _modelsOverlay != null,
- icon: const ModelMark(size: 20, semanticLabel: 'AI Models'),
+ style: _toolbarIconStyle(_toolbarNotices.modelCount),
+ icon: _toolbarBadge(
+ key: const ValueKey('swarm-models-badge'),
+ count: _toolbarNotices.modelCount,
+ label:
+ '${_toolbarNotices.modelCount} ${_toolbarNotices.modelCount == 1 ? 'model' : 'models'} ready to use',
+ child: const ToolbarIcon(name: 'Models'),
+ ),
+ ),
+ IconButton(
+ key: _sessionsButton,
+ tooltip: 'Harnesses',
+ onPressed: _toggleSessions,
+ isSelected: _sessionsOverlay != null,
+ style: _toolbarIconStyle(_unread),
+ icon: _toolbarBadge(
+ key: const ValueKey('swarm-unread-badge'),
+ count: _unread,
+ label:
+ '$_unread ${_unread == 1 ? 'harness has' : 'harnesses have'} news you have not seen',
+ child: const ToolbarIcon(name: 'Harnesses'),
+ ),
),
const SizedBox(width: 6),
Tooltip(
message: 'Harness Store ${_keymap.hint('app.store') ?? ''}'
.trim(),
- child: TextButton.icon(
- key: const ValueKey('swarm-store-button'),
- onPressed: _openStore,
- style: TextButton.styleFrom(
- foregroundColor: grid.AppPalette.swarmAccent,
- backgroundColor: Color.alphaBlend(
- grid.AppPalette.swarmAccent.withValues(alpha: 0.10),
- grid.AppPalette.swarmField,
- ),
- overlayColor: grid.AppPalette.swarmAccent,
- textStyle: grid.AppType.monoLabel(),
- minimumSize: const Size(0, 28),
- padding: const EdgeInsets.symmetric(horizontal: 12),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- shape: StadiumBorder(
- side: BorderSide(
- color: grid.AppPalette.swarmAccent.withValues(
- alpha: 0.12,
+ child: compactTools
+ ? IconButton(
+ key: const ValueKey('swarm-store-button'),
+ onPressed: _openStore,
+ icon: const StoreMark(),
+ )
+ : TextButton.icon(
+ key: const ValueKey('swarm-store-button'),
+ onPressed: _openStore,
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.swarmAccent,
+ backgroundColor: Color.alphaBlend(
+ grid.AppPalette.swarmAccent.withValues(alpha: 0.10),
+ grid.AppPalette.swarmField,
+ ),
+ overlayColor: grid.AppPalette.swarmAccent,
+ textStyle: grid.AppType.monoLabel(),
+ minimumSize: const Size(0, 28),
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ shape: StadiumBorder(
+ side: BorderSide(
+ color: grid.AppPalette.swarmAccent.withValues(
+ alpha: 0.12,
+ ),
+ ),
+ ),
),
+ icon: const StoreMark(),
+ label: const Text('Harness Store'),
),
- ),
- ),
- icon: const StoreMark(),
- label: compactTools
- ? const SizedBox.shrink()
- : const Text('Harness Store'),
- ),
),
const SizedBox(width: 6),
],
diff --git a/desktop/lib/shortcuts/app_keymap.dart b/desktop/lib/shortcuts/app_keymap.dart
index 4be680aae..14e737d9a 100644
--- a/desktop/lib/shortcuts/app_keymap.dart
+++ b/desktop/lib/shortcuts/app_keymap.dart
@@ -55,7 +55,6 @@ class AppKeymap extends ChangeNotifier {
final reserved = {
for (final chord in [
'cmd+q',
- 'cmd+m',
'cmd+alt+h',
'cmd+ctrl+f',
'cmd+c',
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 2e3b1f77c..9680f2de3 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -348,13 +348,14 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'machines.list',
- 'Open Machines Manager',
+ 'Open Machines',
ShortcutGroup.actions,
nativeAction: 'machineList',
+ extraKeys: ['cmd+m'],
),
const HarnessCommand(
'machine.link',
- 'Link machine',
+ 'Connect another machine',
ShortcutGroup.actions,
nativeAction: 'linkMachine',
),
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 1db0af616..d7a367ec4 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -32,6 +32,7 @@ import '../core/local_hostname.dart';
import '../core/local_git_projects.dart';
import '../core/test_run.dart';
import '../core/models.dart';
+import '../core/machine_resources.dart';
import '../core/project_folder.dart';
import '../core/git_worktree.dart';
import '../core/project_history.dart';
@@ -2170,6 +2171,7 @@ class AppNotifier extends ChangeNotifier {
_dismissedLinkPrompts.contains(machineId);
void dismissLinkPrompt(String machineId) {
+ if (_disposed) return;
if (_dismissedLinkPrompts.add(machineId)) notifyListeners();
}
@@ -5107,6 +5109,42 @@ class AppNotifier extends ChangeNotifier {
machineStates.values.firstOrNull;
}
+ /// A visible Machines panel uses the existing connection; it never dials a
+ /// disconnected/unlinked host just to obtain optional system readings.
+ Future<MachineResources?> readMachineResources(String machineId) async {
+ final machine = machineStates[machineId];
+ if (_disposed ||
+ machine == null ||
+ machine.machine.isShared ||
+ machine.needsLink ||
+ machine.nodeOnline == false ||
+ machine.connectionStatus != ConnectionStatus.connected ||
+ (_pool == null && connectionForTest == null)) {
+ return null;
+ }
+ final revision = _authRevision;
+ final discoveryRevision = machine._discoveryRevision;
+ try {
+ final connection = _conn(machineId);
+ if (!connection.isReady) return null;
+ final reply = await connection.request(
+ 'machine_resources',
+ timeout: const Duration(seconds: 3),
+ );
+ if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision) ||
+ machine.needsLink ||
+ machine.nodeOnline == false ||
+ machine.connectionStatus != ConnectionStatus.connected ||
+ reply['error'] != null) {
+ return null;
+ }
+ return MachineResources.fromJson(reply);
+ } catch (_) {
+ // Older daemons and temporarily unavailable readings leave the stats blank.
+ return null;
+ }
+ }
+
WsConn _conn(String machineId) {
if (machineStates[machineId]?.machine.isShared == true) {
throw StateError('This harness is shared with view-only access.');
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 41155ee3c..44dfe6ca2 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -128,7 +128,7 @@ class SwarmSearchController extends ChangeNotifier {
: isMachineMode
? 'Machines'
: _groupScope != null
- ? 'Agents · ${_groupScope!.name}'
+ ? 'Harnesses · ${_groupScope!.name}'
: switch (split?.axis) {
PaneResizeAxis.x => 'New Pane to the Right',
PaneResizeAxis.y => 'New Pane Below',
diff --git a/desktop/lib/state/toolbar_notices.dart b/desktop/lib/state/toolbar_notices.dart
new file mode 100644
index 000000000..c4fba6628
--- /dev/null
+++ b/desktop/lib/state/toolbar_notices.dart
@@ -0,0 +1,153 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/foundation.dart';
+
+import '../core/harness_file_store.dart';
+import '../core/local_key_value_store.dart';
+import '../core/test_run.dart';
+
+/// News for the toolbar, separate from connection state or optional setup.
+/// Viewing a panel acknowledges its news; account-scoped receipts survive restart.
+class ToolbarNotices extends ChangeNotifier {
+ ToolbarNotices({LocalKeyValueStore? storage})
+ : _storage = storage ?? (kUnderTest ? null : HarnessFileStore.shared);
+
+ final LocalKeyValueStore? _storage;
+ String? _scope;
+ bool _loaded = false, _disposed = false, _catalogInitialized = false;
+ bool _machinesVisible = false, _modelsVisible = false, _catalogLoaded = false;
+ Set<String> _machines = {}, _ready = {}, _catalog = {};
+ Set<String> _seenMachines = {}, _seenReady = {}, _knownModels = {};
+ Set<String> _newInPanel = {};
+ int _machineCount = 0, _modelCount = 0;
+ int _revision = 0;
+ Future<void> _writes = Future.value();
+
+ int get machineCount => _machineCount;
+ int get modelCount => _modelCount;
+ Set<String> get newModelIds => Set.unmodifiable(_newInPanel);
+ static String storageKey(String scope) =>
+ 'toolbar.notices.${base64Url.encode(utf8.encode(scope))}';
+
+ void sync({
+ required String scope,
+ required Set<String> machines,
+ required Set<String> readyModels,
+ required Set<String> catalog,
+ required bool catalogLoaded,
+ required bool machinesVisible,
+ required bool modelsVisible,
+ }) {
+ if (_disposed) return;
+ final changedScope = _scope != scope;
+ if (changedScope) {
+ _revision++;
+ _scope = scope;
+ _loaded = false;
+ _catalogInitialized = false;
+ _seenMachines = {};
+ _seenReady = {};
+ _knownModels = {};
+ _newInPanel = {};
+ _machineCount = _modelCount = 0;
+ }
+ _machines = Set.of(machines);
+ _ready = Set.of(readyModels);
+ _catalog = Set.of(catalog);
+ _catalogLoaded = catalogLoaded;
+ _machinesVisible = machinesVisible;
+ _modelsVisible = modelsVisible;
+ if (changedScope) {
+ notifyListeners();
+ unawaited(_load(scope, _revision));
+ } else {
+ _apply();
+ }
+ }
+
+ Future<void> _load(String scope, int revision) async {
+ Map<String, dynamic> data = {};
+ try {
+ // A quick account switch must not read before its previous acknowledgement.
+ await _writes;
+ final raw = await _storage?.read(storageKey(scope));
+ if (raw != null) {
+ final decoded = jsonDecode(raw);
+ if (decoded is Map<String, dynamic>) data = decoded;
+ }
+ } catch (_) {
+ // A preference failure never blocks a machine or model.
+ }
+ if (_disposed || _revision != revision) return;
+ Set<String> ids(String key) => data[key] is List
+ ? (data[key] as List).whereType<String>().toSet()
+ : {};
+ _seenMachines = ids('machines');
+ _seenReady = ids('ready');
+ _knownModels = ids('catalog');
+ _catalogInitialized = data['catalog'] is List;
+ _loaded = true;
+ _apply();
+ }
+
+ void _apply() {
+ if (!_loaded || _disposed) return;
+ var save = false;
+ if (_machinesVisible && !_seenMachines.containsAll(_machines)) {
+ _seenMachines.addAll(_machines);
+ save = true;
+ }
+ if (_modelsVisible && !_seenReady.containsAll(_ready)) {
+ _seenReady.addAll(_ready);
+ save = true;
+ }
+ // The initial catalog is a baseline, not hundreds of "new" releases.
+ if (_catalogLoaded && !_catalogInitialized) {
+ _knownModels.addAll(_catalog);
+ _catalogInitialized = true;
+ save = true;
+ }
+ final newInPanel = _modelsVisible
+ ? {
+ ..._newInPanel.intersection(_catalog),
+ ..._catalog.difference(_knownModels),
+ }
+ : <String>{};
+ if (_modelsVisible && !_knownModels.containsAll(_catalog)) {
+ _knownModels.addAll(_catalog);
+ save = true;
+ }
+ final machines = _machines.difference(_seenMachines).length;
+ final models = _ready.difference(_seenReady).length;
+ final changed =
+ machines != _machineCount ||
+ models != _modelCount ||
+ !setEquals(_newInPanel, newInPanel);
+ _machineCount = machines;
+ _modelCount = models;
+ _newInPanel = newInPanel;
+ if (save) _save();
+ if (changed) notifyListeners();
+ }
+
+ void _save() {
+ final key = storageKey(_scope!);
+ final value = jsonEncode({
+ 'machines': _seenMachines.toList(),
+ 'ready': _seenReady.toList(),
+ if (_catalogInitialized) 'catalog': _knownModels.toList(),
+ });
+ _writes = _writes.then((_) async {
+ try {
+ await _storage?.write(key, value);
+ } catch (_) {}
+ });
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/widgets/harness_session_manager.dart b/desktop/lib/widgets/harness_session_manager.dart
index 9358167cb..0e893bd03 100644
--- a/desktop/lib/widgets/harness_session_manager.dart
+++ b/desktop/lib/widgets/harness_session_manager.dart
@@ -279,12 +279,12 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
children: [
Expanded(
child: Text(
- 'Harness Monitor',
+ 'Harnesses',
style: AppType.heading(),
),
),
IconButton(
- tooltip: 'Close Harness Monitor',
+ tooltip: 'Close Harnesses',
onPressed: widget.onClose,
icon: const Icon(LucideIcons.x, size: 16),
),
diff --git a/desktop/lib/widgets/machine_actions.dart b/desktop/lib/widgets/machine_actions.dart
index 72a2eaec3..05bfa7e1c 100644
--- a/desktop/lib/widgets/machine_actions.dart
+++ b/desktop/lib/widgets/machine_actions.dart
@@ -40,6 +40,7 @@ class _DeleteMachinePrompt extends StatefulWidget {
class _DeleteMachinePromptState extends State<_DeleteMachinePrompt> {
final _cancel = FocusNode(debugLabel: 'Cancel machine deletion');
+ final _promptFocus = FocusNode(debugLabel: 'Machine deletion');
final _announcer = BoxAnnouncer();
bool _deleting = false;
String? _error;
@@ -65,6 +66,7 @@ class _DeleteMachinePromptState extends State<_DeleteMachinePrompt> {
@override
void dispose() {
_cancel.dispose();
+ _promptFocus.dispose();
super.dispose();
}
@@ -76,6 +78,9 @@ class _DeleteMachinePromptState extends State<_DeleteMachinePrompt> {
_deleting = true;
_error = null;
});
+ // The focused Delete button is removed while waiting. Keep keyboard input
+ // on this prompt so Escape can close it without reaching the panel behind.
+ _promptFocus.requestFocus();
unawaited(_finish(widget.notifier.deleteMachine(widget.machineId)));
}
@@ -100,6 +105,7 @@ class _DeleteMachinePromptState extends State<_DeleteMachinePrompt> {
return ListenableBuilder(
listenable: terminalFontStore,
builder: (context, _) => TerminalPromptKeys(
+ focusNode: _promptFocus,
cancel: _close,
child: TerminalPrompt(
child: Column(
diff --git a/desktop/lib/widgets/machines_manager.dart b/desktop/lib/widgets/machines_manager.dart
index 436c16b57..a7a684e17 100644
--- a/desktop/lib/widgets/machines_manager.dart
+++ b/desktop/lib/widgets/machines_manager.dart
@@ -455,7 +455,7 @@ class _MachinesManagerState extends State<_MachinesManager> {
Expanded(
child: Text(
_machineId == null
- ? 'Machines Manager'
+ ? 'Machines'
: machine?.machine.displayName ??
_machineTitle ??
'Machine',
diff --git a/desktop/lib/widgets/machines_panel.dart b/desktop/lib/widgets/machines_panel.dart
new file mode 100644
index 000000000..a416a2a43
--- /dev/null
+++ b/desktop/lib/widgets/machines_panel.dart
@@ -0,0 +1,1467 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../auth/cli_link.dart';
+import '../core/models.dart';
+import '../core/machine_resources.dart';
+import '../screens/login_screen.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shortcuts/app_keymap.dart';
+import '../state/app_state.dart';
+import '../terminal/terminal_text.dart';
+import 'box_chrome.dart' show ReadlineKeys;
+import 'link_another_machine_dialog.dart'
+ show
+ kHarnessDownloadUrl,
+ kLinkServerInstallCommand,
+ kLinkServerLoginCommand,
+ kLinkServerStartCommand;
+import 'link_machine_dialog.dart';
+import 'machine_actions.dart';
+import 'terminal_name_prompt.dart';
+import 'terminal_prompt.dart';
+import 'transient_menus.dart';
+
+/// One place to connect out and make this computer available. The notifier
+/// owns every operation; closing this surface never cancels a link or save.
+/// Returns the machine on which the user wants to open a harness.
+Future<String?> showMachinesPanel(
+ BuildContext context,
+ AppNotifier notifier, {
+ AppKeymap? keymap,
+ String? initialMachineId,
+}) => openMachinesPanel(
+ context,
+ notifier,
+ keymap: keymap,
+ initialMachineId: initialMachineId,
+).closed;
+
+/// An anchored toolbar surface, on the same overlay and with the same bounds
+/// as Harnesses. It never pushes a route or dims the workspace.
+MachinesPanelHandle openMachinesPanel(
+ BuildContext context,
+ AppNotifier notifier, {
+ AppKeymap? keymap,
+ String? initialMachineId,
+ double toolbarHeight = 0,
+}) {
+ if (initialMachineId != null) notifier.revisitLinkPrompt(initialMachineId);
+ final activeKeymap = keymap ?? KeymapTheme.of(context, listen: false);
+ final handle = MachinesPanelHandle._(notifier, initialMachineId);
+ handle._entry = OverlayEntry(
+ builder: (context) => LayoutBuilder(
+ builder: (context, constraints) {
+ final panel = _MachinesPanel(
+ notifier: notifier,
+ initialMachineId: initialMachineId,
+ onClose: () => handle.close(),
+ onOpen: (id) => handle.close(destination: id, restoreFocus: false),
+ onModalChanged: handle.hideForModal,
+ active: !handle._hidden,
+ );
+ return Offstage(
+ offstage: handle._hidden,
+ child: Stack(
+ children: [
+ Positioned.fill(
+ top: toolbarHeight,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => handle.close(),
+ child: const SizedBox.expand(),
+ ),
+ ),
+ Positioned(
+ top: toolbarHeight + 8,
+ right: 10,
+ width: (constraints.maxWidth - 20).clamp(0, 640),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: (constraints.maxHeight - toolbarHeight - 20)
+ .clamp(0, 620),
+ ),
+ child: activeKeymap == null
+ ? panel
+ : KeymapProvider(keymap: activeKeymap, child: panel),
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ ),
+ );
+ Overlay.of(context).insert(handle._entry);
+ handle._entry.addListener(() {
+ if (!handle._entry.mounted) {
+ scheduleMicrotask(() => handle.close(restoreFocus: false));
+ }
+ });
+ handle._unregister = registerTransientMenu(
+ () => handle.close(restoreFocus: false),
+ );
+ return handle;
+}
+
+class MachinesPanelHandle {
+ MachinesPanelHandle._(this._app, this._initialMachineId);
+ final AppNotifier _app;
+ final String? _initialMachineId;
+ final _result = Completer<String?>();
+ late final OverlayEntry _entry;
+ VoidCallback? _unregister;
+ bool restoreFocus = true;
+ bool _hidden = false;
+ Future<String?> get closed => _result.future;
+
+ void rebuild() {
+ if (!_result.isCompleted) _entry.markNeedsBuild();
+ }
+
+ void hideForModal(bool hidden) {
+ _hidden = hidden;
+ rebuild();
+ }
+
+ void close({String? destination, bool restoreFocus = true}) {
+ if (_result.isCompleted) return;
+ this.restoreFocus = restoreFocus;
+ _unregister?.call();
+ _unregister = null;
+ if (_initialMachineId case final id?
+ when _app.stateOf(id)?.needsLink == true) {
+ _app.dismissLinkPrompt(id);
+ }
+ _entry.remove();
+ _entry.dispose();
+ _result.complete(destination);
+ }
+}
+
+class _MachinesPanel extends StatefulWidget {
+ const _MachinesPanel({
+ required this.notifier,
+ this.initialMachineId,
+ required this.onClose,
+ required this.onOpen,
+ required this.onModalChanged,
+ required this.active,
+ });
+ final AppNotifier notifier;
+ final String? initialMachineId;
+ final VoidCallback onClose;
+ final ValueChanged<String> onOpen;
+ final ValueChanged<bool> onModalChanged;
+ final bool active;
+
+ @override
+ State<_MachinesPanel> createState() => _MachinesPanelState();
+}
+
+class _MachinesPanelState extends State<_MachinesPanel>
+ with WidgetsBindingObserver {
+ AppNotifier get app => widget.notifier;
+ final _panelFocus = FocusNode(debugLabel: 'Machines');
+ bool _showSetup = false, _server = false, _signingIn = false;
+ bool _downloadFailed = false;
+ String? _expandedMachine;
+ String? _focusMachine;
+ final _resources = <String, MachineResources>{};
+ final _resourceMachines = <String, MachineState>{};
+ final _nextResourceRead = <String, int>{};
+ final _resourceRequests = <String, Object>{};
+ Timer? _resourceTimer;
+ int _resourceTick = 0;
+
+ bool get _canReadResources =>
+ widget.active &&
+ !app.isGuest &&
+ (WidgetsBinding.instance.lifecycleState == null ||
+ WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed);
+
+ bool _readable(MachineState machine) =>
+ !machine.machine.isShared &&
+ !machine.needsLink &&
+ machine.nodeOnline != false &&
+ machine.connectionStatus == ConnectionStatus.connected;
+
+ void _syncResourcePolling() {
+ _resourceTimer?.cancel();
+ _resourceTimer = null;
+ if (!_canReadResources) return;
+ _nextResourceRead.clear();
+ _refreshResources();
+ _resourceTimer = Timer.periodic(const Duration(seconds: 5), (_) {
+ _resourceTick++;
+ _refreshResources();
+ });
+ }
+
+ void _machinesChanged() {
+ if (_canReadResources != (_resourceTimer != null)) {
+ _syncResourcePolling();
+ } else {
+ _refreshResources();
+ }
+ }
+
+ void _refreshResources() {
+ if (!mounted) return;
+ for (final id in {
+ ..._nextResourceRead.keys,
+ ..._resources.keys,
+ ..._resourceRequests.keys,
+ }) {
+ final machine = app.stateOf(id);
+ if (machine == null ||
+ !identical(machine, _resourceMachines[id]) ||
+ !_readable(machine)) {
+ _resources.remove(id);
+ _resourceMachines.remove(id);
+ _nextResourceRead.remove(id);
+ _resourceRequests.remove(id);
+ }
+ }
+ if (!_canReadResources) return;
+ for (final machine in app.machineStates.values) {
+ final id = machine.machine.machineId;
+ if (!_readable(machine) ||
+ _resourceRequests.containsKey(id) ||
+ (_nextResourceRead[id] ?? 0) > _resourceTick) {
+ continue;
+ }
+ final request = Object();
+ _resourceMachines[id] = machine;
+ _resourceRequests[id] = request;
+ _nextResourceRead[id] = _resourceTick + 1;
+ unawaited(_readResources(machine, request));
+ }
+ }
+
+ Future<void> _readResources(MachineState machine, Object request) async {
+ final id = machine.machine.machineId;
+ final reading = await app.readMachineResources(id);
+ if (!mounted || _resourceRequests[id] != request) return;
+ _resourceRequests.remove(id);
+ if (!identical(app.stateOf(id), machine) || !_readable(machine)) return;
+ // Older machines should not be asked every tick for a reply they cannot send.
+ if (reading == null) {
+ _nextResourceRead[id] = _resourceTick + 6;
+ }
+ setState(() {
+ if (reading == null) {
+ _resources.remove(id);
+ } else {
+ _resources[id] = reading;
+ }
+ });
+ }
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) =>
+ _syncResourcePolling();
+
+ @override
+ void didUpdateWidget(covariant _MachinesPanel oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.active != widget.active) _syncResourcePolling();
+ }
+
+ List<MachineState> get _remotes =>
+ app.machineStates.values.where((m) => !m.isLocalMachine).toList()
+ ..sort((a, b) {
+ int order(MachineState m) => m.nodeOnline == false
+ ? 2
+ : m.needsLink && !m.machine.isShared
+ ? 0
+ : 1;
+ final availability = order(a).compareTo(order(b));
+ return availability != 0
+ ? availability
+ : a.machine.displayName.toLowerCase().compareTo(
+ b.machine.displayName.toLowerCase(),
+ );
+ });
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addObserver(this);
+ app.addListener(_machinesChanged);
+ _syncResourcePolling();
+ _expandedMachine =
+ widget.initialMachineId ??
+ _remotes
+ .where((m) => app.pendingMachineLink(m.machine.machineId) != null)
+ .firstOrNull
+ ?.machine
+ .machineId;
+ _focusMachine = _expandedMachine;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _panelFocus.requestFocus();
+ });
+ }
+
+ @override
+ void dispose() {
+ WidgetsBinding.instance.removeObserver(this);
+ app.removeListener(_machinesChanged);
+ _resourceTimer?.cancel();
+ _panelFocus.dispose();
+ super.dispose();
+ }
+
+ Future<void> _signIn() async {
+ setState(() => _signingIn = true);
+ await _modal(
+ () => showSignInSheet(
+ context,
+ app,
+ reason:
+ 'Sign in with the same account on both computers to connect them.',
+ ),
+ );
+ if (!mounted) return;
+ setState(() => _signingIn = false);
+ if (!app.isGuest) unawaited(app.retryMachines());
+ }
+
+ Future<T> _modal<T>(Future<T> Function() show) async {
+ widget.onModalChanged(true);
+ try {
+ return await show();
+ } finally {
+ if (mounted) _reveal();
+ }
+ }
+
+ void _reveal() {
+ widget.onModalChanged(false);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _panelFocus.requestFocus();
+ });
+ }
+
+ Future<void> _machineAction(String action, MachineState machine) async {
+ final id = machine.machine.machineId;
+ switch (action) {
+ case 'rename':
+ await showTerminalPrompt<String>(
+ context,
+ builder: (_) => TerminalNamePrompt(
+ title: 'Rename Machine',
+ name: app.pendingMachineName(id) ?? machine.machine.displayName,
+ fieldKey: const Key('machine-rename-input'),
+ fieldLabel: 'Machine name',
+ pending: app.pendingMachineRename(id),
+ save: (name) => app.renameMachine(id, name),
+ ),
+ );
+ case 'delete':
+ await confirmDeleteMachine(
+ context,
+ app,
+ machineId: id,
+ displayName: machine.machine.displayName,
+ );
+ case 'advanced':
+ await showLinkMachineDialog(context, app);
+ // The advanced surface can change or clear the incoming password.
+ if (mounted) setState(() => _passwordRevision++);
+ }
+ }
+
+ int _passwordRevision = 0;
+
+ Widget _actions(MachineState machine) => SizedBox(
+ width: 32,
+ height: 32,
+ child: PopupMenuButton<String>(
+ tooltip: 'Options for ${machine.machine.displayName}',
+ padding: EdgeInsets.zero,
+ icon: Icon(
+ LucideIcons.ellipsis,
+ semanticLabel: 'Options for ${machine.machine.displayName}',
+ size: 16,
+ color: grid.AppPalette.textFaint,
+ ),
+ onOpened: () => widget.onModalChanged(true),
+ onCanceled: _reveal,
+ onSelected: (action) =>
+ unawaited(_modal(() => _machineAction(action, machine))),
+ itemBuilder: (_) => [
+ const PopupMenuItem(value: 'rename', child: Text('Rename')),
+ if (!machine.isLocalMachine)
+ const PopupMenuItem(
+ value: 'delete',
+ child: Text('Remove from account…'),
+ ),
+ if (machine.isLocalMachine)
+ const PopupMenuItem(
+ value: 'advanced',
+ child: Text('Connection settings…'),
+ ),
+ ],
+ ),
+ );
+
+ Widget _setup() {
+ final email = app.currentUser?.email;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const Text('1. Open Harness on your other computer.'),
+ const SizedBox(height: 6),
+ _Detail(
+ email == null
+ ? 'Sign in with the same account.'
+ : 'Sign in as $email.',
+ ),
+ const SizedBox(height: 8),
+ Wrap(
+ spacing: 8,
+ runSpacing: 4,
+ children: [
+ _button('Download Harness', () async {
+ var opened = false;
+ try {
+ opened = await launchUrl(
+ kHarnessDownloadUrl,
+ mode: LaunchMode.externalApplication,
+ );
+ } catch (_) {
+ // The adjacent copy action still works without a browser.
+ }
+ if (mounted) setState(() => _downloadFailed = !opened);
+ }, primary: true),
+ _CopyButton('Copy download link', kHarnessDownloadUrl.toString()),
+ ],
+ ),
+ if (_downloadFailed) ...[
+ const SizedBox(height: 6),
+ const _Feedback(
+ 'Couldn’t open your browser. Copy the link instead.',
+ error: true,
+ ),
+ ],
+ const SizedBox(height: 16),
+ const Text('2. Open Machines and choose Set password.'),
+ const SizedBox(height: 6),
+ const _Detail('Back here, click Connect and enter that password.'),
+ const SizedBox(height: 12),
+ _button(
+ _server ? 'Hide server setup' : 'Set up a server…',
+ () => setState(() => _server = !_server),
+ ),
+ if (_server) ...[
+ const SizedBox(height: 6),
+ const _Detail('Run these on your server over SSH:'),
+ const SizedBox(height: 8),
+ Container(
+ padding: const EdgeInsets.fromLTRB(12, 4, 12, 12),
+ decoration: BoxDecoration(
+ color: grid.AppPalette.textPrimary.withValues(alpha: .05),
+ borderRadius: BorderRadius.circular(8),
+ border: Border.all(
+ color: grid.AppPalette.textPrimary.withValues(alpha: .10),
+ ),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(child: _Detail('Terminal')),
+ _CopyButton(
+ 'Copy commands',
+ '$kLinkServerInstallCommand\n$kLinkServerLoginCommand\n$kLinkServerStartCommand',
+ iconOnly: true,
+ ),
+ ],
+ ),
+ SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ child: SelectableText(
+ '$kLinkServerInstallCommand\n$kLinkServerLoginCommand\n$kLinkServerStartCommand',
+ style: grid.AppType.monoLabel(
+ color: grid.AppPalette.textSecondary,
+ ).copyWith(height: 1.6),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ],
+ );
+ }
+
+ Widget _remote(MachineState machine) {
+ final id = machine.machine.machineId;
+ final name = machine.machine.displayName;
+ final offline = machine.nodeOnline == false;
+ final linking = app.pendingMachineLink(id) != null;
+ final connected = machine.connectionStatus == ConnectionStatus.connected;
+ final ready = connected && !machine.needsLink && !linking;
+ final canConnect =
+ !offline && machine.needsLink && !machine.machine.isShared;
+ final status = offline
+ ? 'Offline'
+ : linking
+ ? 'Connecting…'
+ : machine.needsLink
+ ? 'Online'
+ : connected
+ ? 'Connected'
+ : 'Connecting…';
+ final options = machine.machine.isShared ? null : _actions(machine);
+ if (!offline &&
+ (machine.needsLink || linking) &&
+ _expandedMachine == id &&
+ !machine.machine.isShared) {
+ return _MachinePassword(
+ key: ValueKey('connect-password-$id'),
+ app: app,
+ machine: machine,
+ options: options,
+ autofocus: _focusMachine == id,
+ resources: _resources[id],
+ onClose: widget.onClose,
+ );
+ }
+ void connect() => setState(() {
+ _expandedMachine = id;
+ _focusMachine = id;
+ _showSetup = false;
+ });
+ return _MachineRow(
+ key: ValueKey('machine-$id'),
+ name: name,
+ annotation: offline
+ ? 'Offline'
+ : linking || !connected && !machine.needsLink
+ ? 'Connecting…'
+ : machine.machine.isShared
+ ? 'Shared with you'
+ : null,
+ onTap: !offline && ready
+ ? () => widget.onOpen(id)
+ : canConnect
+ ? connect
+ : null,
+ subtitle: Tooltip(
+ message: offline ? 'Open Harness on $name to bring it online.' : status,
+ child: _MachineDetails(machine: machine, resources: _resources[id]),
+ ),
+ action:
+ !offline &&
+ ready &&
+ machine.agents.isEmpty &&
+ !machine.machine.isShared
+ ? _button(
+ 'New harness',
+ () => widget.onOpen(id),
+ key: ValueKey('open-machine-$id'),
+ primary: true,
+ )
+ : canConnect
+ ? _button(
+ 'Connect',
+ connect,
+ key: ValueKey('connect-machine-$id'),
+ primary: true,
+ )
+ : null,
+ options: options,
+ );
+ }
+
+ Widget _local(MachineState? machine) {
+ if (machine != null && !app.isGuest) {
+ return _MachinePassword(
+ key: ValueKey(
+ 'local-password-$_passwordRevision-${machine.machine.machineId}',
+ ),
+ app: app,
+ machine: machine,
+ resources: _resources[machine.machine.machineId],
+ options: _actions(machine),
+ onClose: widget.onClose,
+ );
+ }
+ return _MachineRow(
+ name: machine?.machine.displayName ?? 'This computer',
+ local: machine != null,
+ subtitle: _MachineStatus(
+ app.isGuest ? 'Sign in to connect your machines' : 'Starting Harness…',
+ ),
+ action: app.isGuest
+ ? _button(
+ _signingIn ? 'Signing in…' : 'Sign in',
+ _signingIn ? null : () => unawaited(_signIn()),
+ primary: true,
+ )
+ : null,
+ );
+ }
+
+ Widget _addMachine(bool empty) {
+ void toggle() => setState(() => _showSetup = !_showSetup);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _MachineRow(
+ key: const ValueKey('add-machine'),
+ name: empty ? 'Add a second machine' : 'Add machine',
+ icon: LucideIcons.plus,
+ subtitle: empty
+ ? const _MachineStatus('Run harnesses on another computer')
+ : null,
+ onTap: toggle,
+ action: IconButton(
+ tooltip: _showSetup ? 'Hide setup steps' : 'Add a machine',
+ onPressed: toggle,
+ icon: Icon(
+ _showSetup ? LucideIcons.chevronUp : LucideIcons.chevronRight,
+ semanticLabel: _showSetup ? 'Hide setup steps' : 'Add a machine',
+ size: 18,
+ ),
+ ),
+ ),
+ if (_showSetup)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(46, 0, 16, 12),
+ child: _setup(),
+ ),
+ ],
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
+ return ListenableBuilder(
+ listenable: Listenable.merge([app, terminalFontStore]),
+ builder: (context, _) {
+ final local = app.localMachineState;
+ final remotes = _remotes;
+ // New arrivals must not replace a password someone is already typing.
+ if (!remotes.any((m) => m.machine.machineId == _expandedMachine)) {
+ _expandedMachine = null;
+ }
+ final empty = remotes.isEmpty;
+ return FocusScope(
+ child: TerminalPromptKeys(
+ focusNode: _panelFocus,
+ cancel: widget.onClose,
+ refresh: app.isGuest ? null : () => unawaited(app.retryMachines()),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(
+ color: grid.AppPalette.textPrimary.withValues(alpha: .12),
+ ),
+ boxShadow: [
+ BoxShadow(
+ color: Colors.black.withValues(alpha: .35),
+ blurRadius: 36,
+ offset: const Offset(0, 12),
+ ),
+ ],
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(1),
+ child: Material(
+ key: const ValueKey('machines-panel'),
+ color: grid.AppPalette.panelBg,
+ borderRadius: BorderRadius.circular(14),
+ clipBehavior: Clip.antiAlias,
+ child: DefaultTextStyle(
+ style: _panelText(),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 10, 12, 8),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Machines',
+ style: grid.AppType.heading(),
+ ),
+ ),
+ IconButton(
+ tooltip: 'Close Machines',
+ onPressed: widget.onClose,
+ icon: Icon(
+ LucideIcons.x,
+ semanticLabel: 'Close Machines',
+ size: 18,
+ color: grid.AppPalette.textFaint,
+ ),
+ ),
+ ],
+ ),
+ ),
+ Divider(
+ height: 1,
+ color: grid.AppPalette.textPrimary.withValues(
+ alpha: .10,
+ ),
+ ),
+ Flexible(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _local(local),
+ if (!app.isGuest) ...[
+ for (final machine in remotes)
+ _remote(machine),
+ if (app.machineListError case final error?)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ 12,
+ 8,
+ 12,
+ 8,
+ ),
+ child: Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ children: [
+ _Feedback(
+ 'Couldn’t update your machines. $error',
+ error: true,
+ ),
+ _button(
+ 'Try again',
+ () =>
+ unawaited(app.retryMachines()),
+ ),
+ ],
+ ),
+ )
+ else if (empty && app.machinesLoading)
+ const Padding(
+ padding: EdgeInsets.fromLTRB(
+ 46,
+ 12,
+ 12,
+ 12,
+ ),
+ child: _Detail(
+ 'Looking for your machines…',
+ ),
+ ),
+ Divider(
+ height: 13,
+ indent: 12,
+ endIndent: 12,
+ color: grid.AppPalette.textPrimary
+ .withValues(alpha: .10),
+ ),
+ _addMachine(empty),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+}
+
+/// Every computer has the same silhouette: icon, name, one detail line, action.
+/// The detail line becomes the password field while setting up a connection.
+class _MachineRow extends StatelessWidget {
+ const _MachineRow({
+ super.key,
+ required this.name,
+ this.local = false,
+ this.annotation,
+ this.icon = LucideIcons.monitor,
+ this.subtitle,
+ this.action,
+ this.options,
+ this.onTap,
+ });
+ final String name;
+ final bool local;
+ final String? annotation;
+ String? get _annotation => annotation ?? (local ? 'This computer' : null);
+ final IconData icon;
+ final Widget? subtitle, action, options;
+ final VoidCallback? onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final row = Padding(
+ padding: const EdgeInsets.fromLTRB(12, 12, 4, 12),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ // At larger text sizes, keep the details legible instead of squeezing
+ // them into the space left by the fixed-width action column.
+ final stacked =
+ action != null &&
+ action is! IconButton &&
+ constraints.maxWidth <
+ MediaQuery.textScalerOf(context).scale(490);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Icon(icon, size: 22, color: grid.AppPalette.textSecondary),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Flexible(
+ child: Tooltip(
+ message: name,
+ child: Text(
+ name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.label(height: 1.3),
+ ),
+ ),
+ ),
+ if (_annotation != null) ...[
+ const SizedBox(width: 8),
+ Flexible(
+ child: Text(
+ '· $_annotation',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.monoMeta(
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ if (subtitle != null) ...[
+ const SizedBox(height: 5),
+ subtitle!,
+ ],
+ ],
+ ),
+ ),
+ if (action != null && !stacked) ...[
+ const SizedBox(width: 12),
+ action!,
+ ],
+ const SizedBox(width: 4),
+ options ?? const SizedBox(width: 32),
+ ],
+ ),
+ if (stacked)
+ Padding(
+ padding: const EdgeInsets.only(top: 10, right: 36),
+ child: Align(alignment: Alignment.centerRight, child: action),
+ ),
+ ],
+ );
+ },
+ ),
+ );
+ return Padding(
+ padding: const EdgeInsets.symmetric(vertical: 1),
+ child: Semantics(
+ container: true,
+ explicitChildNodes: true,
+ child: onTap == null
+ ? row
+ : InkWell(
+ onTap: onTap,
+ borderRadius: BorderRadius.circular(8),
+ child: row,
+ ),
+ ),
+ );
+ }
+}
+
+class _MachineStatus extends StatelessWidget {
+ const _MachineStatus(this.text);
+ final String text;
+
+ @override
+ Widget build(BuildContext context) => Text(
+ text,
+ style: grid.AppType.monoMeta(
+ height: 1.3,
+ color: grid.AppPalette.textSecondary,
+ ),
+ );
+}
+
+class _MachineDetails extends StatelessWidget {
+ const _MachineDetails({required this.machine, this.resources});
+ final MachineState machine;
+ final MachineResources? resources;
+
+ String _gb(double bytes) {
+ final gb = bytes / (1024 * 1024 * 1024);
+ return gb
+ .toStringAsFixed(gb < 10 ? 1 : 0)
+ .replaceFirst(RegExp(r'\.0$'), '');
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final reachable =
+ machine.nodeOnline != false &&
+ !machine.needsLink &&
+ machine.connectionStatus == ConnectionStatus.connected;
+ final count =
+ reachable &&
+ (machine.agentLoadStatus == AgentLoadStatus.loaded ||
+ machine.agents.isNotEmpty)
+ ? machine.agents.length
+ : null;
+ final stats = reachable ? resources : null;
+ final cpu = stats?.cpuPercent?.round();
+ final used = stats?.memoryUsedBytes, total = stats?.memoryTotalBytes;
+ final memory = used == null || total == null
+ ? '—'
+ : '${_gb(used)}/${_gb(total)} GB';
+ return Text(
+ '${count ?? '—'} ${count == 1 ? 'harness' : 'harnesses'} · CPU ${cpu == null ? '—' : '$cpu%'} · RAM $memory',
+ key: ValueKey('machine-stats-${machine.machine.machineId}'),
+ style: grid.AppType.monoMeta(
+ height: 1.3,
+ color: grid.AppPalette.textSecondary,
+ ),
+ );
+ }
+}
+
+/// The same small, inline form for incoming passwords and outgoing links.
+/// Password buffers belong only to this widget and are cleared on success.
+class _MachinePassword extends StatefulWidget {
+ const _MachinePassword({
+ super.key,
+ required this.app,
+ required this.machine,
+ required this.onClose,
+ this.options,
+ this.resources,
+ this.autofocus = false,
+ });
+ final AppNotifier app;
+ final MachineState machine;
+ final VoidCallback onClose;
+ final Widget? options;
+ final MachineResources? resources;
+ String? get machineId =>
+ machine.isLocalMachine ? null : machine.machine.machineId;
+ final bool autofocus;
+ @override
+ State<_MachinePassword> createState() => _MachinePasswordState();
+}
+
+class _MachinePasswordState extends State<_MachinePassword> {
+ final _password = TextEditingController();
+ final _input = FocusNode(debugLabel: 'Machine password');
+ RemotePasswordStatus? _status;
+ bool _loading = false, _busy = false, _editing = false, _obscure = true;
+ bool _showHelp = false;
+ String? _error;
+ bool get _local => widget.machineId == null;
+ bool get _composing =>
+ _password.value.composing.isValid &&
+ !_password.value.composing.isCollapsed;
+
+ @override
+ void initState() {
+ super.initState();
+ if (_local) {
+ if (widget.app.pendingRemotePasswordChange case final pending?) {
+ _busy = true;
+ unawaited(_finishPassword(pending));
+ } else {
+ unawaited(_load());
+ }
+ } else if (widget.app.pendingMachineLink(widget.machineId!)
+ case final pending?) {
+ _busy = true;
+ unawaited(_finishLink(pending));
+ }
+ if (widget.autofocus) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _input.requestFocus();
+ }
+ });
+ }
+ }
+
+ @override
+ void dispose() {
+ _password.dispose();
+ _input.dispose();
+ super.dispose();
+ }
+
+ Future<void> _load() async {
+ setState(() {
+ _loading = true;
+ _error = null;
+ });
+ final status = await widget.app.remotePasswordStatus();
+ if (!mounted) return;
+ setState(() {
+ _loading = false;
+ _error = status.error;
+ if (status.error == null) {
+ _status = status;
+ _editing = false;
+ }
+ });
+ }
+
+ Future<void> _finishPassword(Future<RemotePasswordStatus> request) async {
+ final result = await request;
+ if (!mounted) return;
+ setState(() {
+ _busy = false;
+ _error = result.error;
+ if (result.error == null) {
+ _status = result;
+ _editing = false;
+ _password.clear();
+ _obscure = true;
+ _showHelp = false;
+ }
+ });
+ // A reopened failed operation has no status yet. Never present it as unset.
+ if (result.error != null && _status == null) {
+ final status = await widget.app.remotePasswordStatus();
+ if (!mounted) return;
+ setState(() {
+ if (status.error == null) {
+ _status = status;
+ _editing = true;
+ }
+ });
+ }
+ }
+
+ Future<void> _finishLink(Future<String?> request) async {
+ final error = await request;
+ if (!mounted) return;
+ setState(() {
+ _busy = false;
+ _error = error;
+ });
+ if (error == null) {
+ _password.clear();
+ } else {
+ _input.requestFocus();
+ }
+ }
+
+ void _submit() {
+ if (_busy || _loading || _composing) return;
+ if (_password.text.isEmpty || _password.text.contains(RegExp(r'[\r\n]'))) {
+ setState(
+ () => _error = _password.text.isEmpty
+ ? 'Enter a password.'
+ : 'Use a password on one line.',
+ );
+ _input.requestFocus();
+ return;
+ }
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ if (_local) {
+ unawaited(
+ _finishPassword(
+ widget.app
+ .setRemotePassword(_password.text)
+ .then(
+ (result) => RemotePasswordStatus(
+ error: result.error,
+ hasPassword: result.error == null,
+ fingerprint: result.fingerprint,
+ ),
+ ),
+ ),
+ );
+ } else {
+ unawaited(
+ _finishLink(
+ widget.app.connectWithPassword(widget.machineId!, _password.text),
+ ),
+ );
+ }
+ }
+
+ void _editPassword() {
+ setState(() {
+ _editing = true;
+ _error = null;
+ });
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _input.requestFocus();
+ });
+ }
+
+ Widget _row({required Widget subtitle, Widget? action, String? annotation}) =>
+ _MachineRow(
+ key: ValueKey('machine-${widget.machine.machine.machineId}'),
+ name: widget.machine.machine.displayName,
+ local: _local,
+ annotation: annotation,
+ subtitle: subtitle,
+ action: action,
+ options: widget.options,
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ if (_loading) {
+ return _row(subtitle: const _MachineStatus('Checking password…'));
+ }
+ if (_local && _status == null) {
+ return _row(
+ subtitle: _Feedback(
+ _busy
+ ? 'Saving password…'
+ : _error ?? 'Couldn’t check your password.',
+ error: !_busy,
+ ),
+ action: _busy ? null : _button('Try again', () => unawaited(_load())),
+ );
+ }
+ if (_local && !_editing) {
+ final available = _status!.hasPassword;
+ return _row(
+ annotation: available ? 'This computer · Available' : null,
+ subtitle: _MachineDetails(
+ machine: widget.machine,
+ resources: widget.resources,
+ ),
+ action: _button(
+ available ? 'Change password' : 'Set password',
+ _editPassword,
+ primary: true,
+ ),
+ );
+ }
+ final form = Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ LayoutBuilder(
+ builder: (context, constraints) {
+ final field = ReadlineKeys(
+ controller: _password,
+ enabled: !_busy,
+ onChanged: (_) {
+ if (_error != null) setState(() => _error = null);
+ },
+ child: TextField(
+ key: ValueKey(
+ _local
+ ? 'make-available-password'
+ : 'connect-password-${widget.machineId}-input',
+ ),
+ controller: _password,
+ focusNode: _input,
+ autofocus: widget.autofocus,
+ obscureText: _obscure,
+ readOnly: _busy,
+ autocorrect: false,
+ enableSuggestions: false,
+ style: grid.AppType.monoLabel(),
+ textInputAction: TextInputAction.done,
+ decoration: InputDecoration(
+ hintText: _local ? 'Choose a password' : 'Harness password',
+ hintStyle: grid.AppType.monoLabel(
+ color: grid.AppPalette.textFaint,
+ ),
+ isDense: true,
+ filled: false,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 8,
+ ),
+ border: OutlineInputBorder(
+ borderSide: BorderSide(
+ color: grid.AppPalette.textPrimary.withValues(alpha: .20),
+ ),
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderSide: BorderSide(
+ color: grid.AppPalette.textPrimary.withValues(alpha: .20),
+ ),
+ ),
+ suffixIconConstraints: const BoxConstraints(
+ minWidth: 64,
+ minHeight: 32,
+ ),
+ suffixIcon: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ IconButton(
+ padding: EdgeInsets.zero,
+ constraints: const BoxConstraints.tightFor(
+ width: 32,
+ height: 32,
+ ),
+ tooltip: _obscure ? 'Show password' : 'Hide password',
+ onPressed: () => setState(() => _obscure = !_obscure),
+ icon: Icon(
+ _obscure ? LucideIcons.eye : LucideIcons.eyeOff,
+ semanticLabel: _obscure
+ ? 'Show password'
+ : 'Hide password',
+ size: 15,
+ ),
+ ),
+ IconButton(
+ padding: EdgeInsets.zero,
+ constraints: const BoxConstraints.tightFor(
+ width: 32,
+ height: 32,
+ ),
+ tooltip: 'Password help',
+ isSelected: _showHelp,
+ onPressed: () => setState(() => _showHelp = !_showHelp),
+ icon: const Icon(
+ LucideIcons.circleHelp,
+ semanticLabel: 'Password help',
+ size: 15,
+ ),
+ ),
+ ],
+ ),
+ ),
+ onChanged: (_) {
+ if (_error != null) setState(() => _error = null);
+ },
+ onEditingComplete: () {},
+ onSubmitted: (_) => _submit(),
+ ),
+ );
+ final button = _button(
+ _busy
+ ? (_local ? 'Saving…' : 'Connecting…')
+ : _local
+ ? 'Save'
+ : 'Connect',
+ _busy ? null : _submit,
+ primary: true,
+ );
+ if (constraints.maxWidth <
+ 340 * MediaQuery.textScalerOf(context).scale(1)) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ field,
+ const SizedBox(height: 8),
+ Align(alignment: Alignment.centerLeft, child: button),
+ ],
+ );
+ }
+ return Row(
+ children: [
+ Expanded(child: field),
+ const SizedBox(width: 10),
+ button,
+ ],
+ );
+ },
+ ),
+ if (_error case final error?) ...[
+ const SizedBox(height: 8),
+ _Feedback(error, error: true),
+ ],
+ if (_showHelp) ...[
+ const SizedBox(height: 8),
+ _Detail(
+ _local
+ ? 'Use this password to connect to ${widget.machine.machine.displayName} from your other computers.'
+ : 'On ${widget.machine.machine.displayName}, open Machines → Set password.',
+ ),
+ ],
+ if (_local && _status?.hasPassword == true)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: _button(
+ 'Cancel',
+ _busy
+ ? null
+ : () {
+ setState(() {
+ _editing = false;
+ _password.clear();
+ _error = null;
+ _obscure = true;
+ });
+ },
+ ),
+ ),
+ ],
+ );
+ return TerminalPromptKeys(
+ inputFocus: _input,
+ composing: () => _composing,
+ cancel: widget.onClose,
+ accept: () {
+ if (_input.hasFocus) {
+ _submit();
+ } else {
+ activatePromptControl();
+ }
+ },
+ child: _row(subtitle: form),
+ );
+ }
+}
+
+Widget _button(
+ String label,
+ VoidCallback? onPressed, {
+ Key? key,
+ bool primary = false,
+}) {
+ final button = TextButton(
+ key: key,
+ onPressed: onPressed,
+ style: TextButton.styleFrom(
+ foregroundColor: primary
+ ? grid.AppPalette.textPrimary
+ : grid.AppPalette.textSecondary,
+ backgroundColor: primary
+ ? grid.AppPalette.textPrimary.withValues(alpha: .10)
+ : null,
+ textStyle: grid.AppType.monoLabel(),
+ minimumSize: const Size(0, 32),
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
+ ),
+ child: Text(label),
+ );
+ if (!primary) return button;
+ return Builder(
+ builder: (context) => SizedBox(
+ width: MediaQuery.textScalerOf(context).scale(140),
+ child: button,
+ ),
+ );
+}
+
+class _Detail extends StatelessWidget {
+ const _Detail(this.text);
+ final String text;
+ @override
+ Widget build(BuildContext context) => Text(
+ text,
+ style: grid.AppType.body(color: grid.AppPalette.textSecondary),
+ );
+}
+
+class _Feedback extends StatelessWidget {
+ const _Feedback(this.text, {this.error = false});
+ final String text;
+ final bool error;
+ @override
+ Widget build(BuildContext context) => Semantics(
+ liveRegion: true,
+ child: Text(
+ text,
+ style: _panelText(
+ color: error
+ ? grid.AppTheme.pick(const Color(0xffb24b17), Colors.orangeAccent)
+ : grid.AppTheme.pick(
+ const Color(0xff356522),
+ const Color(0xffa5d786),
+ ),
+ ),
+ ),
+ );
+}
+
+class _CopyButton extends StatefulWidget {
+ const _CopyButton(this.label, this.value, {this.iconOnly = false});
+ final String label, value;
+ final bool iconOnly;
+ @override
+ State<_CopyButton> createState() => _CopyButtonState();
+}
+
+class _CopyButtonState extends State<_CopyButton> {
+ Timer? _timer;
+ String? _message;
+ int _attempt = 0;
+ @override
+ void dispose() {
+ _timer?.cancel();
+ super.dispose();
+ }
+
+ Future<void> _copy() async {
+ final attempt = ++_attempt;
+ try {
+ await Clipboard.setData(ClipboardData(text: widget.value));
+ if (!mounted || attempt != _attempt) return;
+ setState(() => _message = 'Copied');
+ } catch (_) {
+ if (!mounted || attempt != _attempt) return;
+ setState(() => _message = 'Couldn’t copy. Try again');
+ }
+ _timer?.cancel();
+ _timer = Timer(const Duration(seconds: 3), () {
+ if (mounted) setState(() => _message = null);
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) => widget.iconOnly
+ ? IconButton(
+ tooltip: _message ?? widget.label,
+ onPressed: _copy,
+ icon: Icon(
+ _message == 'Copied'
+ ? LucideIcons.check
+ : _message == null
+ ? LucideIcons.copy
+ : LucideIcons.circleAlert,
+ size: 16,
+ semanticLabel: _message ?? widget.label,
+ ),
+ )
+ : _button(_message ?? widget.label, _copy);
+}
+
+TextStyle _panelText({Color? color, FontWeight? weight}) => grid.AppType.label(
+ color: color ?? grid.AppPalette.textPrimary,
+ fontWeight: weight,
+);
diff --git a/desktop/lib/widgets/swarm_dialogs.dart b/desktop/lib/widgets/swarm_dialogs.dart
index 9427f9be9..a23af8e3a 100644
--- a/desktop/lib/widgets/swarm_dialogs.dart
+++ b/desktop/lib/widgets/swarm_dialogs.dart
@@ -6,11 +6,10 @@ import 'package:harness/shared/theme/app_type.dart';
import '../shared/widgets/app_dialog.dart';
import '../shared/widgets/app_select_field.dart';
-import '../screens/login_screen.dart';
import '../state/app_state.dart';
import '../shortcuts/app_keymap.dart';
import '../state/swarm_catalog.dart';
-import 'link_another_machine_dialog.dart';
+import 'machines_panel.dart';
import 'remote_folder_picker.dart';
import 'clone_repository_dialog.dart';
import 'terminal_name_prompt.dart';
@@ -201,27 +200,11 @@ class _ProjectDialogState extends State<_ProjectDialog> {
}
}
-/// Link another machine. The dialog itself lives in
-/// `link_another_machine_dialog.dart`; this name is what every caller — the
-/// Machines menu, ⌘ commands, the machines manager — has always used.
-///
-/// The one thing on this desk that cannot work without an account: machines are
-/// listed, paired and relayed THROUGH it, so a guest is asked to sign in first —
-/// over the desk, and only here, where reaching for another machine is exactly
-/// what they just did. Declining leaves them where they were.
+/// Compatibility entry point: every setup entry opens the same Machines panel.
Future<void> showSwarmLinkDialog(
BuildContext context,
AppNotifier notifier, {
AppKeymap? keymap,
}) async {
- if (notifier.isGuest) {
- final signedIn = await showSignInSheet(
- context,
- notifier,
- reason: 'Your machines live on your account. Sign in to link another one '
- 'to this computer.',
- );
- if (!signedIn || !context.mounted) return;
- }
- return showLinkAnotherMachineDialog(context, notifier, keymap: keymap);
+ await showMachinesPanel(context, notifier, keymap: keymap);
}
diff --git a/desktop/lib/widgets/toolbar_icon.dart b/desktop/lib/widgets/toolbar_icon.dart
new file mode 100644
index 000000000..54bc2b76c
--- /dev/null
+++ b/desktop/lib/widgets/toolbar_icon.dart
@@ -0,0 +1,21 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_svg/flutter_svg.dart';
+
+/// Shared vector marks inherit the toolbar button's quiet or notified tint.
+class ToolbarIcon extends StatelessWidget {
+ const ToolbarIcon({super.key, required this.name});
+
+ final String name;
+
+ @override
+ Widget build(BuildContext context) => SvgPicture.asset(
+ 'assets/${name.toLowerCase()}.svg',
+ width: 20,
+ height: 20,
+ colorFilter: ColorFilter.mode(
+ IconTheme.of(context).color ?? const Color(0xff999999),
+ BlendMode.srcIn,
+ ),
+ semanticsLabel: name,
+ );
+}
diff --git a/desktop/lib/widgets/workspace_welcome.dart b/desktop/lib/widgets/workspace_welcome.dart
index 5759f721b..90acffd0f 100644
--- a/desktop/lib/widgets/workspace_welcome.dart
+++ b/desktop/lib/widgets/workspace_welcome.dart
@@ -18,8 +18,8 @@ class WorkspaceWelcome extends StatelessWidget {
static const _actions = [
('agent.new', 'New Harness', 'to start a new harness'),
('agent.open', 'Open Harness', 'to open a harness'),
+ ('machines.list', 'Machines', 'to connect your machines'),
('app.store', 'Harness Store', 'to browse the harness store'),
- ('keyboard.help', 'Keyboard Shortcuts', 'to see keyboard shortcuts'),
];
@override
diff --git a/desktop/macos/Runner/Base.lproj/MainMenu.xib b/desktop/macos/Runner/Base.lproj/MainMenu.xib
index 5ce309cef..50a7767a1 100644
--- a/desktop/macos/Runner/Base.lproj/MainMenu.xib
+++ b/desktop/macos/Runner/Base.lproj/MainMenu.xib
@@ -302,7 +302,7 @@
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
<items>
- <menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
+ <menuItem title="Minimize" id="OY7-WF-poV">
<connections>
<action selector="performMiniaturize:" target="-1" id="VwT-WD-YPe"/>
</connections>
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index aabda3227..efd83805b 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -24,7 +24,6 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private var closedHistory: [SwarmHistoryEntry] = []
private let historyIcons = SwarmHistoryIcons()
private let modelsMenu = NSMenu(title: "Models")
- private let machinesMenu = NSMenu(title: "Machines")
private var machines: [SwarmMachineEntry] = []
private var subscriptions: [SwarmSubscriptionEntry] = []
private var keymap: HarnessNativeKeymap?
@@ -166,6 +165,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
keymap = map
// Mouse controls teach the effective shortcuts, including user remaps.
strip.newButton.toolTip = "New Tab " + (map.hint(for: "swarm.new", context: "workspace") ?? "")
+ strip.machinesButton.toolTip = "Machines " + (map.hint(for: "machines.list", context: "workspace") ?? "")
strip.storeButton.toolTip = "Harness Store " + (map.hint(for: "app.store", context: "workspace") ?? "")
if let main = NSApp.mainMenu, let window {
let menu = main as? HarnessKeymapMenu ?? HarnessKeymapMenu.replacing(main)
@@ -318,13 +318,13 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
if let view = main.item(withTitle: "View")?.submenu {
view.addItem(.separator())
add(view, "Harnesses Needing Input…", "i", "notifications", [.command, .shift])
+ add(view, "Machines", "m", "machineList")
+ add(view, "Machine Monitor", "", "manageMachines")
}
modelsMenu.autoenablesItems = false
modelsMenu.delegate = self
rebuildModelsMenu()
install(modelsMenu, at: main.items.firstIndex(where: { $0.title == "Window" }) ?? main.numberOfItems)
- rebuildMachinesMenu()
- install(machinesMenu, at: main.items.firstIndex(where: { $0.title == "Window" }) ?? main.numberOfItems)
installTerminalFindMenu(main)
}
@@ -356,140 +356,11 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
let entries = rows.prefix(128).compactMap(SwarmMachineEntry.init)
guard entries != machines else { return }
machines = entries
- rebuildMachinesMenu()
// The Models menu's last row lists these too (see `rebuildModelsMenu`), so it is rebuilt on
// the same change rather than waiting for the next models push to catch up.
rebuildModelsMenu()
}
- private func rebuildMachinesMenu() {
- machinesMenu.removeAllItems()
- machinesMenu.minimumWidth = 0
- let labels = machines.map { machine -> (name: String, owner: String, presence: String, status: String, count: String) in
- (name: SwarmMenuText.fitted(machine.name, width: 200),
- owner: machine.shared && !machine.ownerName.isEmpty ? " · " + SwarmMenuText.fitted(machine.ownerName, width: 140) : "",
- // Node presence ("Online"/"Offline"), shown grey right after the name,
- // independent of the link state on the trailing edge.
- presence: machine.presence,
- status: machine.status,
- count: machine.agentCount.map { "\($0) \($0 == 1 ? "harness" : "harnesses")" } ?? "")
- }
- // Preserve the compact menu's proportions, with the requested extra room.
- // Leading text = name + presence; trailing column = the agent count, or the
- // status word ("Link required"/"Offline"/…) when there is no count.
- let compactEdge = SwarmMenuText.trailingEdge(labels.map {
- ($0.name + $0.owner + ($0.presence.isEmpty ? "" : " " + $0.presence),
- $0.count.isEmpty ? $0.status : $0.count)
- })
- let trailingEdge = ceil((compactEdge + 62) * 1.2) - 62
- // Two doors for one release: Machine Monitor, the harness that manages the fleet by conversation
- // and draws it, and the plain list beneath it. The second is a bridge — it goes when this menu
- // does, along with machines_manager.dart and the "machineList" action.
- let manage = NSMenuItem(title: "Open Machine Monitor…", action: #selector(menuAction(_:)), keyEquivalent: "")
- manage.target = self
- manage.representedObject = "manageMachines"
- manage.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "manageMachines")
- machinesMenu.addItem(manage)
- let manager = NSMenuItem(title: "Open Machines Manager", action: #selector(menuAction(_:)), keyEquivalent: "")
- manager.target = self
- manager.representedObject = "machineList"
- manager.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "machineList")
- machinesMenu.addItem(manager)
- machinesMenu.addItem(.separator())
- var lastSection: Bool? = nil
- for (machine, parts) in zip(machines, labels).sorted(by: { !$0.0.shared && $1.0.shared }) {
- if lastSection != machine.shared {
- if lastSection != nil { machinesMenu.addItem(.separator()) }
- let header = NSMenuItem(title: machine.shared ? "Shared with you" : "Your machines", action: nil, keyEquivalent: "")
- header.isEnabled = false
- machinesMenu.addItem(header)
- lastSection = machine.shared
- }
- let item = NSMenuItem(title: machine.name, action: #selector(machineAction(_:)), keyEquivalent: "")
- item.target = self
- item.representedObject = machine.id
- let paragraph = NSMutableParagraphStyle()
- paragraph.tabStops = [NSTextTab(textAlignment: .right, location: trailingEdge)]
- let label = NSMutableAttributedString(string: parts.name,
- attributes: [.font: NSFont.menuFont(ofSize: 0), .paragraphStyle: paragraph])
- // After the name: the node presence ("Online"). Trailing (tab-aligned
- // right): the agent count, or the link/offline status when there is no
- // count. The two are independent slots, so a machine can read
- // "Online … Link required".
- let afterName = parts.owner + (parts.presence.isEmpty ? "" : " " + parts.presence)
- let trailing = parts.count.isEmpty ? parts.status : parts.count
- label.append(NSAttributedString(string: afterName + "\t" + trailing,
- attributes: [.font: NSFont.menuFont(ofSize: 0), .paragraphStyle: paragraph,
- .foregroundColor: NSColor.secondaryLabelColor]))
- item.attributedTitle = label
- item.image = NSImage(systemSymbolName: machine.shared ? "person.2" : machine.local ? "laptopcomputer" : "desktopcomputer", accessibilityDescription: machine.shared ? "Shared machine" : nil)
- let submenu = NSMenu(title: machine.name)
- for agent in machine.agents {
- let child = NSMenuItem(title: agent.title + (machine.shared ? " · View only" : ""), action: #selector(machineAgentAction(_:)), keyEquivalent: "")
- if agent.stopped && !machine.shared {
- // Still a choice — it resumes — but not an attach, so the row says so in the quieter colour,
- // the way a machine row carries its status after the name.
- let label = NSMutableAttributedString(string: agent.title, attributes: [.font: NSFont.menuFont(ofSize: 0)])
- label.append(NSAttributedString(string: " · stopped",
- attributes: [.font: NSFont.menuFont(ofSize: 0), .foregroundColor: NSColor.secondaryLabelColor]))
- child.attributedTitle = label
- }
- child.target = self
- child.representedObject = ["machineId": machine.id, "agentId": agent.id]
- child.image = historyIcons.image(engine: agent.engine, asset: agent.iconAsset)
- submenu.addItem(child)
- }
- if machine.agents.isEmpty {
- // Presence/online no longer rides in `status` (it moved to its own
- // slot). Link-required wins; a node known to be offline says so; a
- // reachable-or-connecting node is still fetching.
- let title: String
- if machine.agentCount == 0 {
- title = "No harnesses yet"
- } else if machine.linkRequired {
- title = "Link required"
- } else if machine.presence == "Offline" {
- title = "Offline"
- } else {
- title = "Loading harnesses…"
- }
- let empty = NSMenuItem(title: title, action: nil, keyEquivalent: "")
- empty.isEnabled = false
- submenu.addItem(empty)
- }
- if !machine.shared {
- submenu.addItem(.separator())
- let find = NSMenuItem(title: "Find Harnesses…", action: #selector(machineAction(_:)), keyEquivalent: "")
- find.target = self
- find.representedObject = machine.id
- submenu.addItem(find)
- if !machine.local {
- submenu.addItem(.separator())
- let del = NSMenuItem(title: "Delete Machine…", action: #selector(machineDeleteAction(_:)), keyEquivalent: "")
- del.target = self
- del.representedObject = machine.id
- del.image = NSImage(systemSymbolName: "trash", accessibilityDescription: nil)
- submenu.addItem(del)
- }
- }
- item.submenu = submenu
- machinesMenu.addItem(item)
- }
- if machines.isEmpty {
- let empty = NSMenuItem(title: "No Machines Linked", action: nil, keyEquivalent: "")
- empty.isEnabled = false
- machinesMenu.addItem(empty)
- }
- machinesMenu.addItem(.separator())
- for (title, action) in [("Link Machine…", "linkMachine"), ("Refresh Machines", "refreshMachines")] {
- let item = NSMenuItem(title: title, action: #selector(menuAction(_:)), keyEquivalent: "")
- item.target = self
- item.representedObject = action
- item.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + action)
- machinesMenu.addItem(item)
- }
- }
-
/// One heading's worth of the picker: the account's own grid ("Local") or a shared grid, with
/// the models it is serving. `own` picks the heading word; `name` names a shared grid under the
/// "Models shared with you" header, or is empty for the account's own grid.
@@ -1209,7 +1080,7 @@ private final class SwarmHistoryIcons {
/// lib/store/store_mark.dart). Any other path draws the engine's initial,
/// which is how the store tab once read "S".
static func opens(_ asset: String) -> Bool {
- !asset.contains("..") && (asset == "assets/app_icon.png" || asset == "assets/harnesses.png" || asset == "assets/models.png" || asset == "assets/store/polymath.png"
+ !asset.contains("..") && (asset == "assets/app_icon.png" || asset == "assets/harnesses.png" || asset == "assets/machines.svg" || asset == "assets/models.svg" || asset == "assets/harnesses.svg" || asset == "assets/models.png" || asset == "assets/store/polymath.png"
|| asset.hasPrefix("assets/engine-icons/") && asset.hasSuffix(".png"))
}
@@ -1234,7 +1105,13 @@ private final class SwarmHistoryIcons {
if let image = cache.object(forKey: key) { return image }
let size = NSSize(width: pointSize, height: pointSize)
let image: NSImage
- if let asset, SwarmHistoryIcons.opens(asset),
+ if let asset, SwarmHistoryIcons.opens(asset), asset.hasSuffix(".svg"), let url = assetURL(asset),
+ let vector = NSImage(contentsOf: url) {
+ // Preserve the SVG representation so AppKit redraws sharply at any scale.
+ vector.size = size
+ vector.isTemplate = true
+ image = vector
+ } else if let asset, SwarmHistoryIcons.opens(asset),
let url = assetURL(asset),
let source = CGImageSourceCreateWithURL(url as CFURL, nil),
let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, [
@@ -1358,6 +1235,10 @@ private class SwarmIconButton: NSButton {
return true
}
override func draw(_ dirtyRect: NSRect) {
+ if state == .on && isEnabled {
+ NSColor.white.withAlphaComponent(0.08).setFill()
+ NSBezierPath(roundedRect: bounds.insetBy(dx: 1, dy: 1), xRadius: 7, yRadius: 7).fill()
+ }
if showsHoverFill && isEnabled && (hovered || hasKeyboardFocus || isHighlighted) {
NSColor.white.withAlphaComponent(isHighlighted ? 0.10 : 0.05).setFill()
NSBezierPath(roundedRect: bounds.insetBy(dx: 1, dy: 1), xRadius: 7, yRadius: 7).fill()
@@ -1400,10 +1281,14 @@ private final class SwarmStoreButton: SwarmIconButton {
}
}
-private final class SwarmSessionsButton: SwarmIconButton {
- var running = 0 { didSet { needsDisplay = true } }
- var attention = 0 { didSet { needsDisplay = true } }
- var expanded = false { didSet { needsDisplay = true } }
+private class SwarmNoticeButton: SwarmIconButton {
+ var attention = 0 { didSet { contentTintColor = iconTint; needsDisplay = true } }
+ var expanded = false { didSet { contentTintColor = iconTint; needsDisplay = true } }
+
+ var iconTint: NSColor {
+ let bright = isEnabled && (expanded || state == .on || hovered || hasKeyboardFocus || isHighlighted)
+ return NSColor(white: attention > 0 ? 0.96 : bright ? 0.84 : 0.60, alpha: 1)
+ }
var attentionLabel: String? {
attention > 0 ? (attention > 99 ? "99+" : String(attention)) : nil
@@ -1416,6 +1301,7 @@ private final class SwarmSessionsButton: SwarmIconButton {
}
override func draw(_ dirtyRect: NSRect) {
+ if contentTintColor != iconTint { contentTintColor = iconTint }
if expanded {
NSColor.white.withAlphaComponent(0.08).setFill()
NSBezierPath(roundedRect: bounds.insetBy(dx: 1, dy: 1), xRadius: 7, yRadius: 7).fill()
@@ -1436,6 +1322,11 @@ private final class SwarmSessionsButton: SwarmIconButton {
}
}
+}
+
+private final class SwarmSessionsButton: SwarmNoticeButton {
+ var running = 0 { didSet { needsDisplay = true } }
+
func receiveSession() {
guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else { return }
wantsLayer = true
@@ -1479,8 +1370,9 @@ private final class SwarmTabStrip: NSView {
private let scroll = SwarmStripScrollView()
private let document = NSView()
fileprivate let newButton = SwarmIconButton()
+ fileprivate let machinesButton = SwarmNoticeButton()
fileprivate let storeButton = SwarmStoreButton(title: "Harness Store", target: nil, action: nil)
- fileprivate let modelsButton = SwarmIconButton()
+ fileprivate let modelsButton = SwarmNoticeButton()
fileprivate let sessionsButton = SwarmSessionsButton()
private var tabs: [SwarmTabButton] = []
private let icons = SwarmHistoryIcons()
@@ -1520,7 +1412,7 @@ private final class SwarmTabStrip: NSView {
button.isBordered = false
button.title = ""
button.imagePosition = .imageOnly
- button.contentTintColor = palette.accent
+ button.contentTintColor = (button as? SwarmNoticeButton)?.iconTint ?? palette.accent
button.target = self
button.action = action
button.setAccessibilityLabel(label)
@@ -1529,11 +1421,16 @@ private final class SwarmTabStrip: NSView {
button(newButton, "plus", "New Tab", #selector(newSwarm))
newButton.setAccessibilityLabel("New Tab")
newButton.isEnabled = false
- button(sessionsButton, "terminal", "Harness Monitor", #selector(openSessions))
- sessionsButton.image = icons.image(engine: "harnesses", asset: "assets/harnesses.png", pointSize: 24)
+ button(machinesButton, "desktopcomputer", "Machines", #selector(openMachines))
+ machinesButton.image = icons.image(engine: "machines", asset: "assets/machines.svg", pointSize: 20)
+ machinesButton.symbolConfiguration = nil
+ machinesButton.isEnabled = false
+ machinesButton.toolTip = "Machines ⌘M"
+ button(sessionsButton, "terminal", "Harnesses", #selector(openSessions))
+ sessionsButton.image = icons.image(engine: "harnesses", asset: "assets/harnesses.svg", pointSize: 20)
sessionsButton.symbolConfiguration = nil
sessionsButton.isEnabled = false
- sessionsButton.toolTip = "Harness Monitor"
+ sessionsButton.toolTip = "Harnesses"
newButton.toolTip = "New Tab ⌘T"
storeButton.isBordered = false
storeButton.palette = palette
@@ -1545,12 +1442,12 @@ private final class SwarmTabStrip: NSView {
storeButton.toolTip = "Harness Store ⌘S"
storeButton.setAccessibilityLabel("Harness Store")
addSubview(storeButton)
- button(modelsButton, "brain", "AI Models", #selector(openModels))
- modelsButton.image = icons.image(engine: "models", asset: "assets/models.png", pointSize: 20)
+ button(modelsButton, "brain", "Models", #selector(openModels))
+ modelsButton.image = icons.image(engine: "models", asset: "assets/models.svg", pointSize: 20)
modelsButton.symbolConfiguration = nil
modelsButton.isEnabled = false
- modelsButton.toolTip = "AI Models"
- setAccessibilityChildren([scroll, newButton, sessionsButton, modelsButton, storeButton])
+ modelsButton.toolTip = "Models"
+ setAccessibilityChildren([scroll, newButton, machinesButton, modelsButton, sessionsButton, storeButton])
registerForDraggedTypes([swarmPasteboardType])
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
@@ -1560,9 +1457,7 @@ private final class SwarmTabStrip: NSView {
guard nextPalette != palette else { return }
palette = nextPalette
newButton.contentTintColor = palette.accent
- sessionsButton.contentTintColor = palette.accent
storeButton.palette = palette
- modelsButton.contentTintColor = palette.accent
for tab in tabs { tab.palette = palette }
needsDisplay = true
}
@@ -1631,16 +1526,25 @@ private final class SwarmTabStrip: NSView {
// Moving frames alone leaves AppKit's child traversal in insertion order.
document.setAccessibilityChildren(tabs)
newButton.isEnabled = actionsEnabled
+ machinesButton.isEnabled = actionsEnabled
+ machinesButton.state = state["machinesOpen"] as? Bool == true ? .on : .off
+ machinesButton.attention = max(0, state["machineNotices"] as? Int ?? 0)
+ let machineExpanded = machinesButton.state == .on ? "Expanded" : "Collapsed"
+ machinesButton.setAccessibilityValue(machinesButton.attention > 0
+ ? "\(machineExpanded), \(machinesButton.attention) new \(machinesButton.attention == 1 ? "computer" : "computers") ready to connect" : machineExpanded)
storeButton.isEnabled = actionsEnabled
modelsButton.isEnabled = actionsEnabled
- let modelReady = state["localModelReady"] as? Bool == true
- modelsButton.toolTip = modelReady ? "AI Models · Your local model is running" : "AI Models"
- modelsButton.setAccessibilityValue(state["modelsOpen"] as? Bool == true ? "Expanded" : "Collapsed")
+ modelsButton.state = state["modelsOpen"] as? Bool == true ? .on : .off
+ modelsButton.attention = max(0, state["modelNotices"] as? Int ?? 0)
+ modelsButton.toolTip = "Models"
+ let modelExpanded = modelsButton.state == .on ? "Expanded" : "Collapsed"
+ modelsButton.setAccessibilityValue(modelsButton.attention > 0
+ ? "\(modelExpanded), \(modelsButton.attention) \(modelsButton.attention == 1 ? "model" : "models") ready to use" : modelExpanded)
sessionsButton.isEnabled = actionsEnabled
sessionsButton.running = state["runningSessions"] as? Int ?? 0
sessionsButton.expanded = state["sessionsOpen"] as? Bool == true
let expandedState = sessionsButton.expanded ? "Expanded" : "Collapsed"
- sessionsButton.toolTip = sessionsButton.running > 0 ? "Harness Monitor · \(sessionsButton.running) running" : "Harness Monitor"
+ sessionsButton.toolTip = sessionsButton.running > 0 ? "Harnesses · \(sessionsButton.running) running" : "Harnesses"
let attention = state["attention"] as? Int ?? 0
// What the badge COUNTS is `unread` — harnesses carrying news nobody has looked at, which
// includes the ones that simply finished. `attention` is the narrower "blocked, waiting on a
@@ -1653,8 +1557,8 @@ private final class SwarmTabStrip: NSView {
sessionsButton.setAccessibilityValue(unread > 0 ? "\(expandedState), \(unreadState)" : expandedState)
if unread > 0 {
sessionsButton.toolTip = attention > 0
- ? "Harness Monitor · \(unreadState) · \(attentionState)"
- : "Harness Monitor · \(unreadState)"
+ ? "Harnesses · \(unreadState) · \(attentionState)"
+ : "Harnesses · \(unreadState)"
}
needsLayout = true
layoutSubtreeIfNeeded()
@@ -1687,7 +1591,8 @@ private final class SwarmTabStrip: NSView {
// where a full strip can still be dragged and double-clicked to zoom
// (owner, 2026-09-15); tabs shrink and then scroll instead of taking it.
let grip: CGFloat = spacious ? 84 : 44
- let available = max(32, bounds.width - leading - trailing - (newButton.isHidden ? 0 : 36) - grip - storeWidth - modelsWidth - 52)
+ // Reserve three adjacent controls: Machines, Models, Harnesses.
+ let available = max(32, bounds.width - leading - trailing - (newButton.isHidden ? 0 : 36) - grip - storeWidth - modelsWidth - 88)
// As in Chrome, tabs keep shrinking until they are only their mark, so thirty tabs still sit in
// one strip with nothing hidden; only past that does the strip scroll (the wheel scrolls it).
let width = min(220, max(min(SwarmTabButton.minimumWidth, available), available / CGFloat(max(1, tabs.count))))
@@ -1703,8 +1608,9 @@ private final class SwarmTabStrip: NSView {
let buttonY = (bounds.height - 28) / 2
newButton.frame = NSRect(x: leading + occupied + 4, y: buttonY, width: 28, height: 28)
storeButton.frame = NSRect(x: bounds.width - trailing - storeWidth, y: buttonY, width: storeWidth, height: 28)
- modelsButton.frame = NSRect(x: storeButton.frame.minX - modelsWidth - 8, y: buttonY, width: modelsWidth, height: 28)
- sessionsButton.frame = NSRect(x: modelsButton.frame.minX - 36, y: buttonY, width: 28, height: 28)
+ sessionsButton.frame = NSRect(x: storeButton.frame.minX - 36, y: buttonY, width: 28, height: 28)
+ modelsButton.frame = NSRect(x: sessionsButton.frame.minX - modelsWidth - 8, y: buttonY, width: modelsWidth, height: 28)
+ machinesButton.frame = NSRect(x: modelsButton.frame.minX - 36, y: buttonY, width: 28, height: 28)
let geometryChanged = scroll.frame.size != previousScrollSize || document.frame.size != previousDocumentSize
if let active, revealActiveAfterLayout || (activeWasVisible && (geometryChanged || tabOrderChanged)) {
document.scrollToVisible(active.frame)
@@ -1745,6 +1651,9 @@ private final class SwarmTabStrip: NSView {
@objc private func openStore() {
if actionsEnabled { emit?("store", nil) }
}
+ @objc private func openMachines() {
+ if actionsEnabled { emit?("machineList", nil) }
+ }
@objc private func openSessions() {
if actionsEnabled { emit?("sessions", nil) }
}
diff --git a/desktop/pubspec.lock b/desktop/pubspec.lock
index def02c47b..9f33908d8 100644
--- a/desktop/pubspec.lock
+++ b/desktop/pubspec.lock
@@ -251,6 +251,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.6.1"
+ flutter_svg:
+ dependency: "direct main"
+ description:
+ name: flutter_svg
+ sha256: "35882981abcbfb8c15b286f0cd690ff25bac12d95eff3e25ee207f37d4c42e7f"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.3.0"
flutter_test:
dependency: "direct dev"
description: flutter
@@ -407,6 +415,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.1"
+ path_parsing:
+ dependency: transitive
+ description:
+ name: path_parsing
+ sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.0"
petitparser:
dependency: transitive
description:
@@ -660,6 +676,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.6"
+ vector_graphics:
+ dependency: transitive
+ description:
+ name: vector_graphics
+ sha256: "9d0e3b9cb16542ad660daee871e726a10d13a93b7b5391677c3160e8f5e83935"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.3"
+ vector_graphics_codec:
+ dependency: transitive
+ description:
+ name: vector_graphics_codec
+ sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.13"
+ vector_graphics_compiler:
+ dependency: transitive
+ description:
+ name: vector_graphics_compiler
+ sha256: "4dca4feb77dc3ec7f6e27e49c53241eb8217f55e4f9b12599a27f8903bca5682"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.3.0"
vector_math:
dependency: transitive
description:
diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yaml
index 32b2391a8..a0e797dbd 100644
--- a/desktop/pubspec.yaml
+++ b/desktop/pubspec.yaml
@@ -37,6 +37,7 @@ dependencies:
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
lucide_icons_flutter: ^3.1.15
+ flutter_svg: ^2.3.0
dio: ^5.11.0
web_socket_channel: ^3.0.3
flutter_riverpod: ^2.6.1
@@ -107,6 +108,9 @@ flutter:
# the material Icons class.
uses-material-design: true
assets:
+ - assets/machines.svg
+ - assets/models.svg
+ - assets/harnesses.svg
- assets/engine-icons/
- assets/store/
- assets/store/projects/
diff --git a/desktop/test/boot_flow_widget_test.dart b/desktop/test/boot_flow_widget_test.dart
index 7ca8dbbd4..fb4a76a2b 100644
--- a/desktop/test/boot_flow_widget_test.dart
+++ b/desktop/test/boot_flow_widget_test.dart
@@ -910,11 +910,16 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
// With no machine to open an agent on, the start page's New goes to
- // linking one, with the desktop and server setup choices in its picker.
- expect(find.text('Link another machine'), findsOneWidget);
- expect(find.text('Set up a desktop'), findsOneWidget);
- expect(find.text('Set up a server over SSH'), findsOneWidget);
- await tester.tap(find.text('esc close'));
+ // the Machines panel, with desktop and server instructions one click away.
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ await tester.tap(find.text('Add a second machine'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('1. Open Harness on your other computer.'),
+ findsOneWidget,
+ );
+ expect(find.text('Set up a server…'), findsOneWidget);
+ await tester.tap(find.byTooltip('Close Machines'));
await tester.pumpAndSettle();
expect(app.panes, isEmpty);
await tester.pumpWidget(const SizedBox());
@@ -1072,61 +1077,66 @@ void main() {
},
);
- testWidgets('unlinked remote with a pending agent shows the link form', (
- tester,
- ) async {
- final app = makeNotifier(AppStatus.authenticated);
- const machine = Machine(
- machineId: 'unlinked-machine',
- apiKey: '',
- authMode: MachineAuthMode.remote,
- name: 'remote-mac',
- status: 'online',
- );
- final state = MachineState(machine)
- ..nodeOnline = false
- ..needsLink = true
- ..activeAgentId = 'previous-agent'
- ..pendingOfflineAgentId = 'previous-agent'
- ..agentLoadStatus = AgentLoadStatus.needsLink
- ..agents = [
- Agent.fromJson({
- 'id': 'previous-agent',
- 'name': 'previous-session',
- 'engine': 'claude',
- 'terminal': {
- 'runtimes': [
- {'backend': 'tmux', 'paneId': '%1'},
- ],
- },
- }),
- ];
- app.machines = [machine];
- app.machineStates[machine.machineId] = state;
- app.expandedMachines.add(machine.machineId);
- app.selectedMachineId = machine.machineId;
- await app.selectAgent(machine.machineId, 'previous-agent');
+ testWidgets(
+ 'offline unlinked remote with a pending agent opens machine recovery',
+ (tester) async {
+ final app = makeNotifier(AppStatus.authenticated);
+ const machine = Machine(
+ machineId: 'unlinked-machine',
+ apiKey: '',
+ authMode: MachineAuthMode.remote,
+ name: 'remote-mac',
+ status: 'online',
+ );
+ final state = MachineState(machine)
+ ..nodeOnline = false
+ ..needsLink = true
+ ..activeAgentId = 'previous-agent'
+ ..pendingOfflineAgentId = 'previous-agent'
+ ..agentLoadStatus = AgentLoadStatus.needsLink
+ ..agents = [
+ Agent.fromJson({
+ 'id': 'previous-agent',
+ 'name': 'previous-session',
+ 'engine': 'claude',
+ 'terminal': {
+ 'runtimes': [
+ {'backend': 'tmux', 'paneId': '%1'},
+ ],
+ },
+ }),
+ ];
+ app.machines = [machine];
+ app.machineStates[machine.machineId] = state;
+ app.expandedMachines.add(machine.machineId);
+ app.selectedMachineId = machine.machineId;
+ await app.selectAgent(machine.machineId, 'previous-agent');
- await tester.pumpWidget(
- ProviderScope(
- overrides: [appStateProvider.overrideWithValue(app)],
- child: HarnessApp(authenticatedScreen: _swarm),
- ),
- );
- // The link screen now arrives as a popup (a post-frame callback pushes a showDialog route
- // with its own entrance transition), not a synchronous inline build — one pump() is no
- // longer enough to see it.
- await tester.pumpAndSettle();
+ await tester.pumpWidget(
+ ProviderScope(
+ overrides: [appStateProvider.overrideWithValue(app)],
+ child: HarnessApp(authenticatedScreen: _swarm),
+ ),
+ );
+ // The panel and its password field receive focus after the first frame.
+ await tester.pumpAndSettle();
- expect(find.text('Link this machine'), findsOneWidget);
- expect(
- find.text('Enter the remote password set on this machine.'),
- findsOneWidget,
- );
- expect(find.text('Harness is offline'), findsNothing);
- expect(find.text('harness start'), findsNothing);
- app.dispose();
- });
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is TextField &&
+ widget.decoration?.hintText == 'Harness password',
+ ),
+ findsNothing,
+ );
+ expect(find.textContaining('Offline'), findsOneWidget);
+ expect(find.text('Harness is offline'), findsNothing);
+ expect(find.text('harness start'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
testWidgets('clicking the link-required prompt opens the link screen', (
tester,
@@ -1167,26 +1177,25 @@ void main() {
),
);
await tester.pump();
- expect(find.text('Link this machine'), findsNothing);
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
- await chord(tester, LogicalKeyboardKey.keyP);
- await tester.enterText(
- find.byKey(const ValueKey('harness-start-search')),
- '> link machine',
- );
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await chord(tester, LogicalKeyboardKey.keyM);
await tester.pumpAndSettle();
await tester.ensureVisible(find.text('link-mac'));
await tester.tap(find.text('link-mac'));
// Same popup-transition reasoning as above.
await tester.pumpAndSettle();
- expect(find.text('Link this machine'), findsOneWidget);
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
expect(
- find.text('Enter the remote password set on this machine.'),
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is TextField &&
+ widget.decoration?.hintText == 'Harness password',
+ ),
findsOneWidget,
);
+ await tester.pumpWidget(const SizedBox());
app.dispose();
});
@@ -1250,21 +1259,15 @@ void main() {
),
);
await tester.pump();
- expect(find.text('Link this machine'), findsNothing);
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
- await chord(tester, LogicalKeyboardKey.keyP);
- await tester.enterText(
- find.byKey(const ValueKey('harness-start-search')),
- '> link machine',
- );
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await chord(tester, LogicalKeyboardKey.keyM);
await tester.pumpAndSettle();
await tester.ensureVisible(find.text('link-mac'));
await tester.tap(find.text('link-mac'));
await tester.pumpAndSettle();
- expect(find.text('Link this machine'), findsOneWidget);
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
// No second pane was opened for the popup — just the one terminal pane that was
// already there.
expect(app.allPanes, hasLength(1));
@@ -1274,6 +1277,7 @@ void main() {
find.text('link-mac is not linked to this computer yet.'),
findsNothing,
);
+ await tester.pumpWidget(const SizedBox());
app.dispose();
});
}
diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dart
index 2b3fdd936..5207a5f34 100644
--- a/desktop/test/first_workspace_test.dart
+++ b/desktop/test/first_workspace_test.dart
@@ -514,7 +514,7 @@ void main() {
find.byKey(const ValueKey('swarm-new-pane-button')),
findsNothing,
);
- expect(find.byTooltip('Harness Monitor'), findsOneWidget);
+ expect(find.byTooltip('Harnesses'), findsOneWidget);
expect(
find.byKey(const ValueKey('swarm-new-harness-button')),
findsNothing,
diff --git a/desktop/test/harness_session_manager_test.dart b/desktop/test/harness_session_manager_test.dart
index 2842fbb4a..ef492a6f3 100644
--- a/desktop/test/harness_session_manager_test.dart
+++ b/desktop/test/harness_session_manager_test.dart
@@ -69,7 +69,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.byTooltip('Harness Monitor'));
+ await tester.tap(find.byTooltip('Harnesses'));
await tester.pumpAndSettle();
}
@@ -230,13 +230,13 @@ void main() {
await app.addAgentToSwarm('m', 'a0');
app.machineStates['m']!.blockedAgents['a0'] = question('a0');
await mount(tester, app);
- await tester.tap(find.byTooltip('Harness Monitor'));
+ await tester.tap(find.byTooltip('Harnesses'));
await tester.pump(const Duration(milliseconds: 300));
expect(
find.byKey(const ValueKey('swarm-notifications-button')),
findsNothing,
);
- final managerIcon = tester.getRect(find.byTooltip('Harness Monitor'));
+ final managerIcon = tester.getRect(find.byTooltip('Harnesses'));
expect(
managerIcon.right,
lessThan(
@@ -373,7 +373,7 @@ void main() {
(tester) async {
await open(tester);
expect(find.byType(HarnessSessionManager), findsOneWidget);
- expect(find.text('Harness Monitor'), findsOneWidget);
+ expect(find.text('Harnesses'), findsOneWidget);
expect(find.text('Running 1'), findsOneWidget);
expect(find.text('Paused 1'), findsOneWidget);
expect(find.text('Ready'), findsNothing);
@@ -513,7 +513,7 @@ void main() {
await tester.pump();
connection.stopReplies.single.complete({'deleted': true});
await tester.pump();
- await tester.tap(find.byTooltip('Harness Monitor'));
+ await tester.tap(find.byTooltip('Harnesses'));
await tester.pump();
expect(toggle('a0'), findsNothing);
expect(find.byTooltip('Pausing…'), findsOneWidget);
@@ -904,7 +904,7 @@ void main() {
expect(app.panes, [sibling]);
expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
expect(connection.stops, isEmpty);
- await tester.tap(find.byTooltip('Harness Monitor'));
+ await tester.tap(find.byTooltip('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 a3dfcbcea..1dc976444 100644
--- a/desktop/test/keymap_host_test.dart
+++ b/desktop/test/keymap_host_test.dart
@@ -76,6 +76,7 @@ void main() {
('cmd+p', 'navigation.commands'),
('cmd+shift+j', 'navigation.command_bar'),
('cmd+s', 'app.store'),
+ ('cmd+m', 'machines.list'),
('cmd+shift+l', 'pane.layout'),
('cmd+b', 'task.route'),
('cmd+shift+w', 'pane.close'),
@@ -97,7 +98,7 @@ void main() {
final id = command(stroke.toString());
expect(harnessCommandById[id]?.action, shortcut.action);
}
- for (final retired in ['cmd+shift+h', 'cmd+shift+k']) {
+ for (final retired in ['cmd+shift+h', 'cmd+shift+k', 'cmd+u']) {
expect(command(retired), isNull, reason: retired);
}
expect(command('cmd+alt+left'), isNull);
@@ -136,7 +137,7 @@ void main() {
final map = ResolvedKeymap(
harnessDefaultBindings,
KeymapConfig.parse(
- '{"bindings":[{"keys":"cmd+h","command":"pane.focus_left"},{"keys":"cmd+k","command":null},{"keys":"cmd+k c","command":"pane.focus_right"}]}',
+ '{"bindings":[{"keys":"cmd+h","command":"pane.focus_left"},{"keys":"cmd+m","command":"machines.list"},{"keys":"cmd+k","command":null},{"keys":"cmd+k c","command":"pane.focus_right"}]}',
commands: harnessCommandById.keys.toSet(),
),
);
diff --git a/desktop/test/link_another_machine_test.dart b/desktop/test/link_another_machine_test.dart
index afd6a1be5..00deefcc7 100644
--- a/desktop/test/link_another_machine_test.dart
+++ b/desktop/test/link_another_machine_test.dart
@@ -290,6 +290,29 @@ void main() {
{"keys":"f9","command":"picker.refresh","when":"picker"}
]}''');
await _mount(tester, app, keymap: map, manager: manager);
+ if (manager) {
+ // The legacy entry forwards to the new Machines panel and keeps
+ // the live picker keymap across that nested route.
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.text('Machines'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.keyR, cmd: true);
+ expect(app.refreshes, 0);
+ await key(tester, LogicalKeyboardKey.f9);
+ expect(app.refreshes, 1);
+ map.apply(
+ '{"bindings":[{"keys":"f4","command":"picker.cancel","when":"picker"}]}',
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.f7);
+ expect(find.text('Machines'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.f4);
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ expect(find.text('Machines'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ return;
+ }
await key(tester, LogicalKeyboardKey.enter);
await key(tester, LogicalKeyboardKey.escape);
expect(_input, findsOneWidget);
diff --git a/desktop/test/machine_resources_test.dart b/desktop/test/machine_resources_test.dart
new file mode 100644
index 000000000..18e899bfd
--- /dev/null
+++ b/desktop/test/machine_resources_test.dart
@@ -0,0 +1,221 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/machine_resources.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/e2ee/envelope.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ bool ready = true;
+ @override
+ bool get isReady => ready;
+ final calls = <(String, Duration)>[];
+ Map<String, dynamic> reply = {};
+ Completer<Map<String, dynamic>>? pending;
+ Object? failure;
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ calls.add((type, timeout));
+ if (failure != null) throw failure!;
+ return pending?.future ?? reply;
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test(
+ 'readings preserve valid zero and partial data without inventing values',
+ () {
+ final empty = MachineResources.fromJson({});
+ expect(empty.cpuPercent, isNull);
+ expect(empty.memoryUsedBytes, isNull);
+ final idle = MachineResources.fromJson({
+ 'cpuPercent': 0,
+ 'memoryUsedBytes': 0,
+ 'memoryTotalBytes': 1024,
+ });
+ expect(idle.cpuPercent, 0);
+ expect(idle.memoryUsedBytes, 0);
+ expect(idle.memoryTotalBytes, 1024);
+ final partial = MachineResources.fromJson({'cpuPercent': 18.5});
+ expect(partial.cpuPercent, 18.5);
+ expect(partial.memoryTotalBytes, isNull);
+ },
+ );
+
+ test('invalid readings stay unknown', () {
+ for (final value in [-1, 101, double.nan, double.infinity, '18', null]) {
+ expect(
+ MachineResources.fromJson({'cpuPercent': value}).cpuPercent,
+ isNull,
+ );
+ }
+ for (final json in [
+ {'memoryUsedBytes': 2, 'memoryTotalBytes': 1},
+ {'memoryUsedBytes': 0, 'memoryTotalBytes': 0},
+ {'memoryUsedBytes': -1, 'memoryTotalBytes': 1},
+ {'memoryUsedBytes': 1, 'memoryTotalBytes': double.infinity},
+ {'memoryUsedBytes': 1},
+ ]) {
+ final reading = MachineResources.fromJson(json);
+ expect(reading.memoryUsedBytes, isNull);
+ expect(reading.memoryTotalBytes, isNull);
+ }
+ });
+
+ group('reading over the existing machine connection', () {
+ test(
+ 'closing the app ignores pending stats and a closing link prompt',
+ () async {
+ final connection = _Connection()
+ ..pending = Completer<Map<String, dynamic>>();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ connectionForTest: (_) => connection,
+ );
+ app.machineStates['m'] = MachineState(
+ const Machine(
+ machineId: 'm',
+ name: 'Fixture',
+ authMode: MachineAuthMode.remote,
+ ),
+ )..connectionStatus = ConnectionStatus.connected;
+ final read = app.readMachineResources('m');
+ app.dispose();
+ app.dismissLinkPrompt('m');
+ connection.pending!.complete({'cpuPercent': 99});
+ expect(await read, isNull);
+ expect(await app.readMachineResources('m'), isNull);
+ connection.close();
+ },
+ );
+ late AppNotifier app;
+ late _Connection connection;
+ late MachineState machine;
+ var connections = 0;
+ setUp(() {
+ connections = 0;
+ connection = _Connection();
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ connectionForTest: (_) {
+ connections++;
+ return connection;
+ },
+ );
+ machine =
+ MachineState(
+ const Machine(
+ machineId: 'm',
+ name: 'Computer',
+ authMode: MachineAuthMode.remote,
+ ),
+ )
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected;
+ app.machineStates['m'] = machine;
+ });
+ tearDown(() {
+ app.dispose();
+ connection.close();
+ });
+
+ test('uses the encrypted RPC with a short timeout', () async {
+ connection.reply = {'cpuPercent': 24};
+ expect((await app.readMachineResources('m'))!.cpuPercent, 24);
+ expect(connection.calls, [
+ ('machine_resources', const Duration(seconds: 3)),
+ ]);
+ expect(encryptedDownTypes, contains('machine_resources'));
+ });
+
+ for (final change in [
+ 'offline',
+ 'unlinked',
+ 'disconnected',
+ 'removed',
+ 'reconnected',
+ ]) {
+ test(
+ 'ignores a delayed resource reply after the machine is $change',
+ () async {
+ connection.pending = Completer<Map<String, dynamic>>();
+ final read = app.readMachineResources('m');
+ switch (change) {
+ case 'offline':
+ machine.nodeOnline = false;
+ case 'unlinked':
+ machine.needsLink = true;
+ case 'disconnected':
+ machine.connectionStatus = ConnectionStatus.disconnected;
+ case 'removed':
+ app.machineStates.remove('m');
+ case 'reconnected':
+ app.onMachineConnectedForTest('m');
+ }
+ connection.pending!.complete({'cpuPercent': 99});
+ expect(await read, isNull);
+ },
+ );
+ }
+
+ test('never starts a connection to missing, offline, unlinked, or shared machines', () async {
+ expect(await app.readMachineResources('missing'), isNull);
+ machine.nodeOnline = false;
+ expect(await app.readMachineResources('m'), isNull);
+ machine.nodeOnline = true;
+ machine.needsLink = true;
+ expect(await app.readMachineResources('m'), isNull);
+ machine.needsLink = false;
+ machine.connectionStatus = ConnectionStatus.disconnected;
+ expect(await app.readMachineResources('m'), isNull);
+ app.machineStates['m'] = MachineState(
+ const Machine(
+ machineId: 'm',
+ name: 'Shared',
+ isShared: true,
+ authMode: MachineAuthMode.remote,
+ ),
+ )..connectionStatus = ConnectionStatus.connected;
+ expect(await app.readMachineResources('m'), isNull);
+ expect(connections, 0);
+ expect(connection.calls, isEmpty);
+ });
+
+ test(
+ 'unready connections and older daemons leave readings unknown',
+ () async {
+ connection.ready = false;
+ expect(await app.readMachineResources('m'), isNull);
+ expect(connection.calls, isEmpty);
+ connection.ready = true;
+ connection.reply = {'error': 'UNKNOWN_TYPE'};
+ expect(await app.readMachineResources('m'), isNull);
+ connection.failure = TimeoutException('Older daemon');
+ expect(await app.readMachineResources('m'), isNull);
+ },
+ );
+ });
+}
diff --git a/desktop/test/machines_manager_keyboard_test.dart b/desktop/test/machines_manager_keyboard_test.dart
index 3e3a05981..ae693d6a4 100644
--- a/desktop/test/machines_manager_keyboard_test.dart
+++ b/desktop/test/machines_manager_keyboard_test.dart
@@ -246,7 +246,7 @@ void main() {
app.edits.deleteReply!.complete();
await tester.pumpAndSettle();
expect(app.stateOf('work'), isNull);
- expect(find.text('Machines Manager'), findsOneWidget);
+ expect(find.text('Machines'), findsOneWidget);
expect(find.text('Workstation deleted.'), findsOneWidget);
},
);
@@ -343,7 +343,7 @@ void main() {
await _mount(tester, app, keymap: map);
await key(tester, LogicalKeyboardKey.enter);
await key(tester, LogicalKeyboardKey.escape);
- expect(find.text('Machines Manager'), findsOneWidget);
+ expect(find.text('Machines'), findsOneWidget);
await key(tester, LogicalKeyboardKey.f8);
await tester.pumpAndSettle();
await key(tester, LogicalKeyboardKey.f8);
@@ -377,7 +377,7 @@ void main() {
expect(app.edits.renames, [('work', 'Office')]);
await key(tester, LogicalKeyboardKey.f4);
await tester.pumpAndSettle();
- expect(find.text('Machines Manager'), findsOneWidget);
+ expect(find.text('Machines'), findsOneWidget);
},
);
diff --git a/desktop/test/machines_manager_test.dart b/desktop/test/machines_manager_test.dart
index 5d40dec6d..cc82a79a7 100644
--- a/desktop/test/machines_manager_test.dart
+++ b/desktop/test/machines_manager_test.dart
@@ -4,6 +4,13 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/api/api_client.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/models/models_panel.dart';
+import 'package:harness/models/local_model.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/new_harness_box.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:xterm/xterm.dart';
@@ -11,6 +18,7 @@ import 'keymap_runtime_test.dart' show native;
import 'keymap_host_test.dart' show key;
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
+import 'support/model_manager.dart';
class _MachineApi extends ApiClient {
_MachineApi() : super(config: AppConfig.dev, session: AuthSession());
@@ -29,9 +37,355 @@ class _MachineApi extends ApiClient {
}
void main() {
+ testWidgets('machine and model badges acknowledge independently', (
+ tester,
+ ) async {
+ final app = ModelManagerTestApp(ModelManagerConnection());
+ app.stateOf('m')!.nodeOnline = true;
+ app.stateOf('other')!
+ ..nodeOnline = true
+ ..needsLink = true;
+ app.machineStates['offline'] =
+ MachineState(
+ const Machine(
+ machineId: 'offline',
+ name: 'Offline',
+ authMode: MachineAuthMode.remote,
+ ),
+ )
+ ..nodeOnline = false
+ ..needsLink = true;
+ app.machineStates['shared'] =
+ MachineState(
+ const Machine(
+ machineId: 'shared',
+ name: 'Shared',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ ),
+ )
+ ..nodeOnline = true
+ ..needsLink = true;
+ final ready = <String, dynamic>{
+ 'id': 'ready',
+ 'name': 'Ready model',
+ 'state': 'running',
+ 'operation': <String, dynamic>{
+ 'id': 'download-1',
+ 'modelId': 'ready',
+ 'action': 'start',
+ 'stage': 'verifying',
+ 'phase': 'done',
+ },
+ };
+ app.localInventory = {
+ 'models': [ready],
+ };
+ app.modelManager
+ ..localModels = [LocalModel.fromJson(ready)]
+ ..loaded = true;
+ await mount(tester, app);
+ await tester.pumpAndSettle();
+ Badge badge(String name) =>
+ tester.widget<Badge>(find.byKey(ValueKey('swarm-$name-badge')));
+ expect(badge('machines').isLabelVisible, isTrue);
+ expect((badge('machines').label as Text).data, '1');
+ expect(badge('models').isLabelVisible, isTrue);
+ await tester.tap(find.byKey(const ValueKey('swarm-machines-button')));
+ await tester.pumpAndSettle();
+ expect(badge('machines').isLabelVisible, isFalse);
+ expect(badge('models').isLabelVisible, isTrue);
+ await tester.tap(find.byKey(const ValueKey('swarm-models-button')));
+ await tester.pumpAndSettle();
+ expect(badge('models').isLabelVisible, isFalse);
+ expect(find.text('Models'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ app.localInventory = {
+ 'models': [
+ ready,
+ {'id': 'release', 'name': 'New release'},
+ ],
+ };
+ await app.modelManager.refresh();
+ await tester.pumpAndSettle();
+ expect(badge('models').isLabelVisible, isFalse);
+ await tester.tap(find.byKey(const ValueKey('swarm-models-button')));
+ await tester.pumpAndSettle();
+ expect(find.text('New'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
+ for (final nativeTabs in [false, true]) {
+ testWidgets(
+ 'toolbar panels switch in one click without stacking (native=$nativeTabs)',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!.nodeOnline = true;
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', input));
+ await mount(tester, app, nativeTabs: nativeTabs);
+ final buttons = {
+ 'machineList': find.byKey(const ValueKey('swarm-machines-button')),
+ 'models': find.byKey(const ValueKey('swarm-models-button')),
+ 'sessions': find.byTooltip('Harnesses'),
+ };
+ final panels = {
+ 'machineList': find.byKey(const ValueKey('machines-panel')),
+ 'models': find.byType(ModelsPanel),
+ 'sessions': find.byKey(const ValueKey('session-manager')),
+ };
+ Future<void> open(String command) async {
+ if (nativeTabs) {
+ final action = native(tester, command);
+ await tester.pumpAndSettle();
+ await action;
+ } else {
+ await tester.tap(buttons[command]!);
+ await tester.pumpAndSettle();
+ }
+ }
+
+ for (final from in panels.keys) {
+ for (final to in panels.keys) {
+ await open(from);
+ await open(to);
+ for (final entry in panels.entries) {
+ expect(
+ entry.value,
+ from != to && entry.key == to ? findsOneWidget : findsNothing,
+ reason: '$from → $to should leave only the chosen panel open',
+ );
+ }
+ if (from != to) {
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ }
+ expect(tester.takeException(), isNull);
+ expect(
+ input.map((frame) => frame.bytes.toList()).toList(),
+ isEmpty,
+ reason: '$from → $to must not send panel keys to the terminal',
+ );
+ }
+ }
+ tester.testTextInput.enterText('x');
+ await tester.idle();
+ expect(String.fromCharCodes(input.single.bytes), 'x');
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+ }
+
+ testWidgets('native Machines, Models, and Harnesses share one panel', (
+ tester,
+ ) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ final updates = <Map>[];
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
+ call,
+ ) async {
+ if (call.method == 'update') updates.add(call.arguments as Map);
+ return null;
+ });
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ null,
+ ),
+ );
+ final app = createApp();
+ app.stateOf('m')!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app, nativeTabs: true);
+ var action = native(tester, 'machineList');
+ await tester.pumpAndSettle();
+ await action;
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ expect(updates.last['enabled'], isTrue);
+ expect(updates.last['machinesOpen'], isTrue);
+ action = native(tester, 'machineList');
+ await tester.pumpAndSettle();
+ await action;
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ action = native(tester, 'machineList');
+ await tester.pumpAndSettle();
+ await action;
+ action = native(tester, 'models');
+ await tester.pumpAndSettle();
+ await action;
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ expect(find.byType(ModelsPanel), findsOneWidget);
+ expect(updates.last['machinesOpen'], isFalse);
+ expect(updates.last['modelsOpen'], isTrue);
+ action = native(tester, 'machineList');
+ await tester.pumpAndSettle();
+ await action;
+ expect(find.byType(ModelsPanel), findsNothing);
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ expect(updates.last['modelsOpen'], isFalse);
+ action = native(tester, 'sessions');
+ await tester.pumpAndSettle();
+ await action;
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ expect(find.byKey(const ValueKey('session-manager')), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
+ testWidgets(
+ 'Cmd M and the toolbar open Machines and restore terminal input',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!.nodeOnline = true;
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', input));
+ await mount(tester, app);
+ await key(tester, LogicalKeyboardKey.keyM, cmd: true);
+ await tester.pumpAndSettle();
+ expect(find.text('Machines'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ final machines = find.byKey(const ValueKey('swarm-machines-button'));
+ final models = find.byKey(const ValueKey('swarm-models-button'));
+ expect(
+ tester.getCenter(machines).dx,
+ lessThan(tester.getCenter(models).dx),
+ );
+ expect(
+ tester.getCenter(models).dx,
+ lessThan(tester.getCenter(find.byTooltip('Harnesses')).dx),
+ );
+ await tester.tap(machines);
+ await tester.pumpAndSettle();
+ expect(find.text('Machines'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ tester.testTextInput.enterText('x');
+ await tester.idle();
+ expect(String.fromCharCodes(input.single.bytes), 'x');
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
+ testWidgets(
+ 'clicking a linked machine scopes work by ID even when names match',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected;
+ app.machineStates['other'] =
+ MachineState(
+ const Machine(
+ machineId: 'other',
+ name: 'Test host',
+ authMode: MachineAuthMode.remote,
+ ),
+ )
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = const [
+ Agent(id: 'unrelated', name: 'Task from another Test host'),
+ ];
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ await tester.tap(find.byKey(const ValueKey('swarm-machines-button')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('machine-m')));
+ await tester.pumpAndSettle();
+ expect(find.text('Machines'), findsNothing);
+ final search = tester.widget<TextField>(
+ find.byKey(const ValueKey('swarm-search-input')),
+ );
+ expect(search.controller!.text, isEmpty);
+ expect(find.text('Harnesses · Test host'), findsOneWidget);
+ expect(find.text('Task from another Test host'), findsNothing);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Task from another',
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Task from another Test host'), findsNothing);
+ expect(search.focusNode!.hasFocus, isTrue);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
+ for (final nativeTabs in [false, true]) {
+ testWidgets(
+ 'New terminal without a machine opens setup and preserves the tab (native=$nativeTabs)',
+ (tester) async {
+ final app = createApp();
+ app.machines = [];
+ app.machineStates.clear();
+ final tab = app.activeSwarm;
+ await mount(tester, app, nativeTabs: nativeTabs);
+
+ if (nativeTabs) {
+ final action = native(tester, 'newTerminal');
+ await tester.pumpAndSettle();
+ await action;
+ } else {
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true, shift: true);
+ await tester.pumpAndSettle();
+ }
+
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ expect(find.text('Add a second machine'), findsOneWidget);
+ expect(app.activeSwarm, same(tab));
+ expect(app.panes, isEmpty);
+ expect(tester.takeException(), isNull);
+
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ expect(app.activeSwarm, same(tab));
+ expect(app.panes, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+ }
+
+ testWidgets('a fresh machine opens creation with that machine selected', (
+ tester,
+ ) async {
+ final previous = newHarnessOpensInBox;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = previous);
+ final app = createApp();
+ const fresh = Machine(
+ machineId: 'fresh',
+ name: 'New Mac mini',
+ authMode: MachineAuthMode.remote,
+ );
+ app.machines = [...app.machines, fresh];
+ app.machineStates['fresh'] = MachineState(fresh)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected;
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ await tester.tap(find.byKey(const ValueKey('swarm-machines-button')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('New harness'));
+ await tester.pumpAndSettle();
+ final box = tester.widget<NewHarnessBox>(find.byType(NewHarnessBox));
+ expect(box.controller.machineId, 'fresh');
+ expect(box.controller.placement, HarnessPlacement.currentTab);
+ expect(app.panes.single.machineId, 'm', reason: 'Existing work stays open');
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
for (final fail in [false, true]) {
testWidgets(
- 'Machines menu opens Rename and updates names (failure=$fail)',
+ 'Machines toolbar opens Rename and updates names (failure=$fail)',
(tester) async {
const channel = MethodChannel('harness/swarm_tabs');
final updates = <Map>[];
@@ -57,12 +411,12 @@ void main() {
final input = <TerminalBinaryFrame>[];
app.adoptSessionForTest(terminal('a0', input));
await mount(tester, app, nativeTabs: true);
- // 'manageMachines' now opens the Machines harness; the plain list is 'machineList'.
+ // The native toolbar and View menu both open the simplified panel.
final opened = native(tester, 'machineList');
await tester.pumpAndSettle();
await opened;
- expect(find.text('Machines Manager'), findsOneWidget);
- await key(tester, LogicalKeyboardKey.enter);
+ expect(find.text('Machines'), findsOneWidget);
+ await tester.tap(find.byTooltip('Options for Test host'));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename'));
await tester.pumpAndSettle();
@@ -86,11 +440,9 @@ void main() {
await tester.pumpAndSettle();
}
expect(find.text('Rename Machine'), findsNothing);
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
expect(
find.descendant(
- of: find.byKey(const ValueKey('managed-machine-m')),
+ of: find.byKey(const ValueKey('machine-m')),
matching: find.text('Office Mac'),
),
findsOneWidget,
@@ -99,7 +451,7 @@ void main() {
expect((updates.last['machines'] as List).single['name'], 'Office Mac');
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(find.text('Machines Manager'), findsNothing);
+ expect(find.text('Machines'), findsNothing);
expect(
tester
.widget<TerminalView>(find.byType(TerminalView))
diff --git a/desktop/test/machines_panel_test.dart b/desktop/test/machines_panel_test.dart
new file mode 100644
index 000000000..4b7d032de
--- /dev/null
+++ b/desktop/test/machines_panel_test.dart
@@ -0,0 +1,1112 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_link.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/machine_resources.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/machines_panel.dart';
+import 'package:harness/widgets/toolbar_icon.dart';
+import 'package:harness/widgets/workspace_welcome.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'support/password_cli.dart';
+import 'support/real_fonts.dart';
+
+class _Cli extends PasswordCli {
+ final connections = <(String, String)>[];
+ Completer<CliLinkConnectResult>? connectReply;
+ String? connectError;
+ @override
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ }) async {
+ connections.add((machineId, password));
+ onProgress?.call('exchanging');
+ return connectReply?.future ??
+ CliLinkConnectResult(error: connectError, linkedMachineId: machineId);
+ }
+}
+
+class _App extends AppNotifier {
+ _App(_Cli cli)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLink: cli,
+ peerLinks: cli,
+ );
+ String? inventoryError;
+ int refreshes = 0;
+ final deletes = <String>[];
+ @override
+ Future<String?> deleteMachine(String id) async {
+ deletes.add(id);
+ machineStates.remove(id);
+ machines = machineStates.values.map((s) => s.machine).toList();
+ notifyListeners();
+ return null;
+ }
+
+ final resourceReadIds = <String>[];
+ final resourceValues = <String, MachineResources?>{};
+ final resourceReplies = <String, Completer<MachineResources?>>{};
+ @override
+ Future<MachineResources?> readMachineResources(String id) async {
+ resourceReadIds.add(id);
+ return resourceReplies[id]?.future ?? resourceValues[id];
+ }
+
+ @override
+ String? get machineListError => inventoryError;
+ @override
+ Future<void> retryMachines() async {
+ refreshes++;
+ }
+
+ void add(
+ String id,
+ String name, {
+ bool local = false,
+ bool linked = false,
+ bool online = true,
+ }) {
+ final machine = Machine(
+ machineId: id,
+ name: name,
+ authMode: MachineAuthMode.remote,
+ );
+ machineStates[id] = MachineState(machine)
+ ..localOnly = local
+ ..nodeOnline = online
+ ..needsLink = !linked && !local
+ ..agentLoadStatus = linked || local
+ ? AgentLoadStatus.loaded
+ : AgentLoadStatus.needsLink
+ ..connectionStatus = linked || local
+ ? ConnectionStatus.connected
+ : ConnectionStatus.disconnected;
+ machines = machineStates.values.map((s) => s.machine).toList();
+ notifyListeners();
+ }
+
+ void connected(String id) {
+ stateOf(id)!.connectionStatus = ConnectionStatus.connected;
+ stateOf(id)!.agentLoadStatus = AgentLoadStatus.loaded;
+ notifyListeners();
+ }
+}
+
+void main() {
+ late _Cli cli;
+ late _App app;
+ final captureKey = GlobalKey();
+ String? opened;
+ setUp(() {
+ cli = _Cli();
+ app = _App(cli)..add('local', 'M2', local: true);
+ opened = null;
+ });
+ tearDown(() => app.dispose());
+
+ Future<void> mount(
+ WidgetTester tester, {
+ Size size = const Size(1000, 900),
+ double scale = 1,
+ Brightness brightness = Brightness.dark,
+ AppKeymap? keymap,
+ bool workspace = false,
+ }) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ if (Platform.environment['HARNESS_MACHINES_CAPTURE_DIR'] != null) {
+ await tester.runAsync(() async {
+ if (Platform.isMacOS) {
+ final bytes = ByteData.sublistView(
+ await File('/System/Library/Fonts/Menlo.ttc').readAsBytes(),
+ );
+ for (final family in [
+ '.AppleSystemUIFontMonospaced',
+ 'SF Mono',
+ 'Menlo',
+ ]) {
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ final sans = ByteData.sublistView(
+ await File('/System/Library/Fonts/Supplemental/Arial.ttf')
+ .readAsBytes(),
+ );
+ for (final family in [
+ '.AppleSystemUIFont',
+ 'SF Pro Text',
+ 'Roboto',
+ ]) {
+ await (FontLoader(family)..addFont(Future.value(sans))).load();
+ }
+ } else {
+ await loadRealFonts();
+ }
+ final font = FontLoader('MaterialIcons');
+ font.addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'));
+ await font.load();
+ await (FontLoader('packages/lucide_icons_flutter/Lucide')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/lucide.ttf',
+ ),
+ ))
+ .load();
+ });
+ }
+ final home = workspace
+ ? SwarmScreen(notifier: app, nativeTabs: false)
+ : Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () async {
+ opened = await showMachinesPanel(context, app);
+ },
+ child: const Text('open machines'),
+ ),
+ ),
+ );
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: captureKey,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: keymap == null
+ ? home
+ : KeymapProvider(
+ keymap: keymap,
+ child: KeymapHost(
+ keymap: keymap,
+ actions: const {},
+ enabled: () => false,
+ child: home,
+ ),
+ ),
+ ),
+ ),
+ );
+ if (workspace &&
+ Platform.environment['HARNESS_MACHINES_CAPTURE_DIR'] != null) {
+ await tester.runAsync(
+ () => precacheImage(
+ const AssetImage('assets/store/polymath.png'),
+ tester.element(find.byType(SwarmScreen)),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+ await tester.tap(
+ workspace
+ ? find.byKey(const ValueKey('swarm-machines-button'))
+ : find.text('open machines'),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> tap(WidgetTester tester, Finder target) async {
+ await tester.ensureVisible(target);
+ await tester.tap(target);
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> capture(WidgetTester tester, String name) async {
+ final dir = Platform.environment['HARNESS_MACHINES_CAPTURE_DIR'];
+ if (dir == null) return;
+ await tester.runAsync(() async {
+ final image =
+ await (captureKey.currentContext!.findRenderObject()
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 2);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ Directory(dir).createSync(recursive: true);
+ File('$dir/$name.png').writeAsBytesSync(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ final localInput = find.byKey(const ValueKey('make-available-password'));
+ final remoteInput = find.byKey(
+ const ValueKey('connect-password-remote-input'),
+ );
+
+ testWidgets(
+ 'toolbar panel is anchored, resizes, and closes outside without dimming work',
+ (tester) async {
+ final previous = newHarnessOpensInBox;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = previous);
+ app.add('remote', 'Mac mini');
+ app.add('office', 'iMac · Office', linked: true);
+ app.stateOf('office')!.agents = List.generate(
+ 8,
+ (i) => Agent(id: 'office-$i', name: 'Work $i'),
+ );
+ app.stateOf('local')!.agents = List.generate(
+ 12,
+ (i) => Agent(id: 'local-$i', name: 'Work $i'),
+ );
+ app.resourceValues.addAll({
+ 'local': const MachineResources(
+ cpuPercent: 18,
+ memoryUsedBytes: 10 * 1024 * 1024 * 1024,
+ memoryTotalBytes: 32 * 1024 * 1024 * 1024,
+ ),
+ 'office': const MachineResources(
+ cpuPercent: 42,
+ memoryUsedBytes: 24 * 1024 * 1024 * 1024,
+ memoryTotalBytes: 64 * 1024 * 1024 * 1024,
+ ),
+ });
+ app.add('server', 'Build server', online: false);
+ await mount(tester, size: const Size(1280, 800), workspace: true);
+ final panel = find.byKey(const ValueKey('machines-panel'));
+ final icon = find.byKey(const ValueKey('swarm-machines-button'));
+ expect(find.byType(Dialog), findsNothing);
+ for (final barrier in tester.widgetList<ModalBarrier>(
+ find.byType(ModalBarrier),
+ )) {
+ expect(
+ barrier.color?.a ?? 0,
+ 0,
+ reason: 'The workspace stays undimmed',
+ );
+ }
+ expect(
+ tester.getRect(panel).top,
+ greaterThan(tester.getRect(icon).bottom),
+ );
+ expect(tester.getRect(panel).right, closeTo(1270, 2));
+ expect(tester.widget<IconButton>(icon).isSelected, isTrue);
+ expect(remoteInput, findsNothing);
+ expect(localInput, findsNothing);
+ expect(find.text('Set password'), findsOneWidget);
+ expect(find.text('View harnesses'), findsNothing);
+ expect(
+ tester.getTopLeft(find.text('M2')).dy,
+ lessThan(tester.getTopLeft(find.text('Mac mini')).dy),
+ );
+ expect(
+ tester.getTopLeft(find.text('Mac mini')).dy,
+ lessThan(tester.getTopLeft(find.text('iMac · Office')).dy),
+ );
+ expect(
+ tester.getTopLeft(find.text('iMac · Office')).dy,
+ lessThan(tester.getTopLeft(find.text('Build server')).dy),
+ );
+ expect(
+ find.text('12 harnesses · CPU 18% · RAM 10/32 GB'),
+ findsOneWidget,
+ );
+ expect(find.text('8 harnesses · CPU 42% · RAM 24/64 GB'), findsOneWidget);
+ expect(find.text('Connected'), findsNothing);
+ expect(app.resourceReadIds, unorderedEquals(['local', 'office']));
+ final widths = ['Set password', 'Connect'].map(
+ (label) => tester
+ .getSize(
+ find.ancestor(
+ of: find.text(label),
+ matching: find.byType(TextButton),
+ ),
+ )
+ .width,
+ );
+ expect(widths.toSet(), hasLength(1));
+ for (final id in ['remote', 'office', 'server']) {
+ expect(
+ tester.getSize(find.byKey(ValueKey('machine-$id'))).height,
+ lessThan(85),
+ );
+ }
+ expect(
+ find.byKey(const ValueKey('connect-machine-remote')),
+ findsOneWidget,
+ );
+ expect(find.byKey(const ValueKey('machine-office')), findsOneWidget);
+ await capture(tester, 'machines-toolbar-panel');
+ await tap(tester, find.text('Set password'));
+ expect(tester.widget<TextField>(localInput).focusNode!.hasFocus, isTrue);
+ await capture(tester, 'machines-toolbar-set-password');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tap(tester, icon);
+ expect(localInput, findsNothing);
+ await tap(tester, find.byKey(const ValueKey('connect-machine-remote')));
+ expect(tester.widget<TextField>(remoteInput).focusNode!.hasFocus, isTrue);
+ await capture(tester, 'machines-toolbar-connect');
+ tester.view.physicalSize = const Size(760, 620);
+ await tester.pumpAndSettle();
+ expect(tester.getRect(panel).right, closeTo(750, 2));
+ expect(tester.getRect(panel).bottom, lessThanOrEqualTo(620));
+ expect(tester.takeException(), isNull);
+ await tester.tapAt(const Offset(30, 200));
+ await tester.pumpAndSettle();
+ expect(panel, findsNothing);
+ expect(tester.widget<IconButton>(icon).isSelected, isFalse);
+ await mount(tester, workspace: true, brightness: Brightness.light);
+ expect(find.byType(ToolbarIcon), findsNWidgets(3));
+ expect(panel, findsOneWidget);
+ await tap(tester, find.byTooltip('Close Machines'));
+ expect(icon.hitTestable(), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'Set password reveals the password field and Save makes this computer available',
+ (tester) async {
+ await mount(tester);
+ expect(find.text('Add a second machine'), findsOneWidget);
+ expect(localInput, findsNothing);
+ expect(find.text('Save'), findsNothing);
+ expect(find.text('Set password'), findsOneWidget);
+ expect(
+ find.text('2. Open Machines and choose Set password.'),
+ findsNothing,
+ );
+ await capture(tester, 'first-machine');
+ await tap(tester, find.byTooltip('Add a machine'));
+ expect(
+ find.text('2. Open Machines and choose Set password.'),
+ findsOneWidget,
+ );
+ await capture(tester, 'desktop-setup');
+ await tap(tester, find.text('Set password'));
+ expect(localInput, findsOneWidget);
+ expect(tester.widget<TextField>(localInput).focusNode!.hasFocus, isTrue);
+ await capture(tester, 'first-machine-setup');
+ await tester.enterText(localInput, 'fixture reusable password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(cli.passwords, ['fixture reusable password']);
+ expect(find.textContaining('This computer · Available'), findsOneWidget);
+ expect(localInput, findsNothing);
+ await capture(tester, 'available-machine');
+ await tap(tester, find.text('Change password'));
+ expect(tester.widget<TextField>(localInput).controller!.text, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'new machine appears live; retry password and open it from the same panel',
+ (tester) async {
+ await mount(tester);
+ app.add('remote', 'Mac mini');
+ await tester.pumpAndSettle();
+ expect(remoteInput, findsNothing);
+ await tap(tester, find.byKey(const ValueKey('connect-machine-remote')));
+ expect(remoteInput, findsOneWidget);
+ expect(
+ find.text('On Mac mini, open Machines → Set password.'),
+ findsNothing,
+ );
+ await tap(
+ tester,
+ find.descendant(
+ of: find.byKey(const ValueKey('machine-remote')),
+ matching: find.byTooltip('Password help'),
+ ),
+ );
+ expect(
+ find.text('On Mac mini, open Machines → Set password.'),
+ findsOneWidget,
+ );
+ await capture(tester, 'connect-machine');
+ cli.connectError = 'Incorrect password. Try again.';
+ await tester.enterText(remoteInput, 'fixture wrong password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text(cli.connectError!), findsOneWidget);
+ expect(find.text('Machines'), findsOneWidget);
+ cli.connectError = null;
+ await tester.enterText(remoteInput, 'fixture correct password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.stateOf('remote')!.needsLink, isFalse);
+ app.connected('remote');
+ await tester.pumpAndSettle();
+ expect(find.text('Connected'), findsNothing);
+ expect(
+ tester
+ .widget<Text>(find.byKey(const ValueKey('machine-stats-remote')))
+ .data,
+ '0 harnesses · CPU — · RAM —',
+ );
+ expect(cli.connections, [
+ ('remote', 'fixture wrong password'),
+ ('remote', 'fixture correct password'),
+ ]);
+ expect(
+ cli.passwords,
+ isEmpty,
+ reason: 'Connecting out never requires setting a local password',
+ );
+ await capture(tester, 'connected-machine');
+ await tap(tester, find.text('New harness'));
+ expect(opened, 'remote');
+ expect(find.text('Machines'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'password save continues across closing and reopening without duplicate submission',
+ (tester) async {
+ cli.setReply = Completer<RemotePasswordSetResult>();
+ await mount(tester);
+ await tap(tester, find.text('Set password'));
+ await tester.enterText(localInput, 'fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(cli.passwords, hasLength(1));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tap(tester, find.text('open machines'));
+ expect(find.text('Saving password…'), findsOneWidget);
+ cli.setReply!.complete(const RemotePasswordSetResult());
+ await tester.pumpAndSettle();
+ expect(find.textContaining('This computer · Available'), findsOneWidget);
+ expect(cli.passwords, hasLength(1));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('another arrival never replaces the password being typed', (
+ tester,
+ ) async {
+ app.add('remote', 'Mac mini');
+ await mount(tester);
+ await tap(tester, find.byKey(const ValueKey('connect-machine-remote')));
+ expect(tester.widget<TextField>(remoteInput).focusNode!.hasFocus, isTrue);
+ await tester.enterText(remoteInput, 'fixture password');
+ app.add('another', 'A build server');
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(remoteInput).controller!.text,
+ 'fixture password',
+ );
+ expect(tester.widget<TextField>(remoteInput).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(cli.connections, [('remote', 'fixture password')]);
+ expect(app.stateOf('another')!.needsLink, isTrue);
+ await tap(tester, find.byKey(const ValueKey('connect-machine-another')));
+ final another = find.byKey(
+ const ValueKey('connect-password-another-input'),
+ );
+ expect(tester.widget<TextField>(another).focusNode!.hasFocus, isTrue);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('connection continues across closing and reopening', (
+ tester,
+ ) async {
+ app.add('remote', 'Mac mini');
+ cli.connectReply = Completer<CliLinkConnectResult>();
+ await mount(tester);
+ await tap(tester, find.byKey(const ValueKey('connect-machine-remote')));
+ await tester.enterText(remoteInput, 'fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tap(tester, find.text('open machines'));
+ expect(tester.widget<TextField>(remoteInput).readOnly, isTrue);
+ expect(tester.widget<TextField>(remoteInput).controller!.text, isEmpty);
+ cli.connectReply!.complete(
+ const CliLinkConnectResult(linkedMachineId: 'remote'),
+ );
+ await tester.pumpAndSettle();
+ app.connected('remote');
+ await tester.pumpAndSettle();
+ expect(find.text('Connected'), findsNothing);
+ expect(
+ tester
+ .widget<Text>(find.byKey(const ValueKey('machine-stats-remote')))
+ .data,
+ '0 harnesses · CPU — · RAM —',
+ );
+ expect(cli.connections, hasLength(1));
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'loading, inventory failure, and password failure never look like an empty account',
+ (tester) async {
+ app.machinesLoading = true;
+ cli.status = const RemotePasswordStatus(error: 'CLI unavailable');
+ await mount(tester);
+ expect(find.text('Looking for your machines…'), findsOneWidget);
+ expect(
+ find.text('1. Open Harness on your other computer.'),
+ findsNothing,
+ );
+ expect(localInput, findsNothing);
+ expect(find.text('CLI unavailable'), findsOneWidget);
+ app.machinesLoading = false;
+ app.inventoryError = 'Network unavailable';
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining('Couldn’t update your machines.'),
+ findsOneWidget,
+ );
+ await tap(tester, find.text('Try again').last);
+ expect(app.refreshes, 1);
+ expect(
+ find.text('1. Open Harness on your other computer.'),
+ findsNothing,
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'offline machine keeps clear recovery and no password submission',
+ (tester) async {
+ app.add('remote', 'Mac mini', online: false);
+ await mount(tester);
+ expect(find.textContaining('Offline'), findsOneWidget);
+ expect(
+ find.byTooltip('Open Harness on Mac mini to bring it online.'),
+ findsOneWidget,
+ );
+ expect(remoteInput, findsNothing);
+ expect(find.byKey(const ValueKey('open-machine-remote')), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'guest sees sign-in and remains on the same panel when signed in',
+ (tester) async {
+ app.signedIn = false;
+ await mount(tester);
+ expect(find.text('Sign in'), findsOneWidget);
+ expect(localInput, findsNothing);
+ app.signedIn = true;
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(localInput, findsNothing);
+ expect(find.text('Set password'), findsOneWidget);
+ await tap(tester, find.byTooltip('Add a machine'));
+ expect(
+ find.text('1. Open Harness on your other computer.'),
+ findsOneWidget,
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'custom prompt keys and composing text do not accidentally submit',
+ (tester) async {
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ map.apply(
+ '{"bindings":[{"when":"picker","keys":"enter","command":null},{"when":"picker","keys":"ctrl+s","command":"picker.accept"}]}',
+ );
+ await mount(tester, keymap: map);
+ await tap(tester, find.text('Set password'));
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.keyS, ctrl: true);
+ expect(tester.widget<TextField>(localInput).obscureText, isFalse);
+ await tester.enterText(localInput, 'fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(cli.passwords, isEmpty);
+ final controller = tester.widget<TextField>(localInput).controller!;
+ controller.value = const TextEditingValue(
+ text: 'fixture password',
+ selection: TextSelection.collapsed(offset: 7),
+ composing: TextRange(start: 0, end: 7),
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.text('Machines'), findsOneWidget);
+ controller.value = controller.value.copyWith(composing: TextRange.empty);
+ await key(tester, LogicalKeyboardKey.keyS, ctrl: true);
+ await tester.pumpAndSettle();
+ expect(cli.passwords, ['fixture password']);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'setup and forms remain usable in a narrow window at large text size',
+ (tester) async {
+ await mount(tester, size: const Size(460, 740), scale: 1.6);
+ await tap(tester, find.byTooltip('Add a machine'));
+ await capture(tester, 'narrow-setup');
+ await tap(tester, find.text('Set up a server…'));
+ expect(tester.takeException(), isNull);
+ app.add('remote', 'A machine with a long descriptive name');
+ await tester.pumpAndSettle();
+ await tap(tester, find.byKey(const ValueKey('connect-machine-remote')));
+ await tester.ensureVisible(remoteInput);
+ await tester.enterText(remoteInput, 'fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(cli.connections, hasLength(1));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'stats ignore late offline replies and stop polling when the panel closes',
+ (tester) async {
+ app.add('remote', 'Mac mini', linked: true);
+ app.resourceReplies['remote'] = Completer<MachineResources?>();
+ await mount(tester);
+ app.notifyListeners();
+ await tester.pump();
+ expect(app.resourceReadIds.where((id) => id == 'remote'), hasLength(1));
+ app.stateOf('remote')!.nodeOnline = false;
+ app.notifyListeners();
+ await tester.pump();
+ app.resourceReplies
+ .remove('remote')!
+ .complete(const MachineResources(cpuPercent: 92));
+ await tester.pumpAndSettle();
+ final stats = find.byKey(const ValueKey('machine-stats-remote'));
+ expect(tester.widget<Text>(stats).data, '— harnesses · CPU — · RAM —');
+ app.resourceValues['remote'] = const MachineResources(cpuPercent: 7);
+ app.stateOf('remote')!.nodeOnline = true;
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(tester.widget<Text>(stats).data, '0 harnesses · CPU 7% · RAM —');
+ final reads = app.resourceReadIds.length;
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.pump(const Duration(minutes: 1));
+ app.notifyListeners();
+ await tester.pump();
+ expect(app.resourceReadIds, hasLength(reads));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'resource polling pauses behind connection settings and resumes on return',
+ (tester) async {
+ await mount(tester);
+ final reads = app.resourceReadIds.length;
+ await tap(tester, find.byTooltip('Options for M2'));
+ await tap(tester, find.text('Connection settings…'));
+ await tester.pump(const Duration(minutes: 1));
+ expect(app.resourceReadIds, hasLength(reads));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(app.resourceReadIds.length, greaterThan(reads));
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'a replacement machine cannot inherit cached stats or a delayed reply',
+ (tester) async {
+ app.add('remote', 'Mac mini', linked: true);
+ final oldReply = Completer<MachineResources?>();
+ app.resourceReplies['remote'] = oldReply;
+ await mount(tester);
+ app.resourceReplies.remove('remote');
+ app.resourceValues['remote'] = const MachineResources(cpuPercent: 7);
+ app.add('remote', 'Replacement', linked: true);
+ await tester.pumpAndSettle();
+ oldReply.complete(const MachineResources(cpuPercent: 99));
+ await tester.pumpAndSettle();
+ final stats = find.byKey(const ValueKey('machine-stats-remote'));
+ expect(tester.widget<Text>(stats).data, '0 harnesses · CPU 7% · RAM —');
+ expect(app.resourceReadIds.where((id) => id == 'remote'), hasLength(2));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'guest sign-in can be cancelled and successful sign-in returns to machines',
+ (tester) async {
+ app.signedIn = false;
+ await mount(tester);
+ await tap(tester, find.text('Sign in'));
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ await tap(tester, find.byTooltip('Close'));
+ expect(find.text('Sign in'), findsOneWidget);
+ expect(app.refreshes, 0);
+ await tap(tester, find.text('Sign in'));
+ app.signedIn = true;
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(find.text('Set password'), findsOneWidget);
+ expect(app.refreshes, 1);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'starting inventory, account instructions and shared machines stay clear',
+ (tester) async {
+ app.machineStates.clear();
+ app.machines = [];
+ app.machinesLoading = true;
+ app.currentUser = const CurrentUserProfile(email: '[email protected]');
+ await mount(tester);
+ expect(find.text('Starting Harness…'), findsOneWidget);
+ expect(find.text('Looking for your machines…'), findsOneWidget);
+ await tap(tester, find.text('Add a second machine'));
+ expect(find.text('Sign in as [email protected].'), findsOneWidget);
+ await tap(tester, find.text('Set up a server…'));
+ expect(find.text('Sign in as [email protected].'), findsOneWidget);
+ await tap(tester, find.text('Hide server setup'));
+ await tap(tester, find.byTooltip('Hide setup steps'));
+ app.add('remote', 'Shared work', linked: true);
+ final shared = app.stateOf('remote')!;
+ app.machineStates['remote'] = MachineState(
+ const Machine(
+ machineId: 'remote',
+ name: 'Shared work',
+ isShared: true,
+ authMode: MachineAuthMode.remote,
+ ),
+ )..connectionStatus = shared.connectionStatus;
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Shared with you'), findsOneWidget);
+ expect(find.byTooltip('Options for Shared work'), findsNothing);
+ expect(find.text('View harnesses'), findsNothing);
+ await tap(tester, find.text('Shared work'));
+ expect(opened, 'remote');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'removing a machine requires the existing confirmation and returns to the list',
+ (tester) async {
+ app.add('remote', 'Mac mini');
+ await mount(tester);
+ await tap(tester, find.byTooltip('Options for Mac mini'));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.text('Mac mini'), findsOneWidget);
+ await tap(tester, find.byTooltip('Options for Mac mini'));
+ await tap(tester, find.text('Remove from account…'));
+ expect(app.deletes, isEmpty);
+ await tap(tester, find.text('Cancel'));
+ expect(find.text('Mac mini'), findsOneWidget);
+ await tap(tester, find.byTooltip('Options for Mac mini'));
+ await tap(tester, find.text('Remove from account…'));
+ await tap(tester, find.byKey(const Key('machine-delete-confirm')));
+ expect(app.deletes, ['remote']);
+ expect(find.text('Mac mini'), findsNothing);
+ expect(find.text('Add a second machine'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'password validation, visibility, help and cancel keep values private',
+ (tester) async {
+ cli.status = const RemotePasswordStatus(hasPassword: true);
+ await mount(tester);
+ await tap(tester, find.text('Change password'));
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Enter a password.'), findsOneWidget);
+ expect(cli.passwords, isEmpty);
+ await tester.enterText(localInput, 'fixture');
+ await tester.pump();
+ expect(find.text('Enter a password.'), findsNothing);
+ await tap(tester, find.byTooltip('Show password'));
+ expect(tester.widget<TextField>(localInput).obscureText, isFalse);
+ await tap(tester, find.byTooltip('Hide password'));
+ expect(tester.widget<TextField>(localInput).obscureText, isTrue);
+ tester.widget<TextField>(localInput).focusNode!.requestFocus();
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(localInput).obscureText, isFalse);
+ await tap(tester, find.byTooltip('Password help'));
+ expect(
+ find.text(
+ 'Use this password to connect to M2 from your other computers.',
+ ),
+ findsOneWidget,
+ );
+ final field = tester.widget<TextField>(localInput);
+ field.controller!.text = 'line one\nline two';
+ await tap(tester, find.text('Save'));
+ expect(find.text('Use a password on one line.'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.keyU, ctrl: true);
+ await tester.pump();
+ expect(find.text('Use a password on one line.'), findsNothing);
+ await tap(tester, find.text('Cancel'));
+ expect(localInput, findsNothing);
+ await tap(tester, find.text('Change password'));
+ expect(tester.widget<TextField>(localInput).controller!.text, isEmpty);
+ // The platform's Done action uses the same validation and submission.
+ await tester.enterText(localInput, 'fixture replacement');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(cli.passwords, ['fixture replacement']);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'failed password status retries and a reopened failed save can be cancelled',
+ (tester) async {
+ cli.status = const RemotePasswordStatus(error: 'Status unavailable');
+ await mount(tester);
+ expect(find.text('Status unavailable'), findsOneWidget);
+ cli.status = const RemotePasswordStatus(hasPassword: true);
+ await tap(tester, find.text('Try again'));
+ await tap(tester, find.text('Change password'));
+ cli.setReply = Completer<RemotePasswordSetResult>();
+ await tester.enterText(localInput, 'fixture replacement');
+ await tap(tester, find.text('Save'));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tap(tester, find.text('open machines'));
+ expect(find.text('Saving password…'), findsOneWidget);
+ cli.setReply!.complete(
+ const RemotePasswordSetResult(error: 'Save unavailable'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Save unavailable'), findsOneWidget);
+ expect(localInput, findsOneWidget);
+ await tap(tester, find.text('Cancel'));
+ expect(find.text('Change password'), findsOneWidget);
+ expect(cli.passwords, ['fixture replacement']);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'copy actions recover, ignore older results and reset their feedback',
+ (tester) async {
+ final copies = <String>[];
+ final replies = <Completer<Object?>>[];
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method != 'Clipboard.setData') return null;
+ copies.add((call.arguments as Map)['text'] as String);
+ final reply = Completer<Object?>();
+ replies.add(reply);
+ return reply.future;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ null,
+ ),
+ );
+ await mount(tester);
+ await tap(tester, find.text('Add a second machine'));
+ await tap(tester, find.text('Copy download link'));
+ replies.last.completeError(
+ PlatformException(code: 'clipboard-unavailable'),
+ );
+ await tester.pumpAndSettle();
+ await tap(tester, find.text('Couldn’t copy. Try again'));
+ final older = replies.last;
+ await tap(tester, find.text('Couldn’t copy. Try again'));
+ replies.last.complete(null);
+ await tester.pumpAndSettle();
+ older.completeError(PlatformException(code: 'late-error'));
+ await tester.pumpAndSettle();
+ expect(find.text('Copied'), findsOneWidget);
+ expect(copies.toSet(), hasLength(1));
+ expect(Uri.parse(copies.first).scheme, 'https');
+ await tester.pump(const Duration(seconds: 3));
+ expect(find.text('Copy download link'), findsOneWidget);
+ await tap(tester, find.text('Set up a server…'));
+ await tap(tester, find.byTooltip('Copy commands'));
+ expect(copies.last, contains('harness login'));
+ expect(copies.last, contains('harness start'));
+ await capture(tester, 'server-setup');
+ replies.last.completeError(
+ PlatformException(code: 'clipboard-unavailable'),
+ );
+ await tester.pumpAndSettle();
+ await tap(tester, find.byTooltip('Couldn’t copy. Try again'));
+ replies.last.complete(null);
+ await tester.pumpAndSettle();
+ expect(find.byTooltip('Copied'), findsOneWidget);
+ await tester.pump(const Duration(seconds: 3));
+ await tap(tester, find.byTooltip('Copy commands'));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ replies.last.complete(null);
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'desktop setup leads with the app and recovers from browser failures',
+ (tester) async {
+ const channel = MethodChannel('plugins.flutter.io/url_launcher');
+ final launches = <String>[];
+ Object? result = false;
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
+ call,
+ ) async {
+ launches.add((call.arguments as Map)['url'] as String);
+ if (result is Exception) {
+ throw result;
+ }
+ if (result is Completer<bool>) {
+ return result.future;
+ }
+ return result;
+ });
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ null,
+ ),
+ );
+ await mount(tester);
+ await tap(tester, find.text('Add a second machine'));
+ expect(
+ find.text('1. Open Harness on your other computer.'),
+ findsOneWidget,
+ );
+ expect(find.textContaining('curl -fsSL'), findsNothing);
+ await tap(tester, find.text('Download Harness'));
+ expect(
+ find.text('Couldn’t open your browser. Copy the link instead.'),
+ findsOneWidget,
+ );
+ result = PlatformException(code: 'browser-unavailable');
+ await tap(tester, find.text('Download Harness'));
+ expect(find.text('Copy download link'), findsOneWidget);
+ result = true;
+ await tap(tester, find.text('Download Harness'));
+ expect(find.textContaining('Couldn’t open your browser'), findsNothing);
+ expect(launches.toSet(), {'https://www.autonomous.ai/harness'});
+ final pending = Completer<bool>();
+ result = pending;
+ await tap(tester, find.text('Download Harness'));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ pending.complete(false);
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'resource refresh backs off on failure and pauses while the app is inactive',
+ (tester) async {
+ app.resourceValues['local'] = const MachineResources(cpuPercent: 12);
+ await mount(tester);
+ expect(app.resourceReadIds, ['local']);
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pump();
+ expect(app.resourceReadIds, ['local', 'local']);
+ app.resourceValues.clear();
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pump();
+ expect(find.text('0 harnesses · CPU — · RAM —'), findsOneWidget);
+ final reads = app.resourceReadIds.length;
+ for (var i = 0; i < 5; i++) {
+ await tester.pump(const Duration(seconds: 5));
+ }
+ expect(app.resourceReadIds, hasLength(reads));
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pump();
+ expect(app.resourceReadIds, hasLength(reads + 1));
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ await tester.pump(const Duration(minutes: 1));
+ expect(app.resourceReadIds, hasLength(reads + 1));
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
+ await tester.pumpAndSettle();
+ expect(app.resourceReadIds, hasLength(reads + 2));
+ app.machineStates.clear();
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(find.text('Starting Harness…'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'Machines toolbar remains usable in a short narrow workspace at large text size',
+ (tester) async {
+ final previous = newHarnessOpensInBox;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = previous);
+ await mount(
+ tester,
+ size: const Size(480, 360),
+ scale: 1.7,
+ workspace: true,
+ );
+ expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ await tap(tester, find.byTooltip('Close Machines'));
+ expect(
+ find.byKey(const ValueKey('swarm-machines-button')).hitTestable(),
+ findsOneWidget,
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('welcome teaches the effective Machines shortcut', (
+ tester,
+ ) async {
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ final commands = <String>[];
+ await tester.pumpWidget(
+ MaterialApp(
+ home: KeymapProvider(
+ keymap: map,
+ child: WorkspaceWelcome(onCommand: commands.add),
+ ),
+ ),
+ );
+ expect(find.text('⌘M'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('welcome-machines.list')));
+ expect(commands, ['machines.list']);
+ map.apply(
+ '{"bindings":[{"keys":"cmd+m","command":null},{"keys":"cmd+y","command":"machines.list"}]}',
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('⌘Y'), findsOneWidget);
+ expect(find.text('⌘M'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/models_panel_test.dart b/desktop/test/models_panel_test.dart
index 60c895ee1..7e93a1e73 100644
--- a/desktop/test/models_panel_test.dart
+++ b/desktop/test/models_panel_test.dart
@@ -470,7 +470,7 @@ void main() {
expect(find.text('Qwen3.8-27B'), findsOneWidget);
expect(find.text('gemma-4-12B'), findsNothing);
}
- await tester.tap(find.text('Model Manager'));
+ await tester.tap(find.text('Manage models'));
expect(manages, 1);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
@@ -558,8 +558,8 @@ void main() {
expect(panel.top, greaterThan(tester.getRect(button).bottom));
expect(panel.width, 640);
expect(
- tester.getRect(find.byTooltip('Harness Monitor')).right,
- lessThan(tester.getRect(button).left),
+ tester.getRect(button).right,
+ lessThan(tester.getRect(find.byTooltip('Harnesses')).left),
);
expect(find.byType(Dialog), findsNothing);
expect(find.text('Run AI on this computer'), findsNothing);
diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dart
index 74ead6f6a..56c6cbec7 100644
--- a/desktop/test/new_harness_entry_rules_test.dart
+++ b/desktop/test/new_harness_entry_rules_test.dart
@@ -564,7 +564,7 @@ void main() {
expect(picker.rows.any((row) => row.isCreate), isFalse);
expect(picker.selected?.id, selected);
expect(picker.rows.map((row) => row.id), results);
- expect(find.text('Agents · openharness'), findsOneWidget);
+ expect(find.text('Harnesses · openharness'), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
expect(picker.query, '# openharness');
expect(picker.canGoBack, isFalse);
diff --git a/desktop/test/swarm_attention_picker_test.dart b/desktop/test/swarm_attention_picker_test.dart
index 009bc35a7..14284f73f 100644
--- a/desktop/test/swarm_attention_picker_test.dart
+++ b/desktop/test/swarm_attention_picker_test.dart
@@ -234,7 +234,7 @@ void main() {
app.dismissError();
await tester.pump();
expect(find.text('No harnesses need your input'), findsOneWidget);
- await tester.tap(find.byTooltip('Close Harness Monitor'));
+ await tester.tap(find.byTooltip('Close Harnesses'));
await tester.pump();
expect(app.panes, isEmpty);
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/toolbar_notices_test.dart b/desktop/test/toolbar_notices_test.dart
new file mode 100644
index 000000000..532b6b564
--- /dev/null
+++ b/desktop/test/toolbar_notices_test.dart
@@ -0,0 +1,213 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/toolbar_notices.dart';
+
+import 'swarm_state_test.dart' show MemoryStore;
+
+class _HeldStore extends MemoryStore {
+ final reads = <Completer<String?>>[];
+ @override
+ Future<String?> read(String key) {
+ final reply = Completer<String?>();
+ reads.add(reply);
+ return reply.future;
+ }
+}
+
+class _BrokenStore extends MemoryStore {
+ @override
+ Future<String?> read(String key) async => throw StateError('read failed');
+ @override
+ Future<void> write(String key, String value) async =>
+ throw StateError('write failed');
+}
+
+void sync(
+ ToolbarNotices notices, {
+ String scope = 'account-a',
+ Set<String> machines = const {},
+ Set<String> ready = const {},
+ Set<String> catalog = const {'existing'},
+ bool catalogLoaded = true,
+ bool machinesVisible = false,
+ bool modelsVisible = false,
+}) => notices.sync(
+ scope: scope,
+ machines: machines,
+ readyModels: ready,
+ catalog: catalog,
+ catalogLoaded: catalogLoaded,
+ machinesVisible: machinesVisible,
+ modelsVisible: modelsVisible,
+);
+
+Future<void> settle() => Future<void>.delayed(Duration.zero);
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test(
+ 'machine news clears when seen and stays cleared after restart',
+ () async {
+ final store = MemoryStore();
+ var notices = ToolbarNotices(storage: store);
+ sync(notices, machines: {'mini'});
+ expect(
+ notices.machineCount,
+ 0,
+ ); // Load acknowledgements before showing badges.
+ await settle();
+ expect(notices.machineCount, 1);
+ sync(notices, machines: {'mini', 'office'});
+ expect(notices.machineCount, 2);
+ sync(
+ notices,
+ machines: {'mini'},
+ ); // Offline or already linked no longer counts.
+ expect(notices.machineCount, 1);
+ sync(notices, machines: {'mini'}, machinesVisible: true);
+ expect(notices.machineCount, 0);
+ await settle();
+ notices.dispose();
+ notices = ToolbarNotices(storage: store);
+ sync(notices, machines: {'mini', 'office'});
+ await settle();
+ expect(notices.machineCount, 1);
+ sync(notices, machines: {'mini', 'office'}, machinesVisible: true);
+ sync(
+ notices,
+ machines: {'mini', 'office', 'server'},
+ machinesVisible: true,
+ );
+ expect(
+ notices.machineCount,
+ 0,
+ ); // New arrivals are visible in the open panel.
+ notices.dispose();
+ },
+ );
+
+ test('only unseen model completions count, not catalog changes', () async {
+ final notices = ToolbarNotices(storage: MemoryStore());
+ sync(notices);
+ await settle();
+ expect(notices.modelCount, 0);
+ sync(notices, catalog: {'existing', 'release'});
+ expect(notices.modelCount, 0);
+ sync(notices, ready: {'host/job-1', 'host/job-2'});
+ expect(notices.modelCount, 2);
+ sync(notices, ready: {'host/job-1', 'host/job-2'}, modelsVisible: true);
+ expect(notices.modelCount, 0);
+ sync(notices);
+ sync(notices, ready: {'host/job-1'});
+ expect(notices.modelCount, 0);
+ sync(notices, ready: {'host/job-3'});
+ expect(notices.modelCount, 1);
+ notices.dispose();
+ });
+
+ test(
+ 'new catalog labels last for one panel visit, with a quiet first run',
+ () async {
+ final notices = ToolbarNotices(storage: MemoryStore());
+ sync(notices, catalogLoaded: false, catalog: {});
+ await settle();
+ sync(notices, modelsVisible: true);
+ expect(notices.newModelIds, isEmpty);
+ sync(notices);
+ sync(notices, catalog: {'existing', 'new'});
+ sync(notices, catalog: {'existing', 'new'}, modelsVisible: true);
+ expect(notices.newModelIds, {'new'});
+ sync(notices, catalog: {'existing', 'new', 'newer'}, modelsVisible: true);
+ expect(notices.newModelIds, {'new', 'newer'});
+ sync(notices, catalog: {'existing', 'newer'}, modelsVisible: true);
+ expect(notices.newModelIds, {'newer'});
+ sync(notices, catalog: {'existing', 'newer'});
+ sync(notices, catalog: {'existing', 'newer'}, modelsVisible: true);
+ expect(notices.newModelIds, isEmpty);
+ notices.dispose();
+ },
+ );
+
+ test('acknowledgements remain separate across accounts', () async {
+ final notices = ToolbarNotices(storage: MemoryStore());
+ sync(
+ notices,
+ machines: {'mini'},
+ ready: {'job'},
+ machinesVisible: true,
+ modelsVisible: true,
+ );
+ await settle();
+ sync(notices, scope: 'account-b', machines: {'mini'}, ready: {'job'});
+ await settle();
+ expect(notices.machineCount, 1);
+ expect(notices.modelCount, 1);
+ sync(notices, machines: {'mini'}, ready: {'job'});
+ await settle();
+ expect(notices.machineCount, 0);
+ expect(notices.modelCount, 0);
+ notices.dispose();
+ });
+
+ test('late preferences cannot overwrite a newer account visit', () async {
+ final store = _HeldStore();
+ final notices = ToolbarNotices(storage: store);
+ sync(notices, machines: {'mini'});
+ await settle();
+ sync(notices, scope: 'account-b');
+ await settle();
+ sync(notices, machines: {'mini'});
+ await settle();
+ store.reads[2].complete('{"machines":["mini"],"ready":[],"catalog":[]}');
+ await settle();
+ store.reads[0].complete(null);
+ store.reads[1].complete(null);
+ await settle();
+ expect(notices.machineCount, 0);
+ notices.dispose();
+ sync(notices, machines: {'new'});
+ });
+
+ test(
+ 'closing during a preference read causes no late notifications',
+ () async {
+ final store = _HeldStore();
+ final notices = ToolbarNotices(storage: store);
+ sync(notices);
+ await settle();
+ notices.dispose();
+ store.reads.single.complete(null);
+ await settle();
+ },
+ );
+
+ for (final value in [
+ 'invalid JSON',
+ '[]',
+ '{"machines":[42],"ready":null}',
+ ]) {
+ test('invalid preferences recover without blocking news: $value', () async {
+ final store = MemoryStore()
+ ..values[ToolbarNotices.storageKey('account-a')] = value;
+ final notices = ToolbarNotices(storage: store);
+ sync(notices, machines: {'mini'});
+ await settle();
+ expect(notices.machineCount, 1);
+ notices.dispose();
+ });
+ }
+
+ test(
+ 'storage failures preserve working in-memory acknowledgements',
+ () async {
+ final notices = ToolbarNotices(storage: _BrokenStore());
+ sync(notices, machines: {'mini'}, machinesVisible: true);
+ await settle();
+ sync(notices, machines: {'mini'});
+ expect(notices.machineCount, 0);
+ notices.dispose();
+ },
+ );
+}
diff --git a/desktop/tool/check_machines_coverage.mjs b/desktop/tool/check_machines_coverage.mjs
new file mode 100644
index 000000000..20c2e3c1b
--- /dev/null
+++ b/desktop/tool/check_machines_coverage.mjs
@@ -0,0 +1,18 @@
+/** Check new Machines feature files, not whole-app coverage.
+ * flutter test --coverage test/machines_panel_test.dart test/machine_resources_test.dart test/machines_manager_test.dart test/boot_flow_widget_test.dart test/toolbar_notices_test.dart
+ */
+import { readFileSync } from 'node:fs'
+
+const expected = new Set(['lib/widgets/machines_panel.dart', 'lib/widgets/toolbar_icon.dart', 'lib/core/machine_resources.dart', 'lib/state/toolbar_notices.dart'])
+const fileCount = expected.size
+let total = 0
+for (const record of readFileSync(process.argv[2] ?? 'coverage/lcov.info', 'utf8').split('end_of_record')) {
+ const path = record.match(/SF:(.*)/)?.[1]
+ if (!expected.delete(path)) continue
+ const found = Number(record.match(/LF:(\d+)/)?.[1])
+ const hit = Number(record.match(/LH:(\d+)/)?.[1])
+ if (!found || hit !== found) throw new Error(`${path}: ${hit}/${found} lines; expected 100%`)
+ total += found
+}
+if (expected.size) throw new Error(`Missing feature coverage: ${[...expected].join(', ')}`)
+console.log(`Machines desktop: ${total}/${total} lines (100%) across ${fileCount} new feature files. This is not whole-app coverage.`)
diff --git a/desktop/tool/keymap_native_checks.swift b/desktop/tool/keymap_native_checks.swift
index fa3c2a6ea..0c766ea7f 100644
--- a/desktop/tool/keymap_native_checks.swift
+++ b/desktop/tool/keymap_native_checks.swift
@@ -30,6 +30,7 @@ for (key, command) in [
("cmd+o", "agent.open"), ("cmd+p", "navigation.commands"),
("cmd+r", "pane.split_right"), ("cmd+d", "pane.split_down"),
("cmd+n", "agent.new"),
+ ("cmd+m", "machines.list"),
("cmd+h", "pane.focus_left"), ("cmd+j", "pane.focus_below"),
("cmd+k", "pane.focus_above"), ("cmd+l", "pane.focus_right"),
] {
@@ -43,6 +44,10 @@ try checkKeymap(defaults.viewerOrchestratorCommand(stroke("cmd+b")) == nil,
try checkKeymap(defaults.viewerOrchestratorCommand(stroke("cmd+p")) == nil,
"The viewer bridge does not take the command palette chord")
for context in HarnessNativeKeymap.contexts {
+ try checkKeymap(defaults.match([stroke("cmd+m")], context: context).binding?.command == "machines.list",
+ "Command-M opens Machines 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+shift+p")], context: context).binding == nil,
"The former commands shortcut is unbound")
try checkKeymap(defaults.match([stroke("cmd+shift+n")], context: context).binding?.command == "agent.clone",
diff --git a/desktop/tool/machines_preview.dart b/desktop/tool/machines_preview.dart
new file mode 100644
index 000000000..de79d698e
--- /dev/null
+++ b/desktop/tool/machines_preview.dart
@@ -0,0 +1,228 @@
+/// Interactive review of the real Machines UI with disposable, in-memory data.
+/// Build this entrypoint, then launch with FLUTTER_TEST=1. Never used in releases.
+/// Start with MACHINES_PREVIEW_EMPTY=1 or MACHINES_PREVIEW_GUEST=1 to review first use.
+/// F6 simulates discovery of a second computer; its fixture password is `123456`.
+library;
+
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_link.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/desktop_window.dart';
+import 'package:harness/core/machine_resources.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:harness/models/local_model.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:window_manager/window_manager.dart';
+
+import '../test/support/machine_api.dart';
+import '../test/support/mixed_agents.dart';
+import '../test/support/password_cli.dart';
+
+class _Cli extends PasswordCli {
+ @override
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ }) async {
+ onProgress?.call('exchanging');
+ await Future<void>.delayed(const Duration(seconds: 2));
+ return password == '123456'
+ ? CliLinkConnectResult(linkedMachineId: machineId)
+ : const CliLinkConnectResult(error: 'Incorrect password. Try again.');
+ }
+
+ @override
+ Future<RemotePasswordSetResult> setRemotePassword(String password) async {
+ await Future<void>.delayed(const Duration(seconds: 2));
+ return super.setRemotePassword(password);
+ }
+}
+
+class _App extends AppNotifier {
+ _App(_Cli cli)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLink: cli,
+ peerLinks: cli,
+ ) {
+ api = MachineApi();
+ hasNavigationRail = false;
+ currentUser = const CurrentUserProfile(email: '[email protected]');
+ seedMixedAgents(this);
+ stateOf('m')!.localOnly = true;
+ if (Platform.environment['MACHINES_PREVIEW_EMPTY'] == '1') {
+ machineStates.removeWhere((id, _) => id != 'm');
+ stateOf('m')!.agents = [];
+ } else {
+ discover();
+ }
+ signedIn = Platform.environment['MACHINES_PREVIEW_GUEST'] != '1';
+ machines = machineStates.values.map((m) => m.machine).toList();
+ _publishModels();
+ }
+
+ final _models = <Map<String, dynamic>>[
+ {
+ 'id': 'qwen3.5',
+ 'name': 'Qwen 3.5',
+ 'state': 'available',
+ 'canStart': true,
+ 'sizeBytes': 5000000000,
+ },
+ ];
+ int _modelJob = 0;
+
+ void _publishModels() {
+ modelManager
+ ..localModels = _models.map(LocalModel.fromJson).toList()
+ ..loaded = true
+ ..inventoryAvailable = true;
+ notifyListeners();
+ }
+
+ void finishModelDownload() {
+ unawaited(controlLocalModel('m', 'qwen3.5', start: true));
+ }
+
+ void discoverModel() {
+ if (_models.any((m) => m['id'] == 'gemma')) return;
+ _models.add({
+ 'id': 'gemma',
+ 'name': 'Gemma',
+ 'state': 'available',
+ 'canStart': true,
+ });
+ _publishModels();
+ }
+
+ @override
+ Future<GridModels> gridModels(String machineId) async =>
+ const GridModels(gridName: 'Review', models: []);
+
+ @override
+ Future<Map<String, dynamic>> localModels(
+ String machineId, {
+ bool refresh = false,
+ }) async => {
+ 'models': _models,
+ 'memoryBytes': 32 * 1024 * 1024 * 1024,
+ 'hardware': 'Apple M2',
+ 'busy': false,
+ };
+
+ @override
+ Future<Map<String, dynamic>> controlLocalModel(
+ String machineId,
+ String modelId, {
+ required bool start,
+ }) async {
+ final model = _models.firstWhere((m) => m['id'] == modelId);
+ final operation = <String, dynamic>{
+ 'id': 'review-${++_modelJob}',
+ 'modelId': modelId,
+ 'action': start ? 'start' : 'stop',
+ 'stage': start ? 'verifying' : 'stopping',
+ 'phase': 'done',
+ };
+ model.addAll({
+ 'state': start ? 'running' : 'downloaded',
+ 'canStart': !start,
+ 'canStop': start,
+ 'operation': operation,
+ });
+ _publishModels();
+ return {'operation': operation};
+ }
+
+ void discover() {
+ machineStates['mini'] =
+ MachineState(
+ const Machine(
+ machineId: 'mini',
+ name: 'Mac mini',
+ authMode: MachineAuthMode.remote,
+ ),
+ )
+ ..nodeOnline = true
+ ..needsLink = true
+ ..agentLoadStatus = AgentLoadStatus.needsLink;
+ machines = machineStates.values.map((m) => m.machine).toList();
+ notifyListeners();
+ }
+
+ @override
+ Future<MachineResources?> readMachineResources(String id) async =>
+ MachineResources(
+ cpuPercent: id == 'm' ? 18 : 42,
+ memoryUsedBytes: (id == 'm' ? 12 : 24) * 1024.0 * 1024 * 1024,
+ memoryTotalBytes: (id == 'm' ? 32 : 64) * 1024.0 * 1024 * 1024,
+ );
+
+ @override
+ Future<void> retryMachines() async => notifyListeners();
+
+ @override
+ Future<void> login() async {
+ await Future<void>.delayed(const Duration(seconds: 1));
+ signedIn = true;
+ notifyListeners();
+ }
+
+ @override
+ Future<String?> connectWithPassword(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ }) async {
+ final error = await super.connectWithPassword(
+ machineId,
+ password,
+ onProgress: onProgress,
+ );
+ if (error == null) {
+ stateOf(machineId)!
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ notifyListeners();
+ }
+ return error;
+ }
+}
+
+Future<void> main() async {
+ if (!kUnderTest) throw StateError('Preview requires FLUTTER_TEST=1.');
+ WidgetsFlutterBinding.ensureInitialized();
+ newHarnessOpensInBox = true;
+ final app = _App(_Cli());
+ await configureDesktopWindow();
+ await windowManager.setTitle(
+ Platform.environment['MACHINES_PREVIEW_TITLE'] ?? 'Machines review',
+ );
+ runApp(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.f6): app.discover,
+ const SingleActivator(LogicalKeyboardKey.f7): app.finishModelDownload,
+ const SingleActivator(LogicalKeyboardKey.f8): app.discoverModel,
+ },
+ child: SwarmScreen(notifier: app, nativeTabs: true),
+ ),
+ ),
+ );
+}
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index ddd46b28e..f0591dd5c 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -140,7 +140,7 @@ private extension SwarmTabStrip {
}
func checkStartupPalette(_ expected: SwarmNativePalette) throws {
- try checkTitlebar(palette == expected && newButton.contentTintColor == expected.accent && sessionsButton.contentTintColor == expected.accent,
+ try checkTitlebar(palette == expected && newButton.contentTintColor == expected.accent && sessionsButton.contentTintColor == sessionsButton.iconTint,
"Initial search and new-swarm colors use the saved palette")
try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled && !sessionsButton.isEnabled,
"Initial palette setup does not create or enable workspace controls")
@@ -270,7 +270,7 @@ private extension SwarmTabStrip {
"The Store action has a visible and accessible name")
try checkTitlebar(newButton.frame.maxX < sessionsButton.frame.minX && sessionsButton.frame.maxX < storeButton.frame.minX && storeButton.frame.maxX <= bounds.width,
"Harnesses sits to the left of the Store without overlapping its hit target")
- try checkTitlebar(sessionsButton.accessibilityLabel() == "Harness Monitor", "Harnesses has an accessible name")
+ try checkTitlebar(sessionsButton.accessibilityLabel() == "Harnesses", "Harnesses has an accessible name")
try checkTitlebar(!subviews.contains(where: { $0 is NSTextField }), "The titlebar has no competing text editor")
events.removeAll()
newButton.performClick(nil)
@@ -303,8 +303,8 @@ private extension SwarmTabStrip {
update(themedState)
try checkTitlebar(newButton === oldButton && tabs[0] === original,
"Palette changes retain native control identity")
- try checkTitlebar(newButton.contentTintColor == palette.accent && sessionsButton.contentTintColor == palette.accent,
- "Both toolbar icons receive the coordinated palette")
+ try checkTitlebar(newButton.contentTintColor == palette.accent && sessionsButton.contentTintColor == sessionsButton.iconTint,
+ "Toolbar tools stay monochrome when the workspace palette changes")
events.removeAll()
try original.checkEnabled(true)
original.clickBothActions()
@@ -393,7 +393,7 @@ private extension SwarmTabStrip {
messenger.finishNextReply()
try checkTitlebar(window.firstResponder === window.contentInput,
"The latest acknowledged tab action restores content focus")
- for (button, method) in [(sessionsButton, "sessions")] {
+ for (button, method) in [(sessionsButton, "sessions"), (machinesButton, "machineList")] {
window.makeFirstResponder(button)
let before = messenger.calls.count
button.performClick(nil)
@@ -577,6 +577,11 @@ private extension SwarmTitlebar {
try checkTitlebar(main.defersToInput(event("p", 35, .command)), "Command-P reaches commands")
try checkTitlebar(!main.defersToInput(event("p", 35, [.command, .shift])), "Command-Shift-P is unbound")
try checkTitlebar(main.defersToInput(event("o", 31, .command)), "Command-O reaches Open Harness")
+ try checkTitlebar(strip.machinesButton.toolTip == "Machines ⌘M", "Machines advertises its effective shortcut")
+ try checkTitlebar(main.defersToInput(event("m", 46, .command)) &&
+ !main.performKeyEquivalent(with: event("m", 46, .command)),
+ "Command-M reaches Flutter exactly once instead of invoking a native window action")
+ try checkTitlebar(!main.defersToInput(event("u", 32, .command)), "Command-U is no longer claimed")
flutterKeyContext = "picker"
syncMenuKeys()
try checkTitlebar(!main.performKeyEquivalent(with: event("\u{f701}", 125)), "Result arrows are owned by the shared picker")
@@ -698,7 +703,7 @@ private extension SwarmTitlebar {
try window.checkContentCommand()
try checkTitlebar(window.firstResponder === window.contentInput,
"Adding toolbar buttons does not take initial keyboard focus from the workspace")
- try checkTitlebar(main.items.map(\.title) == ["Harness", "File", "Edit", "View", "History", "Models", "Machines", "Window", "Help"], "File leads the standard macOS menus, with Machines after Models")
+ try checkTitlebar(main.items.map(\.title) == ["Harness", "File", "Edit", "View", "History", "Models", "Window", "Help"], "Machines lives in the toolbar and View menu")
let settings = appItem.submenu!.items.first { $0.representedObject as? String == "settings" }!
try checkTitlebar(settings.title == "Settings…" && settings.representedObject as? String == "settings", "Settings stays in the application menu")
let agent = main.item(withTitle: "File")!.submenu!
@@ -709,7 +714,7 @@ private extension SwarmTitlebar {
"New Terminal stays off the File menu; its chord lives in the keymap")
let historyMenu = main.item(withTitle: "History")!.submenu!
try checkTitlebar(agent.items.contains { $0.title == "Clone Harness" && $0.representedObject as? String == "cloneAgent" }, "Clone Harness preserves its action")
- try checkTitlebar(agent.items.map { $0.isSeparatorItem ? "separator" : ($0.representedObject as? String ?? "") } == ["newAgent", "addAgent", "cloneAgent", "separator", "new", "renameActive", "closeActive", "separator", "splitRight", "splitDown", "zoomPane", "movePaneToTab", "closePane"], "File groups harness, tab and pane actions, harnesses first")
+ try checkTitlebar(agent.items.map { $0.isSeparatorItem ? "separator" : ($0.representedObject as? String ?? "") } == ["newAgent", "addAgent", "cloneAgent", "restartAgent", "separator", "new", "renameActive", "closeActive", "separator", "splitRight", "splitDown", "zoomPane", "movePaneToTab", "closePane"], "File groups harness, tab and pane actions, harnesses first")
try checkTitlebar(agent.items.first?.title == "New Harness" && agent.items.first?.keyEquivalent == "n" && agent.items.first?.keyEquivalentModifierMask == [.command],
"New Harness leads File on Command-N")
for (action, title, key) in [("splitRight", "Split Right", "r"), ("splitDown", "Split Down", "d")] {
@@ -760,69 +765,60 @@ private extension SwarmTitlebar {
["id": "home", "name": "iMac – Home", "status": "Offline", "presence": "Offline", "local": false, "agentCount": 0],
]
_ = try messenger.receive("machinesState", arguments: ["machines": machineRows])
- let machineMenu = main.item(withTitle: "Machines")!.submenu!
- let manage = machineMenu.items[0]
- let manager = machineMenu.items[1]
- try checkTitlebar(manage.title == "Open Machine Monitor…" && manage.representedObject as? String == "manageMachines" &&
- manager.title == "Open Machines Manager" && manager.representedObject as? String == "machineList" && machineMenu.items[2].isSeparatorItem,
- "The Machines harness and existing manager lead the linked computers")
+ let machineMenu = main.item(withTitle: "View")!.submenu!
+ let manager = machineMenu.items.first { $0.representedObject as? String == "machineList" }!
+ let manage = machineMenu.items.first { $0.representedObject as? String == "manageMachines" }!
+ try checkTitlebar(manager.title == "Machines" && manager.keyEquivalent == "m" &&
+ manager.keyEquivalentModifierMask == [.command], "View exposes Machines on Command-M")
+ try checkTitlebar(main.item(withTitle: "Machines") == nil, "The old Machines menu is replaced")
menuAction(manage)
- try checkTitlebar(messenger.calls.last?.method == "manageMachines",
- "The Machines harness opens through the Flutter command bridge")
+ try checkTitlebar(messenger.calls.last?.method == "manageMachines", "Machine Monitor remains available in View")
menuAction(manager)
- try checkTitlebar(messenger.calls.last?.method == "machineList",
- "Machines Manager opens through the Flutter command bridge")
- let destinations = machineMenu.items.filter { $0.action == #selector(machineAction(_:)) }
- try checkTitlebar(machineMenu.minimumWidth == 0 && machineMenu.size.width < 432 &&
- destinations.first?.attributedTitle?.string.hasSuffix("\t2 harnesses") == true,
- "Machines gives labels twenty percent more room with aligned counts")
- try checkTitlebar(destinations.map { $0.representedObject as? String } == ["office", "home"],
- "Machines lists each linked computer as a destination")
- try checkTitlebar(destinations[0].attributedTitle?.string.contains("Online") == true &&
- destinations[1].attributedTitle?.string.contains("Offline") == true,
- "Machine availability is visible before opening its agent search")
- try checkTitlebar(destinations[0].attributedTitle?.string.contains("2 harnesses") == true && destinations[1].attributedTitle?.string.contains("0 harnesses") == true,
- "Machine labels include their cached agent count")
- let agentItems = destinations[0].submenu!.items.filter { $0.action == #selector(machineAgentAction(_:)) }
- try checkTitlebar(agentItems.map(\.title) == ["App work", "Unavailable session"] && agentItems[0].image != nil,
- "Machines expand into named agents with engine icons")
+ try checkTitlebar(messenger.calls.last?.method == "machineList", "Machines opens the Flutter panel")
_ = try messenger.receive("update", arguments: [
"tabs": [["id": "navigation-check", "name": "Another tab"]],
- "activeId": "navigation-check", "enabled": true,
+ "activeId": "navigation-check", "enabled": true, "machinesOpen": true,
])
- try checkTitlebar(machineMenu.items.contains(where: { $0 === destinations[0] }) &&
- destinations[0].submenu?.items.contains(where: { $0 === agentItems[0] }) == true,
- "Tab updates retain the existing machine menu and agent controls")
- try checkTitlebar(validateMenuItem(agentItems[0]) && !validateMenuItem(agentItems[1]),
- "Unavailable agents cannot be activated")
- machineAgentAction(agentItems[0])
- try checkTitlebar(messenger.calls.last?.method == "machineAgent" &&
- (messenger.calls.last?.arguments as? [String: String]) == ["machineId": "office", "agentId": "one"],
- "Agent selection sends both stable identities to Flutter")
- try checkTitlebar(destinations[1].submenu?.item(withTitle: "No harnesses yet")?.isEnabled == false &&
- destinations[1].submenu?.item(withTitle: "Find Harnesses…") != nil,
- "Empty machines explain the empty list and keep search available")
- try checkTitlebar(machineMenu.items.compactMap { $0.representedObject as? String }.suffix(2) == ["linkMachine", "refreshMachines"],
- "Machines exposes Link and Refresh after the computer list")
- let machineCallCount = messenger.calls.count
- machineAction(destinations[0])
- try checkTitlebar(messenger.calls.count == machineCallCount + 1 &&
- messenger.calls.last?.method == "machineDestination" &&
- (messenger.calls.last?.arguments as? [String: String])?["id"] == "office",
- "A computer sends its stable id to the shared agent search")
- actionsEnabled = false
- machineAction(destinations[1])
- machineAgentAction(agentItems[0])
- try checkTitlebar(!validateMenuItem(destinations[1]) && messenger.calls.count == machineCallCount + 1,
- "A modal blocks machine destinations")
+ try checkTitlebar(strip.machinesButton.state == .on && strip.machinesButton.isEnabled,
+ "The Machines toolbar reflects the open panel")
+ try checkTitlebar(strip.machinesButton.frame.maxX < strip.modelsButton.frame.minX &&
+ strip.modelsButton.frame.maxX < strip.sessionsButton.frame.minX,
+ "Machines, Models, and Harnesses occupy adjacent ordered slots")
+ let beforeMachine = messenger.calls.count
+ strip.machinesButton.performClick(nil)
+ try checkTitlebar(messenger.calls.count == beforeMachine + 1 && messenger.calls.last?.method == "machineList",
+ "The Machines toolbar toggles the same panel as the menu")
+ _ = try messenger.receive("update", arguments: ["enabled": false, "machinesOpen": false])
+ try checkTitlebar(!strip.machinesButton.isEnabled && strip.machinesButton.state == .off,
+ "Modal state disables Machines and a closed panel clears the selection")
+ strip.machinesButton.performClick(nil)
+ menuAction(manager)
+ try checkTitlebar(messenger.calls.count == beforeMachine + 1 && !validateMenuItem(manager),
+ "Neither entry point dispatches behind a modal")
actionsEnabled = true
- updateMachines(machineRows)
- try checkTitlebar(machineMenu.items.contains(where: { $0 === destinations[0] }),
- "Unchanged machine data retains menu controls")
_ = try messenger.receive("machinesState", arguments: ["machines": []])
- try checkTitlebar(!validateMenuItem(destinations[0]) && !validateMenuItem(agentItems[0]) &&
- machineMenu.item(withTitle: "No Machines Linked")?.isEnabled == false,
- "Unlinking computers clears destinations and invalidates stale actions")
+ _ = try messenger.receive("update", arguments: [
+ "enabled": true, "machineNotices": 2, "modelNotices": 101, "unread": 3,
+ ])
+ try checkTitlebar(strip.machinesButton.attentionLabel == "2" &&
+ strip.modelsButton.attentionLabel == "99+" && strip.sessionsButton.attentionLabel == "3",
+ "The three tools share the same bounded notification badge")
+ try checkTitlebar([strip.machinesButton, strip.modelsButton, strip.sessionsButton].allSatisfy {
+ $0.iconTint == NSColor(white: 0.96, alpha: 1)
+ }, "All three icons brighten when they have news")
+ try checkTitlebar(strip.machinesButton.badgeFrame(textWidth: 8) ==
+ strip.modelsButton.badgeFrame(textWidth: 8) &&
+ strip.modelsButton.badgeFrame(textWidth: 8) == strip.sessionsButton.badgeFrame(textWidth: 8),
+ "Badges align consistently on the three equal-size buttons")
+ try checkTitlebar((strip.machinesButton.accessibilityValue() as? String)?.contains("2 new computers") == true &&
+ (strip.modelsButton.accessibilityValue() as? String)?.contains("101 models ready") == true,
+ "Machine and model notifications are available to assistive technology")
+ _ = try messenger.receive("update", arguments: ["enabled": true])
+ try checkTitlebar(strip.machinesButton.attentionLabel == nil && strip.modelsButton.attentionLabel == nil,
+ "Acknowledged machine and model news removes the badge")
+ try checkTitlebar(strip.machinesButton.iconTint == NSColor(white: 0.60, alpha: 1) &&
+ strip.modelsButton.iconTint == NSColor(white: 0.60, alpha: 1),
+ "Acknowledged icons return to muted gray")
var recentRows: [[String: Any]] = (0..<20).map { index -> [String: Any] in
["id": "agent:\(index)", "title": "Agent \(index) — Machine",
"detail": "Project \(index)", "machineName": "M2", "current": index == 0,
@@ -927,7 +923,7 @@ private extension SwarmTitlebar {
let models = main.item(withTitle: "Models")!.submenu!
try checkTitlebar(models.items.filter { !$0.isSeparatorItem }.map(\.title) == [
"Subscriptions", "Anthropic, aabbcc, 12% remaining", "OpenAI, Not signed in",
- "On this Mac", "Manage Local Models in Grid…"
+ "On this Mac", "Open Models…"
], "Models carries the two sections with something behind them, ending on the row that starts a model")
try checkTitlebar(models.items.filter(\.isSeparatorItem).count == 2,
"Two native separators: after the subscriptions, and before the row that manages models")
@@ -935,58 +931,36 @@ private extension SwarmTitlebar {
try checkTitlebar(models.item(withTitle: gone) == nil,
"\(gone) is gone — it named nothing this app can reach or do")
}
- // The manager action closes the menu. It stays enabled with nothing served and dispatches
- // through the same guarded handler as Link Machine…, so a modal still swallows it.
- let runLocal = models.items.last!
- try checkTitlebar(runLocal.title == "Manage Local Models in Grid…",
- "the last item in Models is the row that runs a local model")
- try checkTitlebar(runLocal.isEnabled && runLocal.submenu == nil,
- "the manager row is enabled even when nothing is served, and opens no submenu")
- try checkTitlebar(runLocal.target === self && runLocal.action == #selector(menuAction(_:))
- && runLocal.representedObject as? String == "runLocalModel",
- "the manager row dispatches runLocalModel through the guarded channel handler")
- try checkTitlebar(runLocal.identifier?.rawValue == HarnessKeymapMenu.actionPrefix + "runLocalModel",
- "the manager row is identified for the keymap like every other Harness command")
- try checkTitlebar(validateMenuItem(runLocal), "the manager row validates with the workspace live")
- actionsEnabled = false
- try checkTitlebar(!validateMenuItem(runLocal), "the manager row cannot run behind a modal")
- actionsEnabled = true
- try checkTitlebar(!runLocal.title.contains("Mac"),
- "The model manager action does not assume one vendor's computer")
-
- // With more than one machine linked, the row has to say WHICH computer the manager opens on:
- // it becomes a submenu of the machines, each child dispatching the same command with that
- // machine's id, this computer marked. With one machine (or none) it is the plain row above.
- _ = try messenger.receive("machinesState", arguments: ["machines": machineRows])
- let picked = main.item(withTitle: "Models")!.submenu!.items.last!
- // AppKit gives a submenu's parent its own `submenuAction:`; what matters is that it is no longer
- // the guarded channel handler — nothing is dispatched until a machine is chosen.
- try checkTitlebar(picked.title == "Manage Local Models in Grid…" && picked.submenu != nil
- && picked.action != #selector(menuAction(_:)) && picked.representedObject == nil,
- "with two machines the manager row opens a submenu instead of dispatching itself")
- try checkTitlebar(picked.identifier?.rawValue == HarnessKeymapMenu.actionPrefix + "runLocalModel",
- "the submenu's parent keeps the keymap identifier")
- let choices = picked.submenu!.items
- try checkTitlebar(choices.map(\.title) == ["iMac – Office (this computer)", "iMac – Home"],
- "one child per linked machine, in the Machines menu's order, this computer marked")
- try checkTitlebar(choices.allSatisfy { $0.target === self && $0.action == #selector(runLocalModelAction(_:)) }
- && choices.map { $0.representedObject as? String } == ["office", "home"],
- "each child dispatches runLocalModel for its own machine")
+ let openModels = models.items.last!
+ try checkTitlebar(openModels.title == "Open Models…" && openModels.submenu == nil,
+ "The Models menu opens the shared overview")
+ try checkTitlebar(openModels.target === self && openModels.action == #selector(menuAction(_:))
+ && openModels.representedObject as? String == "models",
+ "The menu dispatches the same Models action as the toolbar")
+ try checkTitlebar(openModels.identifier?.rawValue == HarnessKeymapMenu.actionPrefix + "models",
+ "The Models overview is identified for the keymap")
+ for rows in [machineRows, [machineRows[0]], []] {
+ _ = try messenger.receive("machinesState", arguments: ["machines": rows])
+ let item = main.item(withTitle: "Models")!.submenu!.items.last!
+ try checkTitlebar(item.title == "Open Models…" && item.submenu == nil
+ && item.representedObject as? String == "models",
+ "Any number of machines still opens the same Models overview")
+ }
+ _ = try messenger.receive("update", arguments: ["enabled": true, "modelsOpen": true])
+ try checkTitlebar(strip.modelsButton.state == .on && strip.modelsButton.isEnabled
+ && strip.modelsButton.accessibilityValue() as? String == "Expanded",
+ "Models exposes the same active state as the other toolbar panels")
let modelCalls = messenger.calls.count
- runLocalModelAction(choices[1])
- try checkTitlebar(messenger.calls.last?.method == "runLocalModel"
- && (messenger.calls.last?.arguments as? [String: String]) == ["machineId": "home"]
- && messenger.calls.count == modelCalls + 1,
- "choosing a machine sends runLocalModel with that machine's id")
- actionsEnabled = false
- try checkTitlebar(!validateMenuItem(choices[0]), "a machine choice cannot run behind a modal")
+ strip.modelsButton.performClick(nil)
+ try checkTitlebar(messenger.calls.count == modelCalls + 1 && messenger.calls.last?.method == "models",
+ "The Models toolbar opens its overview")
+ _ = try messenger.receive("update", arguments: ["enabled": false, "modelsOpen": false])
+ strip.modelsButton.performClick(nil)
+ menuAction(openModels)
+ try checkTitlebar(!strip.modelsButton.isEnabled && strip.modelsButton.state == .off
+ && messenger.calls.count == modelCalls + 1 && !validateMenuItem(openModels),
+ "Neither Models entry point dispatches behind a modal")
actionsEnabled = true
- try checkTitlebar(validateMenuItem(choices[0]), "and returns when the modal closes")
- _ = try messenger.receive("machinesState", arguments: ["machines": [machineRows[0]]])
- let single = main.item(withTitle: "Models")!.submenu!.items.last!
- try checkTitlebar(single.submenu == nil && single.representedObject as? String == "runLocalModel",
- "one machine linked: back to the plain row, and the app picks the machine")
- _ = try messenger.receive("machinesState", arguments: ["machines": []])
// The Local section is DATA, not two hardcoded names. A menu naming a model nobody serves is
// worse than one admitting it has none, which is what the empty case above asserts.
@@ -999,7 +973,7 @@ private extension SwarmTitlebar {
"a served model names the machine answering it")
try checkTitlebar(served.item(withTitle: "DeepSeek-V4-Flash") != nil,
"a model with no node named is listed on its own")
- try checkTitlebar(served.items.last?.title == "Manage Local Models in Grid…"
+ try checkTitlebar(served.items.last?.title == "Open Models…"
&& served.items[served.items.count - 2].isSeparatorItem
&& served.items.filter(\.isSeparatorItem).count == 2,
"the manager row sits under its own rule, after the Local data rows")
@@ -1205,6 +1179,16 @@ do {
try checkTitlebar(icons.image(engine: engine, asset: asset) === icon, "Repeated \(engine) history reuses its decoded icon")
}
try checkTitlebar(assetReads == 4, "Native history loads each bundled mark only once")
+ for name in ["machines", "models", "harnesses"] {
+ let icon = icons.image(engine: name, asset: "assets/\(name).svg", pointSize: 20)
+ try checkTitlebar(icon.size == NSSize(width: 20, height: 20) && icon.isTemplate,
+ "\(name) uses a monochrome toolbar SVG")
+ try checkTitlebar(!icon.representations.isEmpty &&
+ icon.representations.allSatisfy { !($0 is NSBitmapImageRep) },
+ "The native \(name) icon retains a vector representation")
+ try checkTitlebar(icons.image(engine: name, asset: "assets/\(name).svg", pointSize: 20) === icon,
+ "\(name) reuses its loaded SVG")
+ }
let unknown = icons.image(engine: "custom", asset: nil)
try checkTitlebar(unknown.isTemplate && unknown.size == NSSize(width: 16, height: 16), "Unknown engines have a native-size adaptive initial")
let strip = SwarmTabStrip(frame: NSRect(x: 0, y: 0, width: 900, height: 52))