Files
archie/internal/webui/api_logs.go
T
sam 03afd2e8ad refactor(webui): take configuration off the dashboard server
webui.Server declared Cfg *config.Holder with eight read sites, none of
which ran in the UI process: composition leaves it nil there. The field
survived because the daemon kept a webui.Server it never served, using it
to render the published ConfigView snapshot and to hold the readiness
probes (archie-core-ml30).

Split at the producer. LocalConfigView becomes webui.BuildConfigView, a
pure function over a ConfigViewInput the configuration owner assembles;
the DTO and its schema stay where the UI renders them. The daemon builds
that input from its own state (boot.configViewInput) and publishes the
result. Readiness reads the daemon's Holder, channel manager and chat
contract, and the registry it produces is a daemon field, not a field on
a server with no listener. Boot now owns one Holder instead of seeding a
second and replacing it in buildDaemon; operator retry caps read it too,
so they follow a reload rather than a boot-time snapshot.

Server loses Cfg, ConfigProvenance, LastReload, ConfigOverrides and
SetProvenance. The nil-guarded branches they fed went with them, each
checked first against what the UI process actually serves:

- chat.show_tool_calls and the /api/setup checklist were degraded, not
  dead. ConfigView gains a chat section carrying show_tool_calls, the
  operator name and whether a channel is configured, and both surfaces
  read the projection. The end-to-end suite asserts the checklist renders
  from the published snapshot.
- /api/logs takes its path as a process-local option. The history is on
  the daemon's disk, so a dashboard elsewhere cannot read it by learning
  the path; that route still needs a contract.
- handleChannels drops its config-derived fallback, superseded by the
  status manager, which already carries the descriptions and detail.
- trustForwardedHeaders keeps only the process's own setting, which the
  UI process already sets.
- resolveForge keeps the published-projection path it already had.

ConfigView.Editable moves to handleConfig, decided by whether this
process holds UpdateConfig. It describes the writer, not the document, so
the write contract (archie-core-j28m) makes the page editable by wiring
one field. The write handlers and their seams stay for it.

overlay.Store gains Keys: Snapshot nests dotted keys for decoding, so the
overridden-key list was publishing section names ("budgets") where the
dashboard marks and resets rows by stored key ("budgets.max_steps").

Multi-identity forge links move to archie-core-pv6t: forgeConfigForTask
resolved a task's forge from config.Config, had no reachable caller once
the holder was gone, and belongs in the projection rather than the
rendering package.
2026-09-11 23:57:38 +10:00

151 lines
4.1 KiB
Go

package webui
import (
"encoding/json"
"net/http"
"slices"
"strconv"
"strings"
"github.com/samcharles93/archie-core/internal/logging"
)
// handleLogs serves a page of log history.
//
// This handler is transport only: parsing the log format belongs to the
// logging package, which owns it. Live output reaches the dashboard over the
// existing /events stream; this endpoint exists so the view has history from
// before the browser connected, which is the whole reason file logging landed
// first.
func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
path := s.logFile()
if path == "" {
// Not an error: file logging is optional. Say so plainly so the UI can
// explain how to turn it on rather than showing an empty table.
writeJSON(w, map[string]any{
"entries": s.LogFeed.Snapshot(),
"file": "",
"disabled": true,
"components": mergeComponents(nil, s.LogFeed.Snapshot()),
})
return
}
q := r.URL.Query()
limit := logging.DefaultTailLines
if raw := strings.TrimSpace(q.Get("limit")); raw != "" {
parsed, err := strconv.Atoi(raw)
if err != nil {
http.Error(w, "bad limit", http.StatusBadRequest)
return
}
switch {
case parsed <= 0:
limit = logging.DefaultTailLines
case parsed > logging.MaxTailLines:
limit = logging.MaxTailLines
default:
limit = parsed
}
}
result, err := logging.Tail(path, logging.Query{
Levels: splitCSV(q.Get("level")),
Component: strings.TrimSpace(q.Get("component")),
Contains: strings.TrimSpace(q.Get("q")),
Limit: limit,
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
components, err := logging.Components(path)
if err != nil {
// The filter list is a convenience; failing to build it must not cost
// the caller their log entries.
s.Log.Warn("log components unavailable", "err", err)
components = []string{}
}
liveEntries := s.LogFeed.Snapshot()
components = mergeComponents(components, liveEntries)
writeJSON(w, map[string]any{
"entries": append(result.Entries, liveEntries...),
"truncated": result.Truncated,
"file": result.File,
"components": components,
})
}
func (s *Server) handleLogStream(w http.ResponseWriter, r *http.Request) {
if s.LogFeed == nil {
http.Error(w, "live daemon log feed unavailable", http.StatusServiceUnavailable)
return
}
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
entries := s.LogFeed.Subscribe(r.Context())
for {
select {
case <-r.Context().Done():
return
case entry, ok := <-entries:
if !ok {
return
}
data, err := json.Marshal(entry)
if err != nil {
continue
}
_, _ = w.Write([]byte("id: " + strconv.FormatInt(entry.ID, 10) + "\ndata: " + string(data) + "\n\n"))
flusher.Flush()
}
}
}
func mergeComponents(history []string, live []logging.Entry) []string {
seen := make(map[string]struct{}, len(history))
for _, component := range history {
seen[component] = struct{}{}
}
for _, entry := range live {
if component, ok := entry.Fields["component"].(string); ok && component != "" {
seen[component] = struct{}{}
}
}
components := make([]string, 0, len(seen))
for component := range seen {
components = append(components, component)
}
slices.Sort(components)
return components
}
// logFile reports the log path this process can read, or "" when it has
// none. It is deliberately this process's own setting rather than the
// daemon's [log].file: the history lives on the daemon's disk, so a
// dashboard running elsewhere cannot read it by learning its path. Serving
// remote log history needs a contract, which /api/logs does not yet have.
func (s *Server) logFile() string {
return strings.TrimSpace(s.LogFile)
}
func splitCSV(v string) []string {
if strings.TrimSpace(v) == "" {
return nil
}
parts := strings.Split(v, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}