Moves the agent model out of env-only config into an admin-editable Settings
section, and enforces is_admin for the first time — it has been in the schema
since migration 0001, plumbed to the client, and checked nowhere.
Backend:
- Migration 0010: instance_settings, a single-row (CHECK id=1) table — pansy's
first instance-level state. Holds agent_model ('' = inherit env) and
agent_enabled (NULL = inherit env), version-guarded like every mutable row.
SECRETS STAY IN ENV: OLLAMA_CLOUD_API_KEY is never stored here.
- requireAdmin at the service seam (authoritative) plus a cheap middleware
early-403. Non-admin gets 403, not 404 — settings existence isn't masked.
- EffectiveAgent resolves DB-over-env (model, enabled); key always from env.
- The live Runner is hot-swapped, not built once. agentHolder holds it behind
an atomic.Pointer; the chat routes are now registered UNCONDITIONALLY and
nil-check agent.get(), so a settings change turns the assistant on/off/onto a
new model with no restart and no race against in-flight readers. /capabilities
reads the pointer, so it reports what's live, not what booted.
- internal/agentmodel is a new leaf package holding the one place that knows how
to turn a spec into a model. Both agent (to run) and service (to validate a
spec before storing it) import it; it can't live in agent, which imports
service. Settings PATCH validates the spec via Parse, so a typo is a 400 now
rather than a broken assistant on the next turn.
Frontend:
- /settings route (admin guard), a Settings page (model field, tri-state
enabled, live status), nav link shown only to admins.
- useCapabilities drops staleTime:Infinity — the assistant can now change under
a running page — and the settings save invalidates it.
Contract change: chat routes always exist, so "assistant off" is a runtime 503
+ capabilities:false, not a missing route. Updated the test that asserted the
old shape.
Verified live against the built binary: disable flips capabilities to false and
logs it; re-enable with a new model swaps it back; a bad spec is rejected 400;
the setting persists across a restart. Swap is race-clean under `go test -race`.
Docs: README (precedence + key-stays-in-env), DESIGN (decision + routes),
CLAUDE (don't re-add conditional route registration; key never in the DB).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01H3zbym8Doka2d7D48maSgZ
141 lines
4.7 KiB
Go
141 lines
4.7 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
|
"gitea.stevedudenhoeffer.com/steve/pansy/internal/service"
|
|
)
|
|
|
|
// Instance settings (#79): admin-only, instance-wide. The authoritative admin
|
|
// check is in the service; requireAdmin here is a cheap early 403 that also
|
|
// keeps the route group readable.
|
|
|
|
// requireAdmin rejects a non-admin actor. It runs after requireAuth, so the
|
|
// actor is already resolved and carries IsAdmin — no extra query. Returns 403
|
|
// (not 404): a logged-in user knows settings exist, they just may not touch them.
|
|
func (h *handlers) requireAdmin() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if !mustActor(c).IsAdmin {
|
|
writeAPIError(c, http.StatusForbidden, "FORBIDDEN", "admin access required")
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// settingsResponse is what GET/PATCH /settings return. It carries the stored
|
|
// settings plus a read-only view of what's resolved and live, so the UI can show
|
|
// "inheriting ollama-cloud/glm-5.2:cloud from the environment" and whether a key
|
|
// is present — without ever exposing the key itself.
|
|
type settingsResponse struct {
|
|
Settings *domain.InstanceSettings `json:"settings"`
|
|
// Effective is the configuration actually in force after layering settings
|
|
// over the environment.
|
|
Effective effectiveView `json:"effective"`
|
|
}
|
|
|
|
type effectiveView struct {
|
|
Model string `json:"model"`
|
|
Enabled bool `json:"enabled"`
|
|
// HasApiKey reports whether OLLAMA_CLOUD_API_KEY is set. The key itself is
|
|
// never serialized — an admin may know one exists, not what it is.
|
|
HasApiKey bool `json:"hasApiKey"`
|
|
// AgentLive is whether the assistant Runner is actually built right now. It
|
|
// can be false even when Enabled+HasApiKey are true (an unresolvable model),
|
|
// which is exactly the case the UI needs to surface.
|
|
AgentLive bool `json:"agentLive"`
|
|
}
|
|
|
|
func (h *handlers) settingsPayload(c *gin.Context, st *domain.InstanceSettings) settingsResponse {
|
|
eff, err := h.svc.EffectiveAgent(c.Request.Context())
|
|
if err != nil {
|
|
// The settings row read succeeded to get here, so this is unexpected; fall
|
|
// back to an empty effective view rather than failing the whole response.
|
|
eff = service.EffectiveAgent{}
|
|
}
|
|
return settingsResponse{
|
|
Settings: st,
|
|
Effective: effectiveView{
|
|
Model: eff.Model,
|
|
Enabled: eff.Enabled,
|
|
HasApiKey: h.cfg.Agent.OllamaCloudAPIKey != "",
|
|
AgentLive: h.agent.get() != nil,
|
|
},
|
|
}
|
|
}
|
|
|
|
func (h *handlers) getSettings(c *gin.Context) {
|
|
st, err := h.svc.GetInstanceSettings(c.Request.Context(), mustActor(c).ID)
|
|
if err != nil {
|
|
writeServiceError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, h.settingsPayload(c, st))
|
|
}
|
|
|
|
// settingsUpdateRequest is the PATCH body. agentModel "" means inherit the env
|
|
// var. agentEnabled is json.RawMessage so an explicit null (inherit) is
|
|
// distinguishable from an absent field and from true/false.
|
|
type settingsUpdateRequest struct {
|
|
AgentModel string `json:"agentModel"`
|
|
AgentEnabled json.RawMessage `json:"agentEnabled"`
|
|
Version int64 `json:"version" binding:"required"`
|
|
}
|
|
|
|
func (h *handlers) updateSettings(c *gin.Context) {
|
|
var req settingsUpdateRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "a current version is required")
|
|
return
|
|
}
|
|
|
|
// agentEnabled: absent or null → inherit (nil); true/false → explicit override.
|
|
enabled, err := parseNullableBool(req.AgentEnabled)
|
|
if err != nil {
|
|
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "agentEnabled must be true, false, or null")
|
|
return
|
|
}
|
|
|
|
st, err := h.svc.UpdateInstanceSettings(c.Request.Context(), mustActor(c).ID, service.InstanceSettingsPatch{
|
|
AgentModel: req.AgentModel,
|
|
AgentEnabled: enabled,
|
|
Version: req.Version,
|
|
})
|
|
if err != nil {
|
|
if errors.Is(err, domain.ErrVersionConflict) {
|
|
writeVersionConflict(c, st)
|
|
return
|
|
}
|
|
writeServiceError(c, err)
|
|
return
|
|
}
|
|
|
|
// Apply the change to the LIVE assistant. Detached from the request context:
|
|
// the write is committed and the rebuild describes it, so a client that hangs
|
|
// up now must not leave the running Runner out of step with the stored
|
|
// settings. Mirrors the same reasoning as the history-write detachment.
|
|
h.agent.rebuild(context.WithoutCancel(c.Request.Context()))
|
|
|
|
c.JSON(http.StatusOK, h.settingsPayload(c, st))
|
|
}
|
|
|
|
// parseNullableBool maps a JSON field that may be absent, null, or a bool to a
|
|
// *bool: nil for absent/null (inherit), else a pointer to the value.
|
|
func parseNullableBool(raw json.RawMessage) (*bool, error) {
|
|
if len(raw) == 0 || string(raw) == "null" {
|
|
return nil, nil
|
|
}
|
|
var b bool
|
|
if err := json.Unmarshal(raw, &b); err != nil {
|
|
return nil, err
|
|
}
|
|
return &b, nil
|
|
}
|