From 3e8f235447fc349b69a850bac5430ee1bcc9a61f Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 00:09:04 -0500 Subject: [PATCH 1/4] =?UTF-8?q?=F0=9F=90=9B=20fix:=20model/method=20switch?= =?UTF-8?q?=20for=20a=20stopped=20or=20paused=20agent,=20and=20keep=20the?= =?UTF-8?q?=20page=20in=20place=20after=20a=20switch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes the not-found failure for configured agents the runtime does not hold and holds scroll, focus and card order across the re-render. Signed-off-by: Andrew Anderson --- ...906-agent-switch-not-running-and-scroll.md | 1 + src/docs/agent-configuration.md | 11 ++ ...ent_model_switch_not_running_18905_test.go | 177 ++++++++++++++++++ .../agent_switch_viewport_18906.test.js | 167 +++++++++++++++++ src/pkg/dashboard/api_agent_control.go | 135 ++++++++++++- .../dashboard/static-src/js/agent-cards.js | 75 ++++++++ .../static-src/js/plan-agent-controls.js | 82 ++++---- src/pkg/dashboard/static/index.html | 157 ++++++++++++---- 8 files changed, 730 insertions(+), 75 deletions(-) create mode 100644 changelog.d/fixed-18905-18906-agent-switch-not-running-and-scroll.md create mode 100644 src/pkg/dashboard/agent_model_switch_not_running_18905_test.go create mode 100644 src/pkg/dashboard/agent_switch_viewport_18906.test.js diff --git a/changelog.d/fixed-18905-18906-agent-switch-not-running-and-scroll.md b/changelog.d/fixed-18905-18906-agent-switch-not-running-and-scroll.md new file mode 100644 index 0000000000..8a7057f556 --- /dev/null +++ b/changelog.d/fixed-18905-18906-agent-switch-not-running-and-scroll.md @@ -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 not found": the choice is saved to both config layers without restarting the agent and the dashboard says "saved; applies when 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). diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index c4d39f988f..4d8e8c819f 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -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 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 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: diff --git a/src/pkg/dashboard/agent_model_switch_not_running_18905_test.go b/src/pkg/dashboard/agent_model_switch_not_running_18905_test.go new file mode 100644 index 0000000000..8b879c8b11 --- /dev/null +++ b/src/pkg/dashboard/agent_model_switch_not_running_18905_test.go @@ -0,0 +1,177 @@ +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) + } + } +} + +// A live agent keeps the original contract: the switch is applied (no +// applied=false / saved message). +func TestHandleModelSet_RunningAgentStillApplies(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["status"] != "model_set" { + t.Fatalf("status field = %v, want model_set", body["status"]) + } + if _, has := body["applied"]; has { + t.Fatalf("a live switch must not carry applied=false: %v", body) + } + if proc, _ := deps.AgentMgr.GetStatus("scanner"); proc == nil || proc.ModelOverride != notRunningTestModel { + t.Fatalf("live ModelOverride not set") + } +} diff --git a/src/pkg/dashboard/agent_switch_viewport_18906.test.js b/src/pkg/dashboard/agent_switch_viewport_18906.test.js new file mode 100644 index 0000000000..8a4c5e5b2f --- /dev/null +++ b/src/pkg/dashboard/agent_switch_viewport_18906.test.js @@ -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 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')); +}); diff --git a/src/pkg/dashboard/api_agent_control.go b/src/pkg/dashboard/api_agent_control.go index 65b5c2091a..cb0bb57ac4 100644 --- a/src/pkg/dashboard/api_agent_control.go +++ b/src/pkg/dashboard/api_agent_control.go @@ -311,15 +311,20 @@ func (s *Server) validateModelForAgent(name, model string) error { if model == "" { return fmt.Errorf("model must not be empty") } - proc, err := s.deps.AgentMgr.GetStatus(name) - if err != nil || proc == nil { - // Agent lookup failures are reported by the caller's SetModelOverride. + var backend string + if proc, err := s.deps.AgentMgr.GetStatus(name); err == nil && proc != nil { + backend = proc.Config.Backend + if proc.BackendOverride != "" { + backend = proc.BackendOverride + } + } else if ac, ok := s.configuredAgent(name); ok { + // Configured but not instantiated in the runtime (stopped, paused or + // held back by the ACMM gate): validate against its saved backend. + backend = ac.Backend + } else { + // Unknown agents are reported by the caller. return nil } - backend := proc.Config.Backend - if proc.BackendOverride != "" { - backend = proc.BackendOverride - } known := s.modelIDsForBackend(backend) if len(known) == 0 { @@ -340,6 +345,61 @@ func (s *Server) validateModelForAgent(name, model string) error { model, backend, strings.Join(known, ", ")) } +// runningAgentProcess returns the runtime's process for name, or nil when the +// agent is not instantiated in the runtime. A configured agent can be absent +// from the runtime (for example one held back by the ACMM level gate), so a nil +// result does not mean the name is unknown: see configuredAgent. +func (s *Server) runningAgentProcess(name string) *crux.Process { + proc, err := s.deps.AgentMgr.GetStatus(name) + if err != nil { + return nil + } + return proc +} + +// configuredAgent looks name up in the saved configuration. +func (s *Server) configuredAgent(name string) (config.AgentConfig, bool) { + if s.deps == nil || s.deps.Config == nil { + return config.AgentConfig{}, false + } + ac, ok := s.deps.Config.Agents[name] + return ac, ok +} + +// agentHoldsNoSession reports whether proc is paused or stopped, so a model or +// backend change is saved for the next start instead of restarting a session. +func agentHoldsNoSession(proc *crux.Process) bool { + return proc != nil && (proc.Paused || proc.State == crux.StatePaused || proc.State == crux.StateStopped) +} + +// unknownAgentMessage is the not-found error for a name that is neither running +// nor configured, listing the valid names so a typo is fixable at a glance. +func (s *Server) unknownAgentMessage(name string) string { + names := make([]string, 0) + if s.deps != nil && s.deps.Config != nil { + for n := range s.deps.Config.Agents { + names = append(names, n) + } + } + sort.Strings(names) + return fmt.Sprintf("agent %s not found (valid agents: %s)", name, strings.Join(names, ", ")) +} + +// savedNotRunningResponse is the success body for a model or backend change +// persisted for an agent that is not running. applied=false tells the client +// that no session was restarted; message is shown to the operator verbatim. +func savedNotRunningResponse(status, name, field, value string, minStatusSeq uint64) map[string]any { + return map[string]any{ + "ok": true, + "status": status, + "applied": false, + "agent": name, + field: value, + "message": fmt.Sprintf("saved; applies when %s starts", name), + "minStatusSeq": minStatusSeq, + } +} + func (s *Server) handleSwitch(w http.ResponseWriter, r *http.Request) { // Owner-only, matching handleEffortSet: switching backends persists to // hive.yaml, claims operator field-ownership, and restarts the agent (#6557). @@ -349,6 +409,29 @@ func (s *Server) handleSwitch(w http.ResponseWriter, r *http.Request) { name := s.resolveAgentParam(r.PathValue("agent")) backend := sanitizeString(r.PathValue("backend")) + proc := s.runningAgentProcess(name) + if proc == nil { + // Configured but not instantiated in the runtime: persist the choice + // so it applies when the agent starts (#18905). Unknown names get the + // not-found error with the valid names. + if _, ok := s.configuredAgent(name); !ok { + jsonError(w, s.unknownAgentMessage(name), http.StatusBadRequest) + return + } + if backend != "" && !config.IsCLIBackend(backend) && !config.IsInferenceBackend(backend) && + s.deps.Config.Governor.ResolveGateway(backend) == nil { + jsonError(w, fmt.Sprintf("unsupported backend %q (supported: %s; or the name of a configured model gateway)", + backend, strings.Join(config.SupportedBackends(), ", ")), http.StatusBadRequest) + return + } + s.claimAgentFieldOwnership(name, "", backend) + s.deps.Logger.Info("audit: backend saved for agent not running", "agent", name, "backend", backend, "trigger", "dashboard-api") + s.auditFromRequest(r, "switch_backend", auditDetail("backend", backend), name) + minStatusSeq := s.refreshAndPersistSeq() + jsonResponse(w, savedNotRunningResponse("backend_saved", name, "backend", backend, minStatusSeq)) + return + } + if err := s.deps.AgentMgr.SetBackendOverride(name, backend); err != nil { jsonError(w, err.Error(), http.StatusBadRequest) return @@ -361,7 +444,14 @@ func (s *Server) handleSwitch(w http.ResponseWriter, r *http.Request) { s.deps.Logger.Info("audit: backend switched", "agent", name, "backend", backend, "trigger", "dashboard-api") s.auditFromRequest(r, "switch_backend", auditDetail("backend", backend), name) - // Restart the agent session so the new backend takes effect immediately. + // Restart the agent session so the new backend takes effect immediately — + // unless the agent is stopped or paused, where a restart would be wrong: + // the saved choice applies when it next starts. + if agentHoldsNoSession(proc) { + minStatusSeq := s.refreshAndPersistSeq() + jsonResponse(w, savedNotRunningResponse("backend_saved", name, "backend", backend, minStatusSeq)) + return + } if err := s.deps.AgentMgr.Restart(s.deps.Ctx, name); err != nil { s.deps.Logger.Warn("restart after backend switch failed", "agent", name, "error", err) } @@ -379,6 +469,14 @@ func (s *Server) handleModelSet(w http.ResponseWriter, r *http.Request) { name := s.resolveAgentParam(r.PathValue("agent")) model := sanitizeString(r.PathValue("model")) + proc := s.runningAgentProcess(name) + if proc == nil { + if _, ok := s.configuredAgent(name); !ok { + jsonError(w, s.unknownAgentMessage(name), http.StatusBadRequest) + return + } + } + // Reject a model the effective backend cannot serve BEFORE storing it. // Silently accepting an unusable value and then falling back at launch is // what made this class of bug invisible: the grid showed the choice, the @@ -388,6 +486,18 @@ func (s *Server) handleModelSet(w http.ResponseWriter, r *http.Request) { return } + if proc == nil { + // Configured but not instantiated in the runtime (stopped, paused or + // held back by the ACMM gate): persist the choice to both config + // layers so it applies when the agent starts (#18905). + s.claimAgentFieldOwnership(name, model, "") + s.deps.Logger.Info("audit: model saved for agent not running", "agent", name, "model", model, "trigger", "dashboard-api") + s.auditFromRequest(r, "set_model", auditDetail("model", model), name) + minStatusSeq := s.refreshAndPersistSeq() + jsonResponse(w, savedNotRunningResponse("model_saved", name, "model", model, minStatusSeq)) + return + } + if err := s.deps.AgentMgr.SetModelOverride(name, model); err != nil { jsonError(w, err.Error(), http.StatusBadRequest) return @@ -400,7 +510,14 @@ func (s *Server) handleModelSet(w http.ResponseWriter, r *http.Request) { s.deps.Logger.Info("audit: model set", "agent", name, "model", model, "trigger", "dashboard-api") s.auditFromRequest(r, "set_model", auditDetail("model", model), name) - // Restart the agent session so the new model takes effect immediately. + // Restart the agent session so the new model takes effect immediately — + // unless the agent is stopped or paused: the saved choice applies when it + // next starts, and a restart must not wake it. + if agentHoldsNoSession(proc) { + minStatusSeq := s.refreshAndPersistSeq() + jsonResponse(w, savedNotRunningResponse("model_saved", name, "model", model, minStatusSeq)) + return + } if err := s.deps.AgentMgr.Restart(s.deps.Ctx, name); err != nil { s.deps.Logger.Warn("restart after model switch failed", "agent", name, "error", err) } diff --git a/src/pkg/dashboard/static-src/js/agent-cards.js b/src/pkg/dashboard/static-src/js/agent-cards.js index 2ae99d0cd4..d2e7455371 100644 --- a/src/pkg/dashboard/static-src/js/agent-cards.js +++ b/src/pkg/dashboard/static-src/js/agent-cards.js @@ -936,6 +936,7 @@ // Preserve custom prompt input values across re-renders const savedInputs = {}; const focusedId = document.activeElement?.id; + const focusSnap = agentFocusSnapshot(document.activeElement); el.querySelectorAll('.kick-prompt').forEach(inp => { if (inp.value) savedInputs[inp.id] = inp.value; }); @@ -1147,6 +1148,9 @@ const prev = document.getElementById(focusedId); if (prev) { try { prev.focus({ preventScroll: true }); } catch (e) { prev.focus(); } } } + // Controls without an id (the method/model/effort selects) are matched + // by agent + action so a replaced that was just used is replaced (its options changed), which + // drops focus, and the rows above/below resize, which moved the page away + // from the agent. These helpers hold the reader's place across such a + // synchronous re-render: the window scroll is re-pinned to the same card by + // key (delta based, so it composes with the scroll stabilizer), and focus + // returns to the same control by id or by (agent, action). Card ORDER is + // never touched here: a setting change must not re-sort the list. + const AGENT_VIEWPORT_MIN_DELTA_PX = 1; + function agentCssEscape(v) { + return (window.CSS && CSS.escape) ? CSS.escape(String(v)) : String(v).replace(/["\\]/g, '\\$&'); + } + function agentFocusSnapshot(el) { + if (!el || el === document.body || typeof el.getAttribute !== 'function') return null; + if (el.id) return { id: el.id }; + const agent = el.getAttribute('data-agent'); + const action = el.getAttribute('data-change-action') || el.getAttribute('data-action'); + return (agent && action) ? { agent, action, change: !!el.getAttribute('data-change-action') } : null; + } + function agentFocusRestore(snap) { + if (!snap) return; + let el = null; + if (snap.id) { + el = document.getElementById(snap.id); + } else { + const attr = snap.change ? 'data-change-action' : 'data-action'; + el = document.querySelector(`#agents [data-agent="${agentCssEscape(snap.agent)}"][${attr}="${agentCssEscape(snap.action)}"]`); + } + if (!el || el.disabled || document.activeElement === el) return; + try { el.focus({ preventScroll: true }); } catch (e) { el.focus(); } + } + function agentViewportCapture(agentName, fallbackFocus) { + // fallbackFocus: the control focused when the switch began, used only when + // focus has since dropped to (a disabled drops focus to , and the option + // swap resizes it; both are re-pinned so the page does not move (#18906). + withAgentViewportPreserved(agent, () => modelSelects.forEach(sel => { sel.innerHTML = ''; sel.disabled = true; - }); + }), focusSnap); const models = isInference ? await fetchInferenceModels(canonicalInferenceBackendName(backend)) : (await fetchBackendsConfig(), modelsForBackend(backend)); - modelSelects.forEach(sel => { + withAgentViewportPreserved(agent, () => modelSelects.forEach(sel => { sel.innerHTML = '' + models.map(m => ``).join(''); sel.disabled = false; applyModelNoticeTitle(sel, backend); - }); + }), focusSnap); } else { - modelSelects.forEach(sel => { + withAgentViewportPreserved(agent, () => modelSelects.forEach(sel => { sel.innerHTML = '' + KNOWN_MODELS.map(m => ``).join(''); - }); + }), focusSnap); } } @@ -695,20 +702,26 @@ async function switchModel(agent, model) { if (!model) return; + const focusSnap = agentFocusSnapshot(document.activeElement); const toast = showToast(`Switching ${agent} model → ${model} (restarting session)...`, 'info', true); const res = await fetch(`/api/model/${agent}/${encodeURIComponent(model)}`, { method: 'POST' }); const data = await res.json(); if (!data.ok) { dismissToast(toast, `Model switch failed: ${data.error || 'unknown'}`, 'error'); return; } - dismissToast(toast, `${agent} model → ${model} (session restarted)`, 'success'); - if (window._lastAgents) { - const a = window._lastAgents.find(x => x.name === agent); - if (a) { a.model = model; renderAgents(window._lastAgents); } - } - // Reflect the switch everywhere it is shown (focused detail panel, - // cadence-matrix model column), then confirm against the server. - ocRenderAgentDetail(); - const lastData = window._lastStatus || {}; - renderGovernor(lastData.governor || {}, lastData.cadenceMatrix || [], lastData); + // A change saved for an agent that is not running restarts nothing: show + // the server's "saved; applies when starts" instead (#18905). + dismissToast(toast, data.applied === false && data.message ? `${agent} model → ${model}: ${data.message}` : `${agent} model → ${model} (session restarted)`, 'success'); + // #18906: hold scroll position, focus and list order across the re-render. + withAgentViewportPreserved(agent, () => { + if (window._lastAgents) { + const a = window._lastAgents.find(x => x.name === agent); + if (a) { a.model = model; renderAgents(window._lastAgents); } + } + // Reflect the switch everywhere it is shown (focused detail panel, + // cadence-matrix model column), then confirm against the server. + ocRenderAgentDetail(); + const lastData = window._lastStatus || {}; + renderGovernor(lastData.governor || {}, lastData.cadenceMatrix || [], lastData); + }, focusSnap); fetch('/api/status').then(r => r.json()).then(render).catch(() => {}); } @@ -718,16 +731,19 @@ // confirm against the server. "default" clears the stored effort. async function switchEffort(agent, effort) { if (!effort) return; + const focusSnap = agentFocusSnapshot(document.activeElement); const toast = showToast(`Switching ${agent} reasoning effort → ${effort} (restarting session)...`, 'info', true); const res = await fetch(`/api/effort/${agent}/${encodeURIComponent(effort)}`, { method: 'POST' }); const data = await res.json(); if (!data.ok) { dismissToast(toast, `Effort switch failed: ${data.error || 'unknown'}`, 'error'); return; } dismissToast(toast, `${agent} reasoning effort → ${effort} (session restarted)`, 'success'); - if (window._lastAgents) { - const a = window._lastAgents.find(x => x.name === agent); - if (a) { a.reasoningEffort = effort === 'default' ? '' : effort; renderAgents(window._lastAgents); } - } - ocRenderAgentDetail(); + withAgentViewportPreserved(agent, () => { + if (window._lastAgents) { + const a = window._lastAgents.find(x => x.name === agent); + if (a) { a.reasoningEffort = effort === 'default' ? '' : effort; renderAgents(window._lastAgents); } + } + ocRenderAgentDetail(); + }, focusSnap); fetch('/api/status').then(r => r.json()).then(render).catch(() => {}); } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 49ea6e741c..a4f8d8391e 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -32522,6 +32522,7 @@

All labels

// Preserve custom prompt input values across re-renders const savedInputs = {}; const focusedId = document.activeElement?.id; + const focusSnap = agentFocusSnapshot(document.activeElement); el.querySelectorAll('.kick-prompt').forEach(inp => { if (inp.value) savedInputs[inp.id] = inp.value; }); @@ -32733,6 +32734,9 @@

All labels

const prev = document.getElementById(focusedId); if (prev) { try { prev.focus({ preventScroll: true }); } catch (e) { prev.focus(); } } } + // Controls without an id (the method/model/effort selects) are matched + // by agent + action so a replaced that was just used is replaced (its options changed), which + // drops focus, and the rows above/below resize, which moved the page away + // from the agent. These helpers hold the reader's place across such a + // synchronous re-render: the window scroll is re-pinned to the same card by + // key (delta based, so it composes with the scroll stabilizer), and focus + // returns to the same control by id or by (agent, action). Card ORDER is + // never touched here: a setting change must not re-sort the list. + const AGENT_VIEWPORT_MIN_DELTA_PX = 1; + function agentCssEscape(v) { + return (window.CSS && CSS.escape) ? CSS.escape(String(v)) : String(v).replace(/["\\]/g, '\\$&'); + } + function agentFocusSnapshot(el) { + if (!el || el === document.body || typeof el.getAttribute !== 'function') return null; + if (el.id) return { id: el.id }; + const agent = el.getAttribute('data-agent'); + const action = el.getAttribute('data-change-action') || el.getAttribute('data-action'); + return (agent && action) ? { agent, action, change: !!el.getAttribute('data-change-action') } : null; + } + function agentFocusRestore(snap) { + if (!snap) return; + let el = null; + if (snap.id) { + el = document.getElementById(snap.id); + } else { + const attr = snap.change ? 'data-change-action' : 'data-action'; + el = document.querySelector(`#agents [data-agent="${agentCssEscape(snap.agent)}"][${attr}="${agentCssEscape(snap.action)}"]`); + } + if (!el || el.disabled || document.activeElement === el) return; + try { el.focus({ preventScroll: true }); } catch (e) { el.focus(); } + } + function agentViewportCapture(agentName, fallbackFocus) { + // fallbackFocus: the control focused when the switch began, used only when + // focus has since dropped to (a disabled drops focus to , and the option + // swap resizes it; both are re-pinned so the page does not move (#18906). + withAgentViewportPreserved(agent, () => modelSelects.forEach(sel => { sel.innerHTML = ''; sel.disabled = true; - }); + }), focusSnap); const models = isInference ? await fetchInferenceModels(canonicalInferenceBackendName(backend)) : (await fetchBackendsConfig(), modelsForBackend(backend)); - modelSelects.forEach(sel => { + withAgentViewportPreserved(agent, () => modelSelects.forEach(sel => { sel.innerHTML = '' + models.map(m => ``).join(''); sel.disabled = false; applyModelNoticeTitle(sel, backend); - }); + }), focusSnap); } else { - modelSelects.forEach(sel => { + withAgentViewportPreserved(agent, () => modelSelects.forEach(sel => { sel.innerHTML = '' + KNOWN_MODELS.map(m => ``).join(''); - }); + }), focusSnap); } } @@ -60874,20 +60956,26 @@

Configure LiteLLM

async function switchModel(agent, model) { if (!model) return; + const focusSnap = agentFocusSnapshot(document.activeElement); const toast = showToast(`Switching ${agent} model → ${model} (restarting session)...`, 'info', true); const res = await fetch(`/api/model/${agent}/${encodeURIComponent(model)}`, { method: 'POST' }); const data = await res.json(); if (!data.ok) { dismissToast(toast, `Model switch failed: ${data.error || 'unknown'}`, 'error'); return; } - dismissToast(toast, `${agent} model → ${model} (session restarted)`, 'success'); - if (window._lastAgents) { - const a = window._lastAgents.find(x => x.name === agent); - if (a) { a.model = model; renderAgents(window._lastAgents); } - } - // Reflect the switch everywhere it is shown (focused detail panel, - // cadence-matrix model column), then confirm against the server. - ocRenderAgentDetail(); - const lastData = window._lastStatus || {}; - renderGovernor(lastData.governor || {}, lastData.cadenceMatrix || [], lastData); + // A change saved for an agent that is not running restarts nothing: show + // the server's "saved; applies when starts" instead (#18905). + dismissToast(toast, data.applied === false && data.message ? `${agent} model → ${model}: ${data.message}` : `${agent} model → ${model} (session restarted)`, 'success'); + // #18906: hold scroll position, focus and list order across the re-render. + withAgentViewportPreserved(agent, () => { + if (window._lastAgents) { + const a = window._lastAgents.find(x => x.name === agent); + if (a) { a.model = model; renderAgents(window._lastAgents); } + } + // Reflect the switch everywhere it is shown (focused detail panel, + // cadence-matrix model column), then confirm against the server. + ocRenderAgentDetail(); + const lastData = window._lastStatus || {}; + renderGovernor(lastData.governor || {}, lastData.cadenceMatrix || [], lastData); + }, focusSnap); fetch('/api/status').then(r => r.json()).then(render).catch(() => {}); } @@ -60897,16 +60985,19 @@

Configure LiteLLM

// confirm against the server. "default" clears the stored effort. async function switchEffort(agent, effort) { if (!effort) return; + const focusSnap = agentFocusSnapshot(document.activeElement); const toast = showToast(`Switching ${agent} reasoning effort → ${effort} (restarting session)...`, 'info', true); const res = await fetch(`/api/effort/${agent}/${encodeURIComponent(effort)}`, { method: 'POST' }); const data = await res.json(); if (!data.ok) { dismissToast(toast, `Effort switch failed: ${data.error || 'unknown'}`, 'error'); return; } dismissToast(toast, `${agent} reasoning effort → ${effort} (session restarted)`, 'success'); - if (window._lastAgents) { - const a = window._lastAgents.find(x => x.name === agent); - if (a) { a.reasoningEffort = effort === 'default' ? '' : effort; renderAgents(window._lastAgents); } - } - ocRenderAgentDetail(); + withAgentViewportPreserved(agent, () => { + if (window._lastAgents) { + const a = window._lastAgents.find(x => x.name === agent); + if (a) { a.reasoningEffort = effort === 'default' ? '' : effort; renderAgents(window._lastAgents); } + } + ocRenderAgentDetail(); + }, focusSnap); fetch('/api/status').then(r => r.json()).then(render).catch(() => {}); } From 7e24f06b5652565f66055698e10c92c00b0950d1 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 00:23:17 -0500 Subject: [PATCH 2/4] =?UTF-8?q?=F0=9F=90=9B=20fix:=20import=20sort=20in=20?= =?UTF-8?q?the=20agent=20control=20handlers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- src/pkg/dashboard/api_agent_control.go | 1 + 1 file changed, 1 insertion(+) diff --git a/src/pkg/dashboard/api_agent_control.go b/src/pkg/dashboard/api_agent_control.go index cb0bb57ac4..f3970410e6 100644 --- a/src/pkg/dashboard/api_agent_control.go +++ b/src/pkg/dashboard/api_agent_control.go @@ -3,6 +3,7 @@ package dashboard import ( "fmt" "net/http" + "sort" "strings" "time" From 3bb02514ac34968579343eb3372a49a990261ea4 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 00:33:46 -0500 Subject: [PATCH 3/4] =?UTF-8?q?=F0=9F=90=9B=20fix:=20keep=20a=20second=20b?= =?UTF-8?q?ody=20tag=20out=20of=20the=20generated=20dashboard=20document?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- src/pkg/dashboard/static-src/js/agent-cards.js | 2 +- src/pkg/dashboard/static-src/js/plan-agent-controls.js | 2 +- src/pkg/dashboard/static/index.html | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/pkg/dashboard/static-src/js/agent-cards.js b/src/pkg/dashboard/static-src/js/agent-cards.js index d2e7455371..fcb5176ace 100644 --- a/src/pkg/dashboard/static-src/js/agent-cards.js +++ b/src/pkg/dashboard/static-src/js/agent-cards.js @@ -1198,7 +1198,7 @@ } function agentViewportCapture(agentName, fallbackFocus) { // fallbackFocus: the control focused when the switch began, used only when - // focus has since dropped to (a disabled blurs itself). const snap = { scrollX: window.scrollX, scrollY: window.scrollY, key: '', top: 0, focus: agentFocusSnapshot(document.activeElement) || fallbackFocus || null }; const grid = document.getElementById('agents'); if (!grid) return snap; diff --git a/src/pkg/dashboard/static-src/js/plan-agent-controls.js b/src/pkg/dashboard/static-src/js/plan-agent-controls.js index 6889547b10..aab04b8b3a 100644 --- a/src/pkg/dashboard/static-src/js/plan-agent-controls.js +++ b/src/pkg/dashboard/static-src/js/plan-agent-controls.js @@ -653,7 +653,7 @@ const isInference = isInferenceBackendName(backend); const isCli = CLI_BACKENDS.includes(backend); if (isInference || isCli) { - // Disabling a focused drops focus to the document body, and the option // swap resizes it; both are re-pinned so the page does not move (#18906). withAgentViewportPreserved(agent, () => modelSelects.forEach(sel => { sel.innerHTML = ''; diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index a4f8d8391e..f28435fdbb 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -32784,7 +32784,7 @@

All labels

} function agentViewportCapture(agentName, fallbackFocus) { // fallbackFocus: the control focused when the switch began, used only when - // focus has since dropped to (a disabled blurs itself). const snap = { scrollX: window.scrollX, scrollY: window.scrollY, key: '', top: 0, focus: agentFocusSnapshot(document.activeElement) || fallbackFocus || null }; const grid = document.getElementById('agents'); if (!grid) return snap; @@ -60907,7 +60907,7 @@

Configure LiteLLM

const isInference = isInferenceBackendName(backend); const isCli = CLI_BACKENDS.includes(backend); if (isInference || isCli) { - // Disabling a focused drops focus to the document body, and the option // swap resizes it; both are re-pinned so the page does not move (#18906). withAgentViewportPreserved(agent, () => modelSelects.forEach(sel => { sel.innerHTML = ''; From 81d1afe9e7f25fd72efea39f23fcc12ec84571f6 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 00:35:03 -0500 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=90=9B=20fix:=20test=20a=20registered?= =?UTF-8?q?=20agent's=20model=20switch=20without=20assuming=20it=20is=20la?= =?UTF-8?q?unched?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- ...agent_model_switch_not_running_18905_test.go | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/pkg/dashboard/agent_model_switch_not_running_18905_test.go b/src/pkg/dashboard/agent_model_switch_not_running_18905_test.go index 8b879c8b11..a966f8c870 100644 --- a/src/pkg/dashboard/agent_model_switch_not_running_18905_test.go +++ b/src/pkg/dashboard/agent_model_switch_not_running_18905_test.go @@ -156,22 +156,21 @@ func TestHandleModelSet_UnknownAgentListsValidNames(t *testing.T) { } } -// A live agent keeps the original contract: the switch is applied (no -// applied=false / saved message). -func TestHandleModelSet_RunningAgentStillApplies(t *testing.T) { +// 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["status"] != "model_set" { - t.Fatalf("status field = %v, want model_set", body["status"]) - } - if _, has := body["applied"]; has { - t.Fatalf("a live switch must not carry applied=false: %v", body) + 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("live ModelOverride not set") + t.Fatalf("runtime ModelOverride not set") } }