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.

Merge origin/main into feat/harness-grid

Tima57f22652523
diff --cc cli/build-bundle.mjs
index 744fa272d,257c213d4..3497538a2
--- a/cli/build-bundle.mjs
+++ b/cli/build-bundle.mjs
@@@ -10,7 -10,8 +10,8 @@@
* `require` via the banner so ws's try/catch fallback works without them.
*/
import * as esbuild from 'esbuild'
-import { readFileSync, copyFileSync, rmSync } from 'fs'
+import { readFileSync, copyFileSync, rmSync, mkdirSync } from 'fs'
+ import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'
const version =
process.env.ADAPTER_VERSION ||
diff --cc cli/src/backendSocket.spec.ts
index b204cbf88,42a8498ff..67c9316b1
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@@ -7,9 -8,9 +8,11 @@@ import type { TerminalStreamManager } f
import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.js'
import { registry, type RegisteredSession } from './lib/registry.js'
import * as mediaPreview from './lib/mediaPreview.js'
+ import * as projectFolder from './lib/projectFolder.js'
+ import * as projectPreview from './lib/projectPreview.js'
import { randomUUID } from 'node:crypto'
+import { fakeGridAnswers, installFakeGrid, type FakeGrid } from './lib/__fixtures__/fakeGrid.js'
+import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
const wsMock = vi.hoisted(() => {
const instances: MockWebSocket[] = []
diff --cc cli/src/cli.ts
index bf9f849ef,9756e4555..336df3f1e
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@@ -69,11 -66,21 +69,22 @@@ import { terminateDeletedAgent, checkPi
import { restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'
import { claudeContinuation, findLiveSession } from './lib/sessionRepair.js'
import { TmuxBackend } from './lib/tmuxBackend.js'
+ import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from './lib/hostTheme.js'
import { createAndRegisterPane } from './lib/createAgentPane.js'
import { restoreAgents } from './lib/restoreAgents.js'
-import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'
+import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'
+import { prepareCodexResume } from './engines/codex/portableHistory.js'
import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'
+ import { installedDsh } from './dsh/installed.js'
+ import { dshVerdictPath } from './dsh/manifest.js'
+ import { registryEntry } from './dsh/registry.js'
+ import { installDsh, resolveInstallSource } from './dsh/install.js'
+ import { materializeWorkspace } from './dsh/materialize.js'
+ import { dshLaunch } from './dsh/launch.js'
+ import { DshViewerManager } from './dsh/viewer.js'
+ import { DshVerdictWatcher, type DshVerdict } from './dsh/verdict.js'
+ import { dshCommand, dshUsage } from './dsh/command.js'
+ import type { AgentDshContext } from './lib/agentFrame.js'
import { basename } from 'node:path'
import {
bypassPermissionActive,
@@@ -999,15 -966,15 +1025,18 @@@ async function logout(): Promise<void>
// Through the lock-taking stop, not an inline kill: a logout that lands mid-handoff would otherwise
// SIGTERM the OLD daemon, leave the new one coming up, and then delete the session under it.
await stopDaemonProcess()
+ // Before clearAuthSession: see the note above on serve children. Its exit code is deliberately
+ // dropped — this command cannot fail — and its own words have already reached the terminal.
+ const gridOut = await passThroughToGridLogout([])
clearAuthSession()
rmSync(MACHINE_NAME_FILE, { force: true })
+ // Same reason as the name above: the cached machine list describes the account that just left, and the
+ // local `/api/machines` fallback would otherwise hand it to whoever signs in next on this computer.
+ rmSync(machineListCachePath(), { force: true })
console.log('Signed out. Run `harness login`, then `harness start`, to reconnect this computer.')
- // Existence is the whole of the test — nothing is read out of the store, and nothing is written
- // into it. On stderr, so a script reading this command's output is unaffected by it.
- warnIfGridSignInRemains()
+ // Only when there was no `grid` to run at all. A child that ran has already said what it did, and
+ // repeating "your grid sign-in is still here" after a successful sign-out would be false.
+ if (!gridOut.ran) warnIfGridSignInRemains()
process.exit(0)
}
@@@ -3369,33 -3512,20 +3569,43 @@@ async function runForeground(session: A
writeGridConfigDir,
tmuxSupportsSessionEnv,
installCodexHooks: (codexHome) => { if (!env.DISABLE_HOOK_INSTALL) installCodexHooks(hookPort, codexHome) },
+ dshLaunch: (id, workspace) => {
+ const installed = installedDsh(id)
+ if (!installed) {
+ console.warn(`[dsh] ${id} is not installed on this machine · relaunching as its plain base engine`)
+ return null
+ }
+ return dshLaunch(installed, workspace)
+ },
}
+ // Whatever the source (the row itself, or a grid override the desktop just sent), the agent's DSH
+ // and workspace come from the row: a retarget must not silently drop the harness the agent is.
const relaunchOverrides = (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> =>
- buildLaunchOverrides(launchOverridesDeps, session.engine, source, session.agentId)
+ buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, cwd: session.cwd, ...source }, session.agentId)
+ /**
+ * A restart or a post-reboot restore rebuilds the ROW's own launch, and the machine may decide
+ * differently about web search this time than it did when the row was written (an administrator
+ * pinned `/etc/hermes` since, or unpinned it). The override is the row's already; what is
+ * refreshed is the decision, so the frame describes the pane that actually came up. Retarget
+ * does not go through here — its override is new, and it records the pair itself once the move
+ * has succeeded.
+ */
+ const refreshGridWebSearch = (agentId: string, overrides: LaunchOverrides): void => {
+ if (overrides.gridLaunchRecord) registry.setGridLaunch(agentId, overrides.gridLaunchRecord)
+ }
+
+ const prepareSessionResume = (session: RegisteredSession): void => {
+ const repair = prepareCodexResume(session)
+ if (repair.repairedItems) {
+ // The rollout we tail was just shrunk in place. Move the tail to the repaired length now, before
+ // the resumed engine appends, or the watcher would read the whole repaired history as new lines
+ // and the live normalizer would replay the conversation into web/device. See Watcher.setTail.
+ if (repair.repairedBytes !== undefined) watcher.setTail(session.sessionId, repair.repairedBytes)
+ console.log(`[resume] repaired ${repair.repairedItems} Codex reasoning items · backup: ${repair.backupPath}`)
+ }
+ }
+
watcher.start()
await cursorDiscovery.start()
// Panes that died while the daemon was down (a reboot takes the whole tmux server with it) are
@@@ -3686,10 -3843,11 +3930,11 @@@
cwd,
sessionLabel: label,
argv,
- env: gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined),
+ env: mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined), dshEnv),
grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,
- gridLaunch: grid ?? null,
+ gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,
codexHome,
+ dsh,
bypassPermission,
})
if (!result.ok) return { ok: false, error: result.error, detail: result.detail }
diff --cc cli/src/dsh/launch.spec.ts
index 000000000,ebe7777c9..27a8bc225
mode 000000,100644..100644
--- a/cli/src/dsh/launch.spec.ts
+++ b/cli/src/dsh/launch.spec.ts
@@@ -1,0 -1,75 +1,76 @@@
+ import { describe, expect, it } from 'vitest'
+ import type { InstalledDsh } from './installed.js'
+ import { dshLaunch } from './launch.js'
+ import { buildLaunchOverrides, type LaunchOverridesDeps } from '../lib/launchOverrides.js'
+ import { dshFromEnv } from './probe.js'
+
+ const installed: InstalledDsh = {
+ id: 'autonomous/circuit', dir: '/home/u/.harness/dsh/autonomous/circuit', realDir: '/src/circuit',
+ source: '', ref: null, commit: null, linked: true, installedAt: 0,
+ manifest: {
+ spec: 1, id: 'autonomous/circuit', name: 'Circuit', engine: 'claude',
+ agent: {
+ env: { CIRCUIT_TOOLCHAIN: '${dsh}/toolchain', CIRCUIT_SKILLS_DIR: '${workspace}/.claude/skills', HARNESS_DSH: 'spoofed' },
+ args: ['--add-dir', '${workspace}/inputs'],
+ },
+ },
+ }
+
+ describe('dshLaunch', () => {
+ it('sets the three HARNESS_ variables, expands the manifest env, and refuses a manifest that renames itself', () => {
+ const launch = dshLaunch(installed, '/ws')
+ expect(launch.env).toEqual({
+ HARNESS_DSH: 'autonomous/circuit',
+ HARNESS_DSH_DIR: '/src/circuit',
+ HARNESS_WORKSPACE: '/ws',
+ CIRCUIT_TOOLCHAIN: '/src/circuit/toolchain',
+ CIRCUIT_SKILLS_DIR: '/ws/.claude/skills',
+ })
+ expect(launch.args).toEqual(['--add-dir', '/ws/inputs'])
+ // What discovery reads back is exactly what was set.
+ expect(dshFromEnv(launch.env)).toBe('autonomous/circuit')
+ })
+ })
+
+ describe('buildLaunchOverrides with a DSH', () => {
+ const deps: LaunchOverridesDeps = {
- configDirFor: () => undefined,
++ // The branch replaced `configDirFor` with the machine facts the grid launch builder reads itself.
++ machine: () => ({ hermesSystemManaged: false }),
+ writeGridConfigDir: async () => '/cfg',
+ tmuxSupportsSessionEnv: async () => true,
+ installCodexHooks: () => undefined,
+ dshLaunch: (id, workspace) => (id === installed.id ? dshLaunch(installed, workspace) : null),
+ }
+
+ it('layers the DSH env and argv over a plain relaunch', async () => {
+ const built = await buildLaunchOverrides(deps, 'claude', { dsh: 'autonomous/circuit', cwd: '/ws' }, 'agent-1')
+ expect(built.ok).toBe(true)
+ if (!built.ok) return
+ expect(built.overrides.env.HARNESS_DSH).toBe('autonomous/circuit')
+ expect(built.overrides.env.CIRCUIT_TOOLCHAIN).toBe('/src/circuit/toolchain')
+ expect(built.overrides.extraArgs).toEqual(['--add-dir', '/ws/inputs'])
+ })
+
+ it('layers it over a Codex profile too, keeping CODEX_HOME', async () => {
+ const built = await buildLaunchOverrides(deps, 'codex', { dsh: 'autonomous/circuit', cwd: '/ws', codexHome: '/home/u/.codex-work' }, 'agent-1')
+ expect(built.ok && built.overrides.env).toMatchObject({ CODEX_HOME: '/home/u/.codex-work', HARNESS_DSH: 'autonomous/circuit' })
+ })
+
+ it('falls back to the plain engine when the DSH is no longer installed here', async () => {
+ const built = await buildLaunchOverrides(deps, 'claude', { dsh: 'gone/away', cwd: '/ws' }, 'agent-1')
+ expect(built.ok && built.overrides).toEqual({ env: {}, extraArgs: [], clearEnv: [] })
+ })
+
+ it('does nothing without a workspace to expand into', async () => {
+ const built = await buildLaunchOverrides(deps, 'claude', { dsh: 'autonomous/circuit', cwd: null }, 'agent-1')
+ expect(built.ok && built.overrides.env).toEqual({})
+ })
+ })
+
+ describe('dshFromEnv', () => {
+ it('accepts only a well-formed id', () => {
+ expect(dshFromEnv({ HARNESS_DSH: 'autonomous/workshop' })).toBe('autonomous/workshop')
+ expect(dshFromEnv({ HARNESS_DSH: 'not an id' })).toBeNull()
+ expect(dshFromEnv({})).toBeNull()
+ })
+ })
diff --cc cli/src/lib/agentFrame.ts
index fc0f17678,b6dbc2447..b5b6d9b20
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@@ -21,17 -21,9 +21,18 @@@
import { stat } from 'node:fs/promises'
import { agentProject, type AgentProject } from './agentProject.js'
import type { GridAssignment } from './gridAssignment.js'
+import type { GridWebSearchStatus } from './gridLaunch.js'
import { projectDisplayName, type RegisteredSession } from './registry.js'
+ import type { DshVerdict } from '../dsh/verdict.js'
+/**
+ * The grid block on the wire: where the agent's inference goes, and — when the daemon built the
+ * launch — whether it can search the web. `webSearch` is absent, not null, when there is nothing to
+ * say: a discovered grid agent, or a row from before the daemon recorded it. The app shows nothing
+ * for absent and for `on`; the two degraded words each get a sentence.
+ */
+export type GridFrameBlock = GridAssignment & { webSearch?: GridWebSearchStatus }
+
/**
* One agent as it travels to every client.
*
@@@ -51,9 -43,26 +52,26 @@@ export type AgentFrame =
terminal: { available: boolean; primary: string; runtimes: RegisteredSession['runtimes'] }
engine: RegisteredSession['engine']
selectedModel: string | null
- grid: GridAssignment | null
+ grid: GridFrameBlock | null
codexHome: string | null
project: AgentProject | null
+ /** The domain-specific harness this agent was created as, or null for a plain engine. */
+ dsh: string | null
+ /** Its display name from the installed manifest; null when unknown here (not installed, plain engine). */
+ dshName: string | null
+ /** Where this agent's viewer is being served right now, or null when it has none up. */
+ viewerUrl: string | null
+ /** The DSH's last verdict for this workspace, reduced for the pane header; null when none yet. */
+ verdict: DshVerdict | null
+ }
+
+ /** What the daemon knows about an agent's DSH — looked up by the caller, never here. */
+ export interface AgentDshContext {
+ /** The harness's CURRENT id — an agent created under a former name (`formerly`) reports the new one. */
+ id: string | null
+ name: string | null
+ viewerUrl: string | null
+ verdict: DshVerdict | null
}
/** What the caller knows and this module deliberately does not look up for itself. */
diff --cc cli/src/lib/createAgentPane.ts
index aed02ab5b,cf7551fa0..ada795248
--- a/cli/src/lib/createAgentPane.ts
+++ b/cli/src/lib/createAgentPane.ts
@@@ -29,8 -29,9 +29,9 @@@ export interface CreateAgentPaneDeps
primaryRuntimeKey?: string
cwd?: string | null
grid?: { baseUrl: string; model: string | null } | null
- gridLaunch?: GridLaunchOverride | null
+ gridLaunchRecord?: GridLaunchRecord | null
codexHome?: string | null
+ dsh?: string | null
bypassPermission?: boolean
}) => RegisteredSession | null }
engine: AgentEngine
@@@ -41,11 -42,12 +42,13 @@@
argv: string[]
env?: Record<string, string>
grid?: { baseUrl: string; model: string | null } | null
- /** The grid launch behind `grid`, credential included — what restore/restart relaunch the pane with. */
- gridLaunch?: GridLaunchOverride | null
+ /** The grid launch behind `grid` (credential included — what restore/restart relaunch the pane with)
+ * and what building it decided about web search (what the app shows for this agent). */
+ gridLaunchRecord?: GridLaunchRecord | null
/** The CODEX_HOME folder this agent was launched against, if the caller chose one; codex only. */
codexHome?: string | null
+ /** The domain-specific harness this agent is created as, if any. */
+ dsh?: string | null
maxAttempts?: number
}
@@@ -77,8 -79,9 +80,9 @@@ export async function createAndRegister
primaryRuntimeKey: terminalRouteKey(spawned.runtime),
cwd: deps.cwd,
grid: deps.grid,
- gridLaunch: deps.gridLaunch,
+ gridLaunchRecord: deps.gridLaunchRecord,
codexHome: deps.codexHome,
+ dsh: deps.dsh,
bypassPermission: deps.bypassPermission,
})
if (pending) return { ok: true, spawned, pending }
diff --cc cli/src/lib/launchOverrides.ts
index 54f94a2b5,f6827842c..5cd4ba9b9
--- a/cli/src/lib/launchOverrides.ts
+++ b/cli/src/lib/launchOverrides.ts
@@@ -19,11 -18,10 +19,12 @@@ import
buildGridEngineLaunch,
gridConflictingEnvToClear,
type GridEngineLaunch,
+ type GridLaunchMachine,
type GridLaunchOverride,
+ type GridLaunchRecord,
} from './gridLaunch.js'
import { TMUX_SESSION_ENV_MIN } from './tmuxVersion.js'
+ import type { DshLaunch } from '../dsh/launch.js'
export interface LaunchOverrides {
/** Layered over the pane's inherited environment. The grid key lives here, and only here. */
@@@ -63,13 -57,10 +67,17 @@@ export interface LaunchOverridesDeps
export interface LaunchSource {
gridLaunch?: GridLaunchOverride | null
codexHome?: string | null
+ /**
+ * The engine's OWN model to come back to, when this relaunch is a move off a grid.
+ *
+ * Ignored while `gridLaunch` is set — that launch names its own model. Absent means "let the
+ * engine decide", which is what happens for an engine with no cited mechanism.
+ */
+ subscriptionModel?: string | null
+ /** The DSH the agent was created as; its env rides on every relaunch (`HARNESS_DSH` included). */
+ dsh?: string | null
+ /** The workspace, for the DSH's `${workspace}` — the registry row's `cwd`. */
+ cwd?: string | null
}
/** Fresh each time: callers hand `env` to tmux and may extend it, and a shared object would carry
diff --cc cli/src/lib/registry.ts
index 8dc1bab4d,38657345f..9090fe25c
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@@ -766,17 -765,12 +783,20 @@@ class Registry
gateway: raw.gateway === 'ori' ? 'ori' : null,
grid: normalizedGridAssignment(raw.grid),
codexHome: typeof rawCodexHome === 'string' && rawCodexHome ? rawCodexHome : null,
+ dsh: normalizedDshId((raw as { dsh?: unknown }).dsh),
...(rawGridLaunch !== undefined ? { gridLaunch: rawGridLaunch } : {}),
+ ...(rawGridLaunch ? { gridWebSearch: normalizedGridWebSearch(raw?.gridWebSearch) } : {}),
+ // ⚠️ Rehydrated EXPLICITLY, like every field above it. A row is rebuilt from this list on
+ // load, so a field added to the type and the setter but not to this list is written to
+ // disk and then silently dropped by the next load — which is exactly what happened, and
+ // it looks like "the setter never ran" rather than like a missing line here.
+ ...(typeof raw?.subscriptionModel === 'string' && raw.subscriptionModel
+ ? { subscriptionModel: raw.subscriptionModel }
+ : {}),
...(raw.bypassPermission === true ? { bypassPermission: true } : {}),
transcriptPath,
+ defaultName: typeof raw.defaultName === 'string' && /^agent-[1-9]\d*$/.test(raw.defaultName)
+ ? raw.defaultName : undefined,
title: titleDisplayName(typeof raw.title === 'string' ? raw.title : null),
sessionId: bound ? rawSessionId : '',
projectDir: !repairedCodexTranscript && typeof raw.projectDir === 'string' && raw.projectDir
@@@ -957,8 -954,8 +980,9 @@@
grid: input.grid ?? null,
// A discovered grid agent has no credential the daemon ever saw: it can be observed, not relaunched.
gridLaunch: null,
+ gridWebSearch: null,
codexHome: input.codexHome ?? null,
+ dsh: input.dsh ?? null,
transcriptPath: null,
projectDir: basename(input.cwd ?? '') || agentId,
cwd: input.cwd ?? null,
@@@ -988,9 -985,9 +1012,10 @@@
primaryRuntimeKey?: string
cwd?: string | null
grid?: GridAssignment | null
- gridLaunch?: GridLaunchOverride | null
+ /** The grid launch this pane was opened with and what it decided — the pair `setGridLaunch` keeps. */
+ gridLaunchRecord?: GridLaunchRecord | null
codexHome?: string | null
+ dsh?: string | null
bypassPermission?: boolean
}): RegisteredSession | null {
if (this.writeBlocked) return null
@@@ -1009,9 -1007,9 +1035,10 @@@
engine: input.engine,
gateway: null,
grid: input.grid ?? null,
- gridLaunch: input.gridLaunch ?? null,
+ gridLaunch: input.gridLaunchRecord?.override ?? null,
+ gridWebSearch: input.gridLaunchRecord?.webSearch ?? null,
codexHome: input.codexHome ?? null,
+ dsh: input.dsh ?? null,
...(input.bypassPermission ? { bypassPermission: true } : {}),
transcriptPath: null,
projectDir: basename(input.cwd ?? '') || agentId,
@@@ -1158,13 -1169,7 +1198,14 @@@
grid: existing?.grid ?? null,
// The credential-bearing launch. Like codexHome: written once, carried forward, never re-derived.
gridLaunch: existing?.gridLaunch ?? null,
+ // What that launch decided — it travels with the launch, or it is lost at the first hook.
+ gridWebSearch: existing?.gridWebSearch ?? null,
+ // ⚠️ Carried forward for the same reason, and it was missed once: a bind REBUILDS the row from
+ // named fields, so a field the rebuild does not name survives on disk and vanishes from
+ // memory the moment the engine reports in. The symptom is a move back to the engine's own
+ // login landing on a house default — the remembered model was there, then a hook bind ate it.
+ ...(existing?.subscriptionModel ? { subscriptionModel: existing.subscriptionModel } : {}),
+ defaultName: existing?.defaultName,
transcriptPath: effectiveTranscriptPath,
projectDir: engine === 'grok' || engine === 'agy' || engine === 'copilot'
? basename(input.cwd ?? existing?.cwd ?? '') || sessionId
@@@ -1369,28 -1375,23 +1411,39 @@@
return true
}
+ /** Fill in the DSH a row did not know (discovery read `HARNESS_DSH` off the live process). Never
+ * replaces one it already has — the harness is chosen once, at creation. */
+ setDsh(agentId: string, dsh: string): boolean {
+ const session = this.agents.get(agentId)
+ if (!session || session.dsh || !DSH_ID_RE.test(dsh)) return false
+ session.dsh = dsh
+ session.updatedAt = Date.now()
+ this.save()
+ return true
+ }
+
- /** Record the launch an agent was last put onto a grid with (`agent_create` / `agent_retarget`), or
- * null once it was moved back to the engine's own login. */
- setGridLaunch(agentId: string, gridLaunch: GridLaunchOverride | null): boolean {
+ /**
+ * Record the launch an agent was last put onto a grid with (`agent_create` / `agent_retarget`) and
+ * what it decided about web search — or null for both once the agent was moved back to the engine's
+ * own login. One call for the pair on purpose: a status without its launch, or a launch without its
+ * status, is a row the app would read wrongly.
+ */
+ setGridLaunch(agentId: string, launch: GridLaunchRecord | null): boolean {
+ const session = this.agents.get(agentId)
+ if (!session) return false
+ session.gridLaunch = launch?.override ?? null
+ session.gridWebSearch = launch?.webSearch ?? null
+ session.updatedAt = Date.now()
+ this.save()
+ return true
+ }
+
+ /** Remember the engine's own model an agent is leaving behind, so a later move back can restore it.
+ * Kept even while the agent is on a grid — it is the only record that the previous choice existed. */
+ setSubscriptionModel(agentId: string, model: string | null): boolean {
const session = this.agents.get(agentId)
if (!session) return false
- session.gridLaunch = gridLaunch
+ session.subscriptionModel = model
session.updatedAt = Date.now()
this.save()
return true
diff --cc desktop/lib/screens/swarm_screen.dart
index facf406f0,cab842e41..dd4d9b321
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@@ -289,10 -289,7 +293,11 @@@ class _SwarmScreenState extends State<S
}
void _syncNative() {
+ // ⚠️ Also from here, not only from `initState`. At init the machine list is still empty, so the
+ // first read returned nothing and the Local section sat on its empty state forever. This fires
+ // on every app change, throttled, so it lands as soon as a machine appears.
+ unawaited(_refreshLocalModels());
+ _syncMachines();
final payload = {
'enabled': _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen,
'activeId': app.activeSwarmId,
@@@ -371,16 -353,83 +361,91 @@@
unawaited(_channel.invokeMethod<void>('update', payload));
}
+ void _syncMachines() {
+ final openAgents = {
+ for (final tab in app.swarms)
+ for (final pane in tab.panes) (pane.machineId, pane.agentId),
+ };
+ final machines = app.machineStates.values.take(128);
+ // Compare only visible values before building/encoding a potentially large
+ // inventory. Tab focus, palette and attention changes use the small update
+ // message; they never resend or decode every agent on the native thread.
+ final presentation = <Object?>[
+ for (final machine in machines) ...[
+ (
+ machine.machine.machineId,
+ machine.machine.displayName,
+ machine.isLocalMachine,
+ machine.nodeOnline,
+ machine.needsLink,
+ machine.agents.isNotEmpty ||
+ machine.agentLoadStatus == AgentLoadStatus.loaded
+ ? machine.agents.length
+ : null,
+ ),
+ for (final agent in machine.agents.take(512))
+ (
+ agent.id,
+ agent.name,
+ agent.engine,
+ agent.terminalAvailable ||
+ openAgents.contains((machine.machine.machineId, agent.id)),
+ ),
+ ],
+ ];
+ if (listEquals(presentation, _machinesPresentation)) return;
+ _machinesPresentation = presentation;
+ unawaited(
+ _channel.invokeMethod<void>('machinesState', {
+ 'machines': [
+ for (final machine in machines)
+ {
+ 'id': machine.machine.machineId,
+ 'name': machine.machine.displayName,
+ 'local': machine.isLocalMachine,
+ 'agentCount':
+ machine.agents.isNotEmpty ||
+ machine.agentLoadStatus == AgentLoadStatus.loaded
+ ? machine.agents.length
+ : null,
+ 'agents': [
+ for (final agent in machine.agents.take(512))
+ {
+ 'id': agent.id,
+ 'title': agent.name,
+ 'engine': agent.engine,
+ 'iconAsset': engineIdentity(agent.engine).asset,
+ 'canOpen':
+ agent.terminalAvailable ||
+ openAgents.contains((
+ machine.machine.machineId,
+ agent.id,
+ )),
+ },
+ ],
+ 'status': machine.needsLink
+ ? 'Link required'
+ : machine.nodeOnline == false
+ ? 'Offline'
+ : machine.nodeOnline == true
+ ? 'Online'
+ : 'Connecting…',
+ },
+ ],
+ }),
+ );
+ }
+
void _syncModels() {
- final payload = {'subscriptions': _modelsMenu?.rows ?? []};
+ final payload = {
+ 'subscriptions': _modelsMenu?.rows ?? [],
+ // The Local section used to be two hardcoded names. A menu that names a model nobody is
+ // serving is worse than one admitting it has none, so this carries what the account's own
+ // grid actually answers with — refreshed below, and empty until the first read lands.
+ 'local': [
+ for (final m in _localModels) {'id': m.id, 'node': m.node},
+ ],
+ };
final encoded = jsonEncode(payload);
if (encoded == _modelsState) return;
_modelsState = encoded;
diff --cc desktop/lib/widgets/terminal_panel.dart
index 2bb53d3a2,8ac1c3a88..dad8ce9d6
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@@ -1514,117 -1517,108 +1518,131 @@@ class _TerminalHeader extends Stateless
child: LayoutBuilder(
builder: (context, constraints) => Row(
children: [
- EngineMark(engine: session.engineId, size: 17),
+ if (agent != null)
+ EngineMark.forAgent(agent, size: 17)
+ else
+ EngineMark(engine: session.engineId, size: 17),
+ // Icon and name, the same as every other pane (owner,
+ // 2026-09-15): a harness agent is its harness here, and the
+ // engine it runs on is the dialog's and the tooltip's to say.
const SizedBox(width: 10),
Expanded(
- child: Tooltip(
- message: identityDetail,
- waitDuration: const Duration(milliseconds: 700),
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onDoubleTap: () => unawaited(
- showAgentRenameDialog(
- context,
- notifier,
- session.machineId,
- session.agentId,
- session.agentName,
+ child: Row(
+ children: [
+ Flexible(
+ child: Tooltip(
+ message: identityDetail,
+ waitDuration: const Duration(milliseconds: 700),
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onDoubleTap: () => unawaited(
+ showAgentRenameDialog(
+ context,
+ notifier,
+ session.machineId,
+ session.agentId,
+ session.agentName,
+ ),
+ ),
+ child: Text(
+ session.agentName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppColors.text,
+ fontFamily: AppFonts.sans,
+ fontSize: 13,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
),
),
- child: Text(
- session.agentName,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppColors.text,
- fontFamily: AppFonts.sans,
- fontSize: 13,
- fontWeight: FontWeight.w600,
+ const SizedBox(width: 8),
+ if (status != null)
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: math.max(
+ 0,
+ math.min(
+ constraints.maxWidth * .22,
+ constraints.maxWidth - actionsWidth - 110,
+ ),
+ ),
+ ),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Tooltip(
+ message: status.detail,
+ child: TextButton(
+ onPressed: canReconnect
+ ? () => notifier.selectAgent(
+ session.machineId,
+ session.agentId,
+ )
+ : null,
+ style: TextButton.styleFrom(
+ foregroundColor: color,
+ disabledForegroundColor: AppColors.textSoft,
+ minimumSize: Size.zero,
+ tapTargetSize:
+ MaterialTapTargetSize.shrinkWrap,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6,
+ vertical: 4,
+ ),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(status.icon, size: 14),
+ const SizedBox(width: 6),
+ Flexible(
+ child: Text(
+ status.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 11),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ )
+ else if (!compact)
+ Padding(
+ padding: const EdgeInsets.all(4),
+ child: Icon(Icons.circle, size: 8, color: color),
),
- ),
- ),
+ ],
),
),
+ // The model picker sits next to the NAME, because that is the pair a person reads
+ // together: this agent, on that model. Hidden while a notice is showing — a header
+ // asking to reconnect is not the moment to offer a menu.
+ if (status == null && !readOnly) ...[
+ const SizedBox(width: 8),
+ GridModelPicker(
+ notifier: notifier,
+ machineId: session.machineId,
+ currentModel: agent?.gridModel,
+ webSearch: agent?.gridWebSearch,
+ engineLabel: session.engineId,
+ onSelected: (model) => unawaited(
+ notifier.retargetAgentToGridModel(
+ session.machineId,
+ session.agentId,
+ model.id,
+ ),
+ ),
+ onUseOwnLogin: () => unawaited(
+ notifier.clearAgentGrid(session.machineId, session.agentId),
+ ),
+ ),
+ ],
const SizedBox(width: 8),
- if (status != null)
- ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: math.max(
- 0,
- math.min(
- constraints.maxWidth * .3,
- constraints.maxWidth - actionsWidth - 110,
- ),
- ),
- ),
- child: Align(
- alignment: Alignment.centerRight,
- child: Tooltip(
- message: status.detail,
- child: TextButton(
- onPressed: canReconnect
- ? () => notifier.selectAgent(
- session.machineId,
- session.agentId,
- )
- : null,
- style: TextButton.styleFrom(
- foregroundColor: color,
- disabledForegroundColor: AppColors.textSoft,
- minimumSize: Size.zero,
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- padding: const EdgeInsets.symmetric(
- horizontal: 6,
- vertical: 4,
- ),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(status.icon, size: 14),
- const SizedBox(width: 6),
- Flexible(
- child: Text(
- status.label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(fontSize: 11),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- )
- else if (!compact)
- Padding(
- padding: const EdgeInsets.all(4),
- child: Icon(Icons.circle, size: 8, color: color),
- ),
// Which of the three paths carries this pane's bytes. Absent for a local machine's own
// terminal, which has no such distinction and so gets no badge.
//
diff --cc desktop/macos/Runner/SwarmTitlebar.swift
index de990b2cc,975309efa..c22b660c2
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@@ -59,13 -59,13 +59,16 @@@ final class SwarmTitlebar: NSObject, NS
self.strip.update(state)
self.window?.backgroundColor = self.strip.palette.tabBar
result(nil)
+ case "machinesState":
+ let state = call.arguments as? [String: Any] ?? [:]
+ self.updateMachines(state["machines"] as? [[String: Any]] ?? [])
+ result(nil)
case "modelsState":
let state = call.arguments as? [String: Any] ?? [:]
- self.updateModels(state["subscriptions"] as? [[String: Any]] ?? [])
+ self.updateModels(
+ state["subscriptions"] as? [[String: Any]] ?? [],
+ local: state["local"] as? [[String: Any]] ?? []
+ )
result(nil)
case "keymapState":
guard let payload = call.arguments as? [String: Any],
@@@ -337,11 -391,7 +413,11 @@@
}
}
section("Subscription")
- let rowWidth = subscriptions.map(SwarmSubscriptionView.preferredWidth).max() ?? 352
+ // One width across both sections. Measuring them separately let the menu's two halves size
+ // independently, so the trailing column stepped in or out at the section break.
+ let rowWidth = max(
- subscriptions.map(SwarmSubscriptionView.preferredWidth).max() ?? 440,
- localModels.map { SwarmSubscriptionView.preferredWidth(title: $0.0, account: "", status: $0.1) }.max() ?? 440)
++ subscriptions.map(SwarmSubscriptionView.preferredWidth).max() ?? 352,
++ localModels.map { SwarmSubscriptionView.preferredWidth(title: $0.0, account: "", status: $0.1) }.max() ?? 352)
for entry in subscriptions {
let item = NSMenuItem(title: entry.accessibilityLabel, action: nil, keyEquivalent: "")
let icon = historyIcons.image(engine: entry.engine, asset: entry.iconAsset)
@@@ -565,26 -653,12 +698,26 @@@ private final class SwarmSubscriptionVi
}
static func preferredWidth(_ entry: SwarmSubscriptionEntry) -> CGFloat {
- let identityWidth = textWidth(entry.title + " " + entry.account)
- let balanceWidth = textWidth(entry.status)
+ preferredWidth(title: entry.title, account: entry.account, status: entry.status)
+ }
+
+ static func preferredWidth(title: String, account: String, status: String) -> CGFloat {
+ let identityWidth = textWidth(title + " " + account)
+ let balanceWidth = textWidth(status)
- return min(720, max(440, identityWidth + balanceWidth + 88))
+ return min(576, max(352, identityWidth + balanceWidth + 88))
}
- init(entry: SwarmSubscriptionEntry, icon: NSImage, width: CGFloat) {
+ convenience init(entry: SwarmSubscriptionEntry, icon: NSImage, width: CGFloat) {
+ self.init(title: entry.title, account: entry.account, status: entry.status,
+ icon: icon, width: width, accessibility: entry.accessibilityLabel)
+ }
+
+ /// Every row in this menu is built here, subscription or local. Sharing the construction is what
+ /// keeps the two sections reading as one menu: same font, same label/secondary split, same icon
+ /// column, same right-aligned trailing field. Local rows were plain disabled `NSMenuItem`s before,
+ /// which AppKit greys wholesale, so a served model looked unavailable beside the accounts above.
+ init(title primary: String, account: String, status: String, icon: NSImage?, width: CGFloat,
+ accessibility: String, tint: NSColor? = nil) {
super.init(frame: NSRect(x: 0, y: 0, width: width, height: 26))
autoresizingMask = [.width]
self.icon.image = icon
diff --cc desktop/test/agent_model_test.dart
index 9c7baeafc,75d248d79..ad5b38b2c
--- a/desktop/test/agent_model_test.dart
+++ b/desktop/test/agent_model_test.dart
@@@ -59,48 -60,99 +60,143 @@@ void main()
expect(agent.launchError, 'ENGINE_DID_NOT_START');
expect(agent.launchDetail, 'Engine exited see terminal');
});
+
+ group('web search on a Local model', () {
+ Agent onGrid(Map<String, Object?> grid) => Agent.fromJson({
+ 'id': 'agent-1',
+ 'name': 'Local',
+ 'engine': 'claude',
+ 'grid': {'baseUrl': 'https://grid.example/grid-abc/relay', ...grid},
+ });
+
+ test('reads the status off the grid block', () {
+ expect(onGrid({'model': 'qwen', 'webSearch': 'on'}).gridWebSearch, GridWebSearch.on);
+ expect(
+ onGrid({'model': 'qwen', 'webSearch': 'unavailable'}).gridWebSearch,
+ GridWebSearch.unavailable,
+ );
+ expect(
+ onGrid({'model': 'qwen', 'webSearch': 'unsupported'}).gridWebSearch,
+ GridWebSearch.unsupported,
+ );
+ });
+
+ test('has nothing to say when the daemon said nothing, or said a word it does not know', () {
+ // An older daemon, or a grid agent the daemon merely discovered: no field at all.
+ expect(onGrid({'model': 'qwen'}).gridWebSearch, isNull);
+ // A newer daemon with a fourth word: not printed verbatim, not guessed at.
+ expect(onGrid({'model': 'qwen', 'webSearch': 'throttled'}).gridWebSearch, isNull);
+ expect(onGrid({'model': 'qwen', 'webSearch': 7}).gridWebSearch, isNull);
+ });
+
+ test('has nothing to say off a grid', () {
+ final own = Agent.fromJson({'id': 'agent-2', 'name': 'Own', 'grid': null});
+ expect(own.gridModel, isNull);
+ expect(own.gridWebSearch, isNull);
+ });
+
+ test('each degraded status is one sentence; on is none', () {
+ expect(GridWebSearch.unavailable.sentence, 'Web search unavailable');
+ expect(
+ GridWebSearch.unsupported.sentence,
+ 'Web search not supported by this engine',
+ );
+ expect(GridWebSearch.on.sentence, isNull);
+ });
+ });
}
+
+ // ── domain-specific harness fields ────────────────────────────────────────────
+
+ void _dshTests() {
+ test('parses the harness, viewer and verdict off an agent frame', () {
+ final agent = Agent.fromJson({
+ 'id': 'agent-1',
+ 'name': 'Board',
+ 'engine': 'claude',
+ 'dsh': 'autonomous/copper',
+ 'dshName': 'Copper',
+ 'viewerUrl': 'http://127.0.0.1:4179/?workspace=1',
+ 'verdict': {
+ 'ready': false,
+ 'summary': '2 errors, 1 warning',
+ 'errors': 2,
+ 'warnings': 1,
+ 'artifact': 'boards/main.board.json',
+ 'updatedAt': '2026-09-14T20:00:00Z',
+ },
+ });
+ expect(agent.engine, 'claude');
+ expect(agent.dsh, 'autonomous/copper');
+ expect(agent.dshName, 'Copper');
+ expect(agent.identityEngine, 'autonomous/copper');
+ expect(agent.identityDisplayName, 'Copper');
+ expect(agent.viewerUrl, 'http://127.0.0.1:4179/?workspace=1');
+ final verdict = agent.verdict!;
+ expect(verdict.ready, isFalse);
+ expect(verdict.summary, '2 errors, 1 warning');
+ expect(verdict.errors, 2);
+ expect(verdict.warnings, 1);
+ expect(verdict.artifact, 'boards/main.board.json');
+ expect(verdict.updatedAt, DateTime.utc(2026, 9, 14, 20));
+ expect(agent.copyWith(name: 'Renamed').verdict, verdict);
+ expect(agent.copyWith(name: 'Renamed').dsh, 'autonomous/copper');
+ });
+
+ test('a plain engine agent has none of them and draws as its engine', () {
+ final agent = Agent.fromJson({
+ 'id': 'agent-1',
+ 'name': 'a',
+ 'engine': 'codex',
+ });
+ expect(agent.dsh, isNull);
+ expect(agent.viewerUrl, isNull);
+ expect(agent.verdict, isNull);
+ expect(agent.identityEngine, 'codex');
+ });
+
+ test(
+ 'refuses a harness id, viewer URL or verdict outside the spec shape',
+ () {
+ Agent parse(Map<String, dynamic> extra) =>
+ Agent.fromJson({'id': 'agent-1', 'name': 'a', ...extra});
+ // The id is owner/name; a bare word, a deeper path, or an upper-case one is not.
+ expect(parse({'dsh': 'circuit'}).dsh, isNull);
+ expect(parse({'dsh': 'a/b/c'}).dsh, isNull);
+ expect(parse({'dsh': 'Autonomous/Circuit'}).dsh, isNull);
+ expect(parse({'dsh': 'autonomous/../etc'}).dsh, isNull);
+ // The viewer URL lands in a webview: http(s) with a host, no whitespace, no control bytes.
+ expect(parse({'viewerUrl': 'file:///etc/passwd'}).viewerUrl, isNull);
+ expect(parse({'viewerUrl': 'javascript:alert(1)'}).viewerUrl, isNull);
+ expect(
+ parse({'viewerUrl': 'http://127.0.0.1:4179/a b'}).viewerUrl,
+ isNull,
+ );
+ expect(parse({'viewerUrl': 'http://\n127.0.0.1/'}).viewerUrl, isNull);
+ expect(
+ parse({'viewerUrl': 'https://viewer.local/x'}).viewerUrl,
+ 'https://viewer.local/x',
+ );
+ // A verdict without the one required fact is no verdict; counts never go negative or absurd.
+ expect(
+ parse({
+ 'verdict': {'summary': 'x'},
+ }).verdict,
+ isNull,
+ );
+ expect(parse({'verdict': 'ready'}).verdict, isNull);
+ final odd = parse({
+ 'verdict': {
+ 'ready': true,
+ 'errors': -3,
+ 'warnings': 1e9,
+ 'summary': 'ok\u0000\u0001',
+ },
+ }).verdict!;
+ expect(odd.errors, 0);
+ expect(odd.warnings, 9999);
+ expect(odd.summary, 'ok');
+ expect(odd.updatedAt, isNull);
+ },
+ );
+ }