Skip to content
Merged
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Switching the model or method of a configured agent that is stopped, paused or not in the runtime no longer fails with "Model switch failed: agent <name> not found": the choice is saved to both config layers without restarting the agent and the dashboard says "saved; applies when <agent> starts", while a genuinely unknown agent still fails and lists the valid names; and switching an agent's method, model or reasoning effort no longer scrolls the dashboard away from that agent, drops focus from the dropdown used, or re-sorts the cards. (#18905, #18906).
11 changes: 11 additions & 0 deletions src/docs/agent-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,17 @@ Two consequences worth knowing:
- **Model validation does not save you here.** `POST /api/model/...` checks the model against the agent's *current effective* backend, and deliberately fails **open** when that backend's model list cannot be enumerated (see `validateModelForAgent`). Codex is exactly such a backend, so `switch` to codex followed by `model` set to a Claude id is accepted. Reverse the order and the model is validated against the backend you are about to leave. Neither order gives you a checked pair.
- **The atomic route does not restart the agent.** It persists the pair and syncs it into the live process config, so the running CLI keeps its current method until the agent next restarts. That is usually what you want for a scripted change — the two-call path pays for two restarts — but if you need the change to take effect now, restart the agent afterwards.

### Switching the method or model of an agent that is not running

`POST /api/switch/{agent}/{backend}` and `POST /api/model/{agent}/{model}` accept a change for any **configured** agent, not only a live one ([#18905](https://github.com/hivecommons/hive/issues/18905)). An agent can be configured but absent from the runtime (stopped, held back by the ACMM level gate) or present but paused:

- **Not in the runtime (stopped or gated):** the choice is persisted to both config layers (`hive.yaml` and the per-agent overlay, see [config-layering](config-layering.md)), marked operator-owned, and nothing is restarted. The model is validated against the agent's saved backend and a backend against the supported list or a configured gateway name, exactly as for a running agent.
- **Paused or stopped in the runtime:** the override is set and persisted as usual, but the agent is **not** restarted, so a model change does not wake a paused agent.

In both cases the response is `{"ok": true, "applied": false, "message": "saved; applies when <agent> starts", ...}` and the dashboard shows that message instead of "session restarted". A live switch is unchanged and carries no `applied` field. A name that is neither running nor configured still fails with `400` and `agent <name> not found (valid agents: ...)`.

On the dashboard, switching an agent's method, model or reasoning effort keeps the page where it was: the re-render re-pins the window to the same agent card, returns focus to the dropdown you used (including after the model list reloads), and never re-sorts the cards ([#18906](https://github.com/hivecommons/hive/issues/18906)).

### `launch_cmd` and `backend`

`backend` is the operator-owned field; `launch_cmd` is derived from it. The two must agree: a `launch_cmd` whose executable is a different agentic CLI than `backend` names (say `backend: codex` next to `launch_cmd: /usr/bin/bob …`) is rejected by config validation, because the agent would be launched as one CLI and health-checked as another. Hive enforces this on every path that can move the two apart:
Expand Down
176 changes: 176 additions & 0 deletions src/pkg/dashboard/agent_model_switch_not_running_18905_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package dashboard

import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"

"github.com/hivecommons/hive/pkg/config"
)

const (
notRunningTestAgent = "supervisor"
notRunningTestModel = "opus"
notRunningTestMethod = "gemini"
)

// notRunningServer returns a server whose config carries an extra agent that the
// runtime does not instantiate (stopped, or held back by the ACMM gate), with an
// agents overlay directory so the second config layer is observable.
func notRunningServer(t *testing.T) (*Server, string) {
t.Helper()
s, deps := apiServer(t)
dir := t.TempDir()
deps.Config.Data.AgentsDir = dir
deps.Config.Agents[notRunningTestAgent] = config.AgentConfig{Backend: "claude", Model: "sonnet", Enabled: true}
return s, dir
}

func decodeBody18905(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("decode %q: %v", rec.Body.String(), err)
}
return body
}

func overlayText(t *testing.T, dir string) string {
t.Helper()
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("read overlay dir: %v", err)
}
var sb strings.Builder
for _, e := range entries {
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
t.Fatalf("read overlay %s: %v", e.Name(), err)
}
sb.Write(b)
}
return sb.String()
}

// A configured agent the runtime does not hold (stopped) accepts a model change
// by persisting it to both config layers, and says it applies on next start.
func TestHandleModelSet_StoppedConfiguredAgentSaves(t *testing.T) {
s, dir := notRunningServer(t)
rec := doPost(s, "/api/model/"+notRunningTestAgent+"/"+notRunningTestModel, nil)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (%s)", rec.Code, rec.Body.String())
}
body := decodeBody18905(t, rec)
if body["ok"] != true || body["applied"] != false {
t.Fatalf("want ok=true applied=false, got %v", body)
}
if want := "saved; applies when " + notRunningTestAgent + " starts"; body["message"] != want {
t.Fatalf("message = %v, want %q", body["message"], want)
}
got := s.deps.Config.Agents[notRunningTestAgent]
if got.Model != notRunningTestModel || got.ModelOwner != config.FieldOwnerOperator {
t.Fatalf("in-memory config not updated: %+v", got)
}
if !strings.Contains(overlayText(t, dir), notRunningTestModel) {
t.Fatalf("agent overlay layer does not carry the saved model")
}
}

func TestHandleSwitch_StoppedConfiguredAgentSaves(t *testing.T) {
s, dir := notRunningServer(t)
rec := doPost(s, "/api/switch/"+notRunningTestAgent+"/"+notRunningTestMethod, nil)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (%s)", rec.Code, rec.Body.String())
}
body := decodeBody18905(t, rec)
if body["applied"] != false || !strings.Contains(body["message"].(string), "applies when "+notRunningTestAgent+" starts") {
t.Fatalf("unexpected body %v", body)
}
if got := s.deps.Config.Agents[notRunningTestAgent]; got.Backend != notRunningTestMethod {
t.Fatalf("backend = %q, want %q", got.Backend, notRunningTestMethod)
}
if !strings.Contains(overlayText(t, dir), notRunningTestMethod) {
t.Fatalf("agent overlay layer does not carry the saved backend")
}
}

func TestHandleSwitch_StoppedConfiguredAgentRejectsBadBackend(t *testing.T) {
s, _ := notRunningServer(t)
rec := doPost(s, "/api/switch/"+notRunningTestAgent+"/not-a-backend", nil)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", rec.Code)
}
if got := s.deps.Config.Agents[notRunningTestAgent]; got.Backend != "claude" {
t.Fatalf("rejected backend must not be saved, got %q", got.Backend)
}
}

// A paused agent the runtime does hold accepts the change and is not restarted
// into running: the response says it applies on start and the pause survives.
func TestHandleModelSet_PausedAgentSavesWithoutRestart(t *testing.T) {
s, deps := apiServer(t)
if err := deps.AgentMgr.Pause("scanner", "test", "paused for 18905"); err != nil {
t.Fatalf("Pause: %v", err)
}
rec := doPost(s, "/api/model/scanner/"+notRunningTestModel, nil)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (%s)", rec.Code, rec.Body.String())
}
body := decodeBody18905(t, rec)
if body["applied"] != false || body["message"] != "saved; applies when scanner starts" {
t.Fatalf("unexpected body %v", body)
}
proc, err := deps.AgentMgr.GetStatus("scanner")
if err != nil || proc == nil {
t.Fatalf("GetStatus: %v", err)
}
if !proc.Paused {
t.Fatalf("model change must not resume a paused agent")
}
if proc.ModelOverride != notRunningTestModel {
t.Fatalf("ModelOverride = %q, want %q", proc.ModelOverride, notRunningTestModel)
}
if got := deps.Config.Agents["scanner"]; got.Model != notRunningTestModel {
t.Fatalf("config model = %q, want %q", got.Model, notRunningTestModel)
}
}

// A name that is neither running nor configured is still not found, and the
// error lists the valid names.
func TestHandleModelSet_UnknownAgentListsValidNames(t *testing.T) {
s, _ := notRunningServer(t)
for _, path := range []string{"/api/model/ghost/opus", "/api/switch/ghost/gemini"} {
rec := doPost(s, path, nil)
if rec.Code != http.StatusBadRequest {
t.Fatalf("%s: status = %d, want 400", path, rec.Code)
}
msg, _ := decodeBody18905(t, rec)["error"].(string)
if !strings.Contains(msg, "agent ghost not found") ||
!strings.Contains(msg, "scanner") || !strings.Contains(msg, notRunningTestAgent) {
t.Fatalf("%s: error %q must say not found and list valid names", path, msg)
}
}
}

// An agent the runtime holds still gets its override set. The test runtime never
// launches agents, so scanner reads as stopped and answers "saved"; a launched
// agent answers "model_set" with no applied field. Either way the runtime
// override is set and the call succeeds.
func TestHandleModelSet_RegisteredAgentSetsOverride(t *testing.T) {
s, deps := apiServer(t)
rec := doPost(s, "/api/model/scanner/"+notRunningTestModel, nil)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
body := decodeBody18905(t, rec)
if body["ok"] != true {
t.Fatalf("want ok=true, got %v", body)
}
if proc, _ := deps.AgentMgr.GetStatus("scanner"); proc == nil || proc.ModelOverride != notRunningTestModel {
t.Fatalf("runtime ModelOverride not set")
}
}
167 changes: 167 additions & 0 deletions src/pkg/dashboard/agent_switch_viewport_18906.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
// #18906: switching an agent's method/model/effort must not scroll the page away
// from that agent, drop focus from the control just used, or re-sort the list.
const test = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');

const js = n => fs.readFileSync(path.join(__dirname, 'static-src', 'js', n), 'utf8');
const cards = js('agent-cards.js');
const controls = js('plan-agent-controls.js');

// Pull a top-level `function name(...) {...}` out of a source by brace matching.
function fn(src, name) {
const start = src.indexOf('function ' + name + '(');
assert.ok(start >= 0, name + ' not found');
let i = src.indexOf('{', src.indexOf(')', start));
let depth = 0;
for (; i < src.length; i++) {
if (src[i] === '{') depth++;
else if (src[i] === '}' && --depth === 0) return src.slice(start, i + 1);
}
throw new Error('unbalanced ' + name);
}

const NAMES = ['agentCssEscape', 'agentFocusSnapshot', 'agentFocusRestore', 'agentViewportCapture', 'agentViewportRestore', 'withAgentViewportPreserved'];
const body = [
'const AGENT_VIEWPORT_MIN_DELTA_PX = 1;',
...NAMES.map(n => fn(cards, n)),
'return { ' + NAMES.join(', ') + ' };',
].join('\n');

// A minimal fake page: a window with a scroll offset and a grid of cards laid
// out top to bottom. `shift` adds height above the anchor card after a render,
// which is what a resized neighbour or a rebuilt select does to the real page.
function makePage(order, heights) {
const state = { scrollY: 300, scrollX: 0, active: null, focusLog: [], order: order.slice(), heights: Object.assign({}, heights), extraAbove: 0 };
const controlsByKey = new Map();
const cardTop = name => {
let y = state.extraAbove - state.scrollY;
for (const n of state.order) { if (n === name) return y; y += state.heights[n]; }
return null;
};
const makeCard = name => ({
getAttribute: a => (a === 'data-agent' ? name : null),
getClientRects: () => [{}],
getBoundingClientRect: () => { const top = cardTop(name); return { top, bottom: top + state.heights[name], height: state.heights[name] }; },
});
const makeControl = (agent, action, disabled) => {
const attrs = { 'data-agent': agent, 'data-change-action': action };
const el = { id: '', disabled: !!disabled, getAttribute: a => attrs[a] || null, focus: opts => { state.focusLog.push(opts); state.active = el; } };
controlsByKey.set(agent + '|' + action, el);
return el;
};
const window_ = {
get scrollY() { return state.scrollY; }, get scrollX() { return state.scrollX; }, innerHeight: 800,
scrollBy: (x, y) => { state.scrollY += y; },
scrollTo: (x, y) => { state.scrollX = x; state.scrollY = y; },
};
const grid = {
querySelectorAll: sel => (sel === '.agent-card[data-agent]' ? state.order.map(makeCard) : []),
querySelector: sel => {
const m = sel.match(/data-agent="([^"]+)"\]$/);
return m && state.order.includes(m[1]) ? makeCard(m[1]) : null;
},
};
const document_ = {
body: { tag: 'body' },
get activeElement() { return state.active || document_.body; },
getElementById: id => (id === 'agents' ? grid : null),
querySelector: sel => {
const m = sel.match(/data-agent="([^"]+)"\]\[data-change-action="([^"]+)"\]$/);
return m ? controlsByKey.get(m[1] + '|' + m[2]) || null : null;
},
};
const api = new Function('window', 'document', 'requestAnimationFrame', body)(window_, document_, undefined);
return { state, api, makeControl, window: window_ };
}

const ORDER = ['guide', 'scanner', 'supervisor', 'reviewer'];
const HEIGHTS = { guide: 400, scanner: 400, supervisor: 400, reviewer: 400 };

