Files
archie/internal/webui/server.go
T
sam fcf64a610d feat(webui): route dashboard task actions through the Gateway contract
The dashboard composed its own taskactions.Service over whatever handles
happened to be set on webui.Server. In the extracted UI process those are
all nil, and each nil silently removes a guarantee: no Cfg means max_retries
stops being enforced, no Issues means a rejected task's forge issue stays
open and the poller re-enqueues it, no Events means operator actions never
reach the timeline, no TaskStopper means Stop cannot interrupt running work.
The handler now asks whoever owns task execution, through
ApplyOperatorTaskAction, and Issues/TaskStopper leave the dashboard entirely.

That path crosses two hops that both flatten errors, so the sentinels the
handler maps to 404/409/503 travel explicitly: a kind beside the message on
the NATS envelope, a gRPC code on the Gateway contract, each restored on
arrival. Without them a task that simply moved on reports as a broken daemon.

The action tests keep running the real service, now behind a local contract
the way the daemon serves it in production, so retry limits, forge closure,
events, archiving and log removal stay covered where they were.
2026-09-09 23:29:11 +10:00

422 lines
17 KiB
Go

// Package webui is archied's dashboard: a control room over the daemon's
// task board, activity stream and configuration.
//
// The Go side owns serving and the JSON API only; the frontend lives in the
// repo-root ui/ package, which exposes the built assets as an embedded FS.
// Handlers are split by concern -- one file per API area -- so a section can
// be added without growing a single file without end.
package webui
import (
"context"
"encoding/json"
"io/fs"
"log/slog"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/logging"
"github.com/samcharles93/archie-core/internal/memory"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/webhookguard"
"github.com/samcharles93/archie-core/ui"
)
type Server struct {
Store store.TaskStore
Log *slog.Logger
// Cfg backs the setup checklist and configuration views. Optional: the
// dashboard degrades to task data alone when it is nil. Held through a
// Holder so a reload swaps the snapshot atomically across handler
// goroutines that would otherwise race on the raw shared pointer.
//
// In production this is the daemon's OWN Holder (main.go wires
// web.Cfg = d.Cfg), so Set here publishes to the running daemon. A
// config-mutating handler must never call Set directly: it goes
// through the same path as reload -- apply to a copy, validate the
// materialised config, persist, then Set.
Cfg *config.Holder
// Workflows is the executable registry snapshot supplied by composition.
Workflows []workflow.Definition
// WorkRequests admits dashboard requests through the same task-creation
// boundary used by chat; it never invokes a workflow runner directly.
WorkRequests gateway.TaskCreator
// LogFeed is the daemon diagnostic stream. It is separate from Events,
// which contains persisted task lifecycle activity only.
LogFeed *logging.Feed
// TaskLogs holds each task's persisted log output. Archiving a task
// removes its log files here too, via TaskLogs.Remove -- nil (task
// logging not configured) makes that a no-op.
TaskLogs *logging.TaskRegistry
// ConfigProvenance lists the files that produced the running config,
// in precedence order. Held through atomic.Pointer so a reload can
// swap it independently of Cfg. A reader may therefore observe the
// new config alongside the old provenance (or vice versa); this is
// display-only, and the skew is accepted rather than serialised.
ConfigProvenance atomic.Pointer[[]ConfigOrigin]
// LastReload reports the most recent config reload outcome, so the
// dashboard can tell the operator when the running config is stale
// (a reload failed validation and the daemon kept the previous
// config). Optional: when nil, the /api/config response omits the
// reload status.
LastReload func() config.ReloadStatus
// UpdateConfig applies a set of dotted-path config updates through
// the same validate-persist-publish path as reload (wired by the
// composition root). Optional: when nil, PATCH /api/config answers
// 503. The handler never touches the Cfg Holder directly -- see the
// Cfg field doc.
UpdateConfig func(context.Context, map[string]any) error
// ConfigOverrides lists the dotted config keys currently overridden
// by the runtime overlay, so the dashboard can mark those rows and
// offer a reset. Optional: when nil, the /api/config response omits
// the overridden list.
ConfigOverrides func(context.Context) ([]string, error)
// ResetConfig deletes one runtime-overlay row and republishes file +
// remaining overlay. Optional: when nil, POST /api/config/reset
// answers 503. Like UpdateConfig, it never touches the Cfg Holder
// directly.
ResetConfig func(context.Context, string) error
// UpdateRepoField changes one editable field (RepoEditableFields) on
// the repository identified by owner/name, republishing the full
// repository list through the same path as UpdateConfig. Optional:
// when nil, PATCH /api/config/repos/{owner}/{name} answers 503. See
// handleConfigRepoUpdate for why this needs its own seam rather than
// going through UpdateConfig's dotted-key path directly.
UpdateRepoField func(ctx context.Context, owner, name, field string, value any) error
// Channels reports actual adapter lifecycle, independently of configuration
// presence. Nil preserves the configuration-only fallback for tests and
// minimal embedding.
Channels *channels.Manager
// ReloadChannel invokes a channel-specific reload seam. Only adapters that
// explicitly support reload are wired here; nil means reload is unavailable.
ReloadChannel func(context.Context, string) error
// Memory backs the memory view. Optional: the section reports memory as
// unavailable rather than failing when it is nil.
Memory *memory.Manager
// Curators is the daemon's live curator registry (epic archie-core-yp9).
// Backs GET /api/curators: registered names, per-curator health, and
// recent activity (archie-core-1786637489932-6). Optional: nil reports
// an empty curator list rather than failing the dashboard.
Curators *curator.Registry
// Chat exposes the Gateway's wire-safe conversational contract. Optional:
// the dashboard simply omits chat when it is nil.
Chat *ChatService
// Health runs the operator readiness probes served by /health/detailed.
// Optional: nil answers 503 rather than fabricating a report, so a
// deployment that has not wired probes never looks healthy by accident.
Health *health.Registry
// Token gates access. Empty means no check, which is how loopback binds
// stay frictionless -- see IsLoopback.
Token string
// Events publishes operator actions so they reach the task timeline and
// the live activity stream. Optional: nil means the action is recorded
// in the store but invisible to anyone watching.
Events EventPublisher
// Captures persists unbound webhook captures (docs/prds/event-capture-storage.md).
// Optional: nil makes POST /webhooks/capture/{source} answer 503 rather
// than the dashboard failing to start -- capture is a precondition for
// the no-code playbook epic, not a hard dependency of the dashboard.
Captures store.CaptureStore
// CaptureLimiter is the per-remote-address token bucket applied before a
// capture request's body is read (keyed by remote address, not the
// unregistered/attacker-chosen source path segment -- see
// handleCapture). Optional: nil disables rate limiting (every request is
// allowed), which composition never actually does in production -- it
// is nil only in tests that don't exercise this path.
CaptureLimiter *webhookguard.RateLimiter
// CaptureRetention and CaptureMaxEvents are passed straight through to
// InsertCapture's prune-on-write bounds. See config.CaptureConfig.
CaptureRetention time.Duration
CaptureMaxEvents int
// CaptureMaxBodyBytes rejects (413) a capture POST body larger than
// this via http.MaxBytesReader, before redaction or storage sees it.
CaptureMaxBodyBytes int64
// Mappings persists payload field mappings (docs/prds/payload-field-mapping.md).
// Optional: nil makes every /api/mappings route answer 503 rather than
// the dashboard failing to start.
Mappings store.MappingStore
// Bindings persists playbook bindings: matcher + mapping + workflow
// triples that turn a captured webhook into an archie task
// (docs/prds/webhook-intake-security.md). Optional: nil makes every
// /api/bindings route answer 503 rather than the dashboard failing to start.
Bindings store.BindingStore
// BindingDispatcher is the dispatch-time helper surface for bindings:
// the capture endpoint calls ArmedBindingsForSource here to look up
// the HMAC secret for an incoming webhook. Split from BindingStore so
// the CRUD interface stays narrow (six methods, under the
// interfacebloat limit). Optional: nil disables per-source HMAC
// verification at handleCapture and every event records as
// authenticated=false.
BindingDispatcher store.BindingDispatcher
// TelegramUpdateReportPath and TelegramUpdateChatID let a dashboard-
// initiated update use the same post-restart notification route as a
// Telegram-initiated update. The web UI has no durable chat identity, so
// composition supplies an authorized Telegram recipient when one exists.
// When either value is empty, UpdateReportPath remains in use.
TelegramUpdateReportPath string
TelegramUpdateChatID int64
// UpdateReportPath is where the update watchdog leaves the phase-2
// outcome of a dashboard-initiated install for this process to relay on
// its next boot -- the webui counterpart of
// channels/telegram.Gateway.UpdateReportPath. Empty (the default unless
// composition wires it) means dashboard-initiated updates get no
// phase-2 report (archie-core-nln7): the operator only sees the
// synchronous install result, never restart/health/version outcome.
UpdateReportPath string
// RunningVersions reports, per component ID (see releaseupdate.Report.Verify),
// the version that component reports for itself right now. Optional:
// nil leaves every claim in a relayed update report Unverified rather
// than Confirmed.
RunningVersions func() map[string]string
// TrustForwardedHeaders controls whether X-Forwarded-Proto and
// X-Forwarded-Host are trusted when validating Origin on mutating
// requests. When false, Origin scheme must match the direct connection (r.TLS).
// When Cfg is present, Cfg.Get().Web.TrustForwardedHeaders is also checked.
TrustForwardedHeaders bool
mu sync.Mutex
conns map[chan events.Event]struct{}
updateReportMu sync.Mutex
}
func (s *Server) trustForwardedHeaders() bool {
if s == nil {
return false
}
if s.TrustForwardedHeaders {
return true
}
if s.Cfg == nil {
return false
}
return s.Cfg.Get().Web.TrustForwardedHeaders
}
// ConfigOrigin explains one source file contributing to the effective
// configuration. Sources are ordered from lowest to highest precedence.
type ConfigOrigin struct {
Path string `json:"path"`
Role string `json:"role"`
Layer string `json:"layer"`
Feature string `json:"feature,omitempty"`
}
// SetProvenance publishes a fresh provenance list after a config reload.
func (s *Server) SetProvenance(origins []ConfigOrigin) {
s.ConfigProvenance.Store(&origins)
}
// EventPublisher accepts events for the store and the live stream. The bus
// in cmd/archied satisfies it.
type EventPublisher interface {
Publish(events.Event)
}
// Broadcast fans an (ID-stamped) event out to every connected SSE
// client; stalled clients drop events rather than blocking the caller.
func (s *Server) Broadcast(e events.Event) {
s.mu.Lock()
defer s.mu.Unlock()
for c := range s.conns {
select {
case c <- e:
default:
}
}
}
func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/summary", s.handleSummary)
mux.HandleFunc("GET /api/setup", s.handleSetup)
mux.HandleFunc("GET /api/workflows", s.handleWorkflows)
mux.HandleFunc("POST /api/work-requests", s.handleWorkRequest)
mux.HandleFunc("GET /api/skills", s.handleSkills)
mux.HandleFunc("GET /api/curators", s.handleCurators)
mux.HandleFunc("GET /api/captures", s.handleCaptures)
mux.HandleFunc("GET /api/channels", s.handleChannels)
mux.HandleFunc("POST /api/channels/{id}/reload", s.handleChannelReload)
mux.HandleFunc("GET /api/version", s.handleVersion)
mux.HandleFunc("GET /api/memory", s.handleMemory)
}
func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/tasks", s.handleTasks)
mux.HandleFunc("GET /api/task-meta", s.handleTaskMeta)
mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction)
mux.HandleFunc("GET /api/tasks/{id}", s.handleTask)
mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs)
}
func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/mappings", s.handleMappingsList)
mux.HandleFunc("POST /api/mappings", s.handleMappingCreate)
mux.HandleFunc("GET /api/mappings/{id}", s.handleMappingGet)
mux.HandleFunc("PATCH /api/mappings/{id}", s.handleMappingUpdate)
mux.HandleFunc("DELETE /api/mappings/{id}", s.handleMappingDelete)
mux.HandleFunc("POST /api/mappings/preview", s.handleMappingPreview)
mux.HandleFunc("GET /api/bindings", s.handleBindingsList)
mux.HandleFunc("POST /api/bindings", s.handleBindingCreate)
mux.HandleFunc("GET /api/bindings/{id}", s.handleBindingGet)
mux.HandleFunc("PATCH /api/bindings/{id}", s.handleBindingUpdate)
mux.HandleFunc("DELETE /api/bindings/{id}", s.handleBindingDelete)
mux.HandleFunc("POST /api/bindings/{id}/approve", s.handleBindingApprove)
}
func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/config", s.handleConfig)
mux.HandleFunc("PATCH /api/config", s.handleConfigUpdate)
mux.HandleFunc("POST /api/config/reset", s.handleConfigReset)
mux.HandleFunc("PATCH /api/config/repos/{owner}/{name}", s.handleConfigRepoUpdate)
mux.HandleFunc("GET /api/logs", s.handleLogs)
mux.HandleFunc("GET /api/logs/stream", s.handleLogStream)
}
func (s *Server) registerChatRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/chat/sessions", s.handleChatSessions)
mux.HandleFunc("GET /api/chat/sessions/{id}/messages", s.handleChatMessages)
mux.HandleFunc("GET /api/chat/sessions/{id}/turns", s.handleChatTurns)
mux.HandleFunc("POST /api/chat/message", s.handleChatMessage)
mux.HandleFunc("POST /api/chat/stream", s.handleChatStream)
mux.HandleFunc("POST /api/chat/cancel", s.handleChatCancel)
mux.HandleFunc("POST /api/chat/persona", s.handleChatPersona)
mux.HandleFunc("GET /api/chat/update", s.handleChatUpdate)
mux.HandleFunc("POST /api/chat/update/defer", s.handleChatUpdateDefer)
mux.HandleFunc("POST /api/chat/update/install", s.handleChatUpdateInstall)
mux.HandleFunc("GET /api/chat/dangerous", s.handleChatDangerousState)
mux.HandleFunc("POST /api/chat/dangerous/{kind}", s.handleChatDangerousRequest)
mux.HandleFunc("POST /api/chat/dangerous/{id}/decision", s.handleChatDangerousDecision)
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
s.registerCoreRoutes(mux)
s.registerTaskRoutes(mux)
s.registerMappingAndBindingRoutes(mux)
s.registerConfigAndLogRoutes(mux)
s.registerChatRoutes(mux)
mux.HandleFunc("GET /health/detailed", s.handleHealthDetailed)
mux.HandleFunc("GET /events", s.handleSSE)
mux.Handle("GET /", s.assets())
top := http.NewServeMux()
top.HandleFunc("GET /healthz", s.handleHealthz)
top.HandleFunc("GET /health", s.handleHealth)
top.HandleFunc("POST /webhooks/capture/{source}", s.handleCapture)
top.Handle("/", s.requireToken(mux))
return top
}
// handleHealthz is a liveness probe for local, unauthenticated callers --
// most notably the update watchdog script, which polls it after restarting
// archied to decide whether the new version came up or the update needs to
// be rolled back (see scripts/archie-update-watchdog). It deliberately
// bypasses requireToken: the token protects the dashboard from remote
// access, not this process's own local restart tooling.
func (s *Server) handleHealthz(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}
// assets serves the embedded dashboard, falling back to index.html so client
// routes deep-link correctly. Under the no_ui build tag the assets are absent
// and a plain explanation is served instead of a confusing 404.
func (s *Server) assets() http.Handler {
if ui.DistDirFS == nil {
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "dashboard not built into this binary (no_ui)", http.StatusNotFound)
})
}
files := http.FileServerFS(ui.DistDirFS)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := fs.Stat(ui.DistDirFS, trimLeadingSlash(r.URL.Path)); err != nil {
r = r.Clone(r.Context())
r.URL.Path = "/"
}
files.ServeHTTP(w, r)
})
}
func trimLeadingSlash(p string) string {
if len(p) > 0 && p[0] == '/' {
return p[1:]
}
if p == "" {
return "."
}
return p
}
// Run serves until ctx ends.
func (s *Server) Run(ctx context.Context, listen string) error {
s.reportPendingUpdate(ctx)
go s.watchPendingUpdate(ctx)
srv := &http.Server{Addr: listen, Handler: s.Handler(), ReadHeaderTimeout: 5 * time.Second}
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
defer cancel()
_ = srv.Shutdown(shutdownCtx)
}()
s.Log.Info("web ui listening", "addr", "http://"+listen)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
return err
}
return nil
}
// watchPendingUpdate closes the watchdog/startup race: the watchdog writes
// the health result only after this process answers /healthz, so a startup
// read alone can always miss a report for the very boot it describes.
func (s *Server) watchPendingUpdate(ctx context.Context) {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.reportPendingUpdate(ctx)
}
}
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}