test('scroll position is re-pinned to the switched agent after a re-render that resizes content above it', () => {
const p = makePage(ORDER, HEIGHTS);
const before = p.state.scrollY;
p.api.withAgentViewportPreserved('scanner', () => {
// Re-render: the card above grows by 120px (new log lines, rebuilt select).
p.state.extraAbove = 120;
});
// The card's viewport offset is unchanged, so the window moved by the shift.
assert.strictEqual(p.state.scrollY, before + 120);
});

test('no correction when nothing shifted', () => {
const p = makePage(ORDER, HEIGHTS);
p.api.withAgentViewportPreserved('scanner', () => {});
assert.strictEqual(p.state.scrollY, 300);
});

test('the list order is never changed by the guard or by a setting change', () => {
const p = makePage(ORDER, HEIGHTS);
const keysBefore = p.state.order.slice();
p.api.withAgentViewportPreserved('supervisor', () => { /* a.cli/a.model updated in place */ });
assert.deepStrictEqual(p.state.order, keysBefore);
assert.ok(!/\.sort\(|\.reverse\(|splice\(|unshift\(/.test(fn(cards, 'withAgentViewportPreserved') + fn(cards, 'agentViewportCapture') + fn(cards, 'agentViewportRestore')),
'viewport helpers must not reorder cards');
});

test('focus returns to the select that was used, without scrolling', () => {
const p = makePage(ORDER, HEIGHTS);
const sel = p.makeControl('scanner', 'switchModel');
p.state.active = sel;
const snap = p.api.agentFocusSnapshot(sel);
assert.deepStrictEqual(snap, { agent: 'scanner', action: 'switchModel', change: true });
// Re-render replaces the select: focus drops to <body> and a new node exists.
p.state.active = null;
const replacement = p.makeControl('scanner', 'switchModel');
p.api.withAgentViewportPreserved('scanner', () => {}, snap);
assert.strictEqual(p.state.active, replacement);
assert.deepStrictEqual(p.state.focusLog, [{ preventScroll: true }]);
});

test('a disabled control is not focused (loading-models state) and focus is restored once re-enabled', () => {
const p = makePage(ORDER, HEIGHTS);
const sel = p.makeControl('scanner', 'switchModel', true);
const snap = { agent: 'scanner', action: 'switchModel', change: true };
p.api.withAgentViewportPreserved('scanner', () => {}, snap);
assert.strictEqual(p.state.active, null);
sel.disabled = false;
p.api.withAgentViewportPreserved('scanner', () => {}, snap);
assert.strictEqual(p.state.active, sel);
});

test('focus the operator moved elsewhere during the switch is not stolen back', () => {
const p = makePage(ORDER, HEIGHTS);
const other = p.makeControl('guide', 'switchCli');
p.makeControl('scanner', 'switchModel');
p.state.active = other;
p.api.withAgentViewportPreserved('scanner', () => {}, { agent: 'scanner', action: 'switchModel', change: true });
assert.strictEqual(p.state.active, other);
});

test('page scroll is restored when the anchor card is gone', () => {
const p = makePage(ORDER, HEIGHTS);
p.api.withAgentViewportPreserved('scanner', () => { p.state.order = []; p.state.scrollY = 0; });
assert.strictEqual(p.state.scrollY, 300);
});

test('all three switch handlers re-render inside the viewport guard and keep the control focus', () => {
for (const name of ['switchCli', 'switchModel', 'switchEffort']) {
const src = fn(controls, name);
assert.ok(src.includes('agentFocusSnapshot(document.activeElement)'), name + ' must snapshot focus before the request');
assert.ok(/withAgentViewportPreserved\(agent, \(\) => \{[\s\S]*renderAgents\(window\._lastAgents\)/.test(src), name + ' must render inside the guard');
}
const dd = fn(controls, 'updateModelDropdown');
assert.strictEqual((dd.match(/withAgentViewportPreserved\(/g) || []).length, 3, 'every model-dropdown rewrite is guarded');
});

test('renderAgents restores focus for id-less controls by agent and action', () => {
const src = fn(cards, 'renderAgents');
assert.ok(src.includes('agentFocusSnapshot(document.activeElement)'));
assert.ok(src.includes('agentFocusRestore(focusSnap)'));
});

test('the server\'s saved-not-running message reaches the toast', () => {
assert.ok(fn(controls, 'switchModel').includes('data.applied === false && data.message'));
assert.ok(fn(controls, 'switchCli').includes('data.applied === false && data.message'));
});
Loading
Loading