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.
This commit is contained in:
1 parent
f787852be3
commit
19062a702d
31 files changed
+809
-502
No files matched your search
@@ -432,6 +432,12 @@ func seedStore(t *testing.T, dir string) *store.Store {
|
||||
ForgeType: "github",
|
||||
ForgeHost: "https://github.example.com",
|
||||
},
|
||||
Repositories: []webui.RepoView{{Owner: "acme", Name: "widget", Base: "main"}},
|
||||
Chat: webui.ChatView{
|
||||
ShowToolCalls: true,
|
||||
Operator: "Sam",
|
||||
ChannelConfigured: true,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -655,6 +661,35 @@ func TestUIProcessServesTheDashboardAgainstLiveDependencies(t *testing.T) {
|
||||
if got := d.do(d.request(http.MethodPatch, "/api/config", `{}`, true)); got.status != http.StatusServiceUnavailable {
|
||||
t.Errorf("PATCH /api/config = %d, want 503", got.status)
|
||||
}
|
||||
|
||||
// The setup checklist reads the same projection. It reported
|
||||
// nothing here while it needed a live config.Holder this process
|
||||
// never receives (archie-core-ml30).
|
||||
setup := d.get("/api/setup")
|
||||
if setup.status != http.StatusOK {
|
||||
t.Fatalf("GET /api/setup = %d (%s), want 200", setup.status, setup.body)
|
||||
}
|
||||
var checklist struct {
|
||||
Steps []struct {
|
||||
Title string `json:"title"`
|
||||
Done bool `json:"done"`
|
||||
} `json:"steps"`
|
||||
Operator string `json:"operator"`
|
||||
}
|
||||
if err := json.Unmarshal(setup.body, &checklist); err != nil {
|
||||
t.Fatalf("decode setup checklist: %v (%s)", err, setup.body)
|
||||
}
|
||||
if len(checklist.Steps) == 0 {
|
||||
t.Errorf("setup checklist is empty; the published projection carries what it reads (%s)", setup.body)
|
||||
}
|
||||
if checklist.Operator != "Sam" {
|
||||
t.Errorf("setup operator = %q, want the published name", checklist.Operator)
|
||||
}
|
||||
for _, step := range checklist.Steps {
|
||||
if step.Title == "Connect a repository" && !step.Done {
|
||||
t.Errorf("checklist says no repository is connected; the projection publishes one (%s)", setup.body)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Last: taking the State Store away is not reversible for this process.
|
||||
|
||||
@@ -404,6 +404,18 @@ document already anticipates is its natural owner. Until then the UI renders
|
||||
configuration and does not write it, which is what the boundary always said
|
||||
about ownership even when it assumed a wider contract.
|
||||
|
||||
Amended 2026-09-11. This descope is a deferral, not a decision that the
|
||||
dashboard should be read-only. Name it that way in review: the daemon-side
|
||||
policy was built and tested, then deleted by the cutover (`e037b95` removed
|
||||
`internal/app/archied/config_update.go` and its tests), so reviving it is
|
||||
recoverable work, not a rewrite. `archie-core-j28m` carries the remaining
|
||||
question -- which process serves the policy and what transport carries the
|
||||
write -- and blocks the feature bead. The handlers, their error sentinels and
|
||||
the `UpdateConfig`/`ResetConfig`/`UpdateRepoField` seams on `webui.Server` are
|
||||
kept deliberately for it; `ConfigView.Editable` follows whichever process holds
|
||||
`UpdateConfig`, so wiring that one field makes the page editable
|
||||
(`archie-core-ml30`).
|
||||
|
||||
Implementation belongs to `archie-core-8cda.5.4`, the cutover that removes the
|
||||
daemon's own dashboard. Nothing here is built yet.
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ cutover.
|
||||
| `/api/logs`, `/api/logs/stream` | daemon diagnostic feed, host-local | unresolved: `logging.Feed` is in-process on the daemon host and has no contract |
|
||||
| `/api/captures`, `/api/mappings`, `/api/bindings` | State Store contracts, with webhook verification owned by Work Intake/Messaging | RESOLVED (cutover, `archie-core-8cda.5.4`): the UI process composes CaptureStore/MappingStore/BindingStore and mounts the `captureintake.Receiver` from its own State Store client; the daemon's binding-dispatch loop keeps consuming captures from the same store |
|
||||
| `/api/config` (read) | daemon-published `ConfigView` snapshot, read over the State Store contract | RESOLVED (`archie-core-ymut`): see migration-decisions, "Dashboard configuration page" |
|
||||
| `/api/config` (write), `/api/config/reset`, `/api/config/repos/*` | none; descoped for Phase 3 | RESOLVED (`archie-core-ymut`): 503 in the UI process, SPA hides the controls, editing is config.toml plus reload |
|
||||
| `/api/config` (write), `/api/config/reset`, `/api/config/repos/*` | a configuration write contract; the daemon stays the policy owner | DESCOPED for Phase 3 (`archie-core-ymut`), NOT abandoned: 503 in the UI process, SPA hides the controls, editing is config.toml plus reload. Dashboard editing is a tracked feature (`archie-core-1786637498420-327`) and its transport is `archie-core-j28m`; the handlers and their func-field seams on `webui.Server` are kept for it |
|
||||
| `/api/channels`, reload, curators, memory, skills, version/update | owning capability contract or an explicitly removed route | owner and failure semantics remain to define |
|
||||
| `/`, `/healthz`, `/health`, `/health/detailed` | UI HTTP process; readiness consumes per-service health contracts | current HTTP behavior is the compatibility baseline |
|
||||
|
||||
@@ -97,10 +97,9 @@ continue to perform validate-persist-publish for those updates through a
|
||||
narrow application contract. The UI process must never implement that policy
|
||||
by holding or mutating a shared `config.Holder`.
|
||||
|
||||
The current daemon's `config.Holder` sharing is migration residue: `buildDaemon`
|
||||
currently assigns `b.web.Cfg = b.d.Cfg`. It is removed only when the UI has a
|
||||
configuration read/update contract and tests prove that the daemon and UI no
|
||||
longer share a mutable holder.
|
||||
The daemon's `config.Holder` sharing was migration residue: `buildDaemon`
|
||||
assigned `b.web.Cfg = b.d.Cfg`. Removed by `archie-core-ml30` -- the field no
|
||||
longer exists, and boot owns the single Holder the daemon reads through.
|
||||
|
||||
For Phase 3, configuration ownership is split deliberately. The UI process
|
||||
owns its listener, browser-auth, asset, dependency-target, and readiness
|
||||
@@ -109,6 +108,11 @@ the dashboard's `/api/config` read, validation, persistence, overlay, reload,
|
||||
and audit behavior. The UI does not become the writer merely because it
|
||||
renders the configuration page.
|
||||
|
||||
Amended 2026-09-11 by `archie-core-ml30`: the daemon's `config.Holder` sharing
|
||||
is gone. `webui.Server` has no holder field, so the sharing this paragraph
|
||||
describes cannot be reintroduced by wiring; the daemon owns one Holder and
|
||||
publishes a rendered projection.
|
||||
|
||||
Amended 2026-09-09 by `archie-core-ymut`: this section previously assumed one
|
||||
narrow admin contract carrying both the read and the write. It does not. The
|
||||
read crosses as a daemon-published `ConfigView` snapshot over the State Store
|
||||
@@ -212,15 +216,15 @@ Phase 3 is closed. Every gate below is proven by test, not by inspection:
|
||||
| Gate | Evidence |
|
||||
| --- | --- |
|
||||
| Deletion | `cmd/archie-ui/architecture_test.go` re-runs `go list -deps` on every `task check` and fails on any banned package, checked in both directions against its two exceptions |
|
||||
| Composition | `internal/app/archieui/TestComposeUIServerHoldsNoDaemonState` fails on a non-nil `config.Holder`, a concrete `*store.Store`, or a Gateway that is not the gRPC client |
|
||||
| Composition | `internal/app/archieui/TestComposeUIServerHoldsNoDaemonState` fails on a concrete `*store.Store` or a Gateway that is not the gRPC client. The holder clause it also carried is now enforced by the type: `webui.Server` has no `config.Holder` field (`archie-core-ml30`) |
|
||||
| End-to-end | `cmd/archie-ui/main_test.go` builds the binary and drives it over HTTP against a live Gateway and State Store |
|
||||
| No dual authority | The dashboard HTTP listener is `internal/app/archieui/run.go` only; the daemon's two `http.Server`s are its own health endpoint and the forge webhook receiver |
|
||||
|
||||
Acceptance criterion 1 is amended to name the UI process rather than the
|
||||
`internal/webui` package: the UI process receives no holder, while the daemon
|
||||
still holds one *inside its own process* to render the published `ConfigView`
|
||||
snapshot (the residue below, tracked by `archie-core-ml30`). No live struct
|
||||
crosses the service boundary, which is what the criterion protects.
|
||||
Acceptance criterion 1 was amended at the close of Phase 3 to name the UI
|
||||
process rather than the `internal/webui` package, because the daemon still held
|
||||
a holder inside its own process to render the published `ConfigView` snapshot.
|
||||
`archie-core-ml30` removed that residue, so the criterion holds in its original
|
||||
form again: `internal/webui` receives no holder in any process.
|
||||
|
||||
### Deletion gate: SATISFIED (archie-core-8cda.5.6, rev. 2)
|
||||
|
||||
@@ -257,13 +261,21 @@ prefix. `internal/app/archieui`'s `TestComposeUIServerHoldsNoDaemonState`
|
||||
covers the composition clauses, failing on a non-nil `config.Holder`, a
|
||||
concrete `*store.Store`, or a Gateway that is not the gRPC client.
|
||||
|
||||
One piece of residue remains visible: `webui.Server` still declares
|
||||
`Cfg *config.Holder`, because the daemon keeps a `webui.Server` as the renderer
|
||||
that builds the published `ConfigView` snapshot. The UI process never receives
|
||||
a holder, and the composition test fails if it ever does, but removing the
|
||||
field outright means moving that renderer and the readiness probes off
|
||||
`webui.Server` onto the daemon's own configuration owner. That cleanup is
|
||||
`archie-core-ml30` (P2); it is daemon-internal and does not gate Phase 3.
|
||||
One piece of residue remained visible at the close of Phase 3: `webui.Server`
|
||||
still declared `Cfg *config.Holder`, because the daemon kept a `webui.Server`
|
||||
as the renderer that built the published `ConfigView` snapshot. That cleanup
|
||||
landed as `archie-core-ml30`. `webui.Server` no longer has a configuration
|
||||
holder, provenance store, reload-status callback or override-listing callback:
|
||||
the projection is built by `webui.BuildConfigView`, a pure function the
|
||||
configuration owner calls, and the daemon assembles its input from its own
|
||||
state (`boot.configViewInput`). Readiness reads the daemon's own Holder,
|
||||
channel manager and chat contract, and the health registry it produces is a
|
||||
daemon field rather than a field on a server the daemon never serves.
|
||||
|
||||
`ConfigView.Editable` moved with it. It describes the rendering process's own
|
||||
write path, so `handleConfig` sets it from `Server.UpdateConfig` rather than
|
||||
any process baking it into the document. A future configuration write contract
|
||||
(`archie-core-j28m`) makes the page editable by wiring that one field.
|
||||
|
||||
### Real-process evidence (archie-core-8cda.5.6)
|
||||
|
||||
@@ -276,11 +288,14 @@ task action crossing to the Gateway (and refused without the CSRF header),
|
||||
capture intake accepted unauthenticated, the ratified degradations, readiness
|
||||
dropping when the State Store dies while liveness holds, and a clean SIGTERM.
|
||||
|
||||
Two dashboard values still degrade because the published projection does not
|
||||
carry them, both daemon configuration the UI cannot see: `chat.show_tool_calls`
|
||||
(the chat page never expands tool calls) and the `/api/setup` checklist (the
|
||||
panel is omitted rather than rendered from what the snapshot knows). Neither is
|
||||
a boundary violation; both are fields the projection could publish.
|
||||
Two dashboard values degraded here because the published projection did not
|
||||
carry them: `chat.show_tool_calls` (the chat page never expanded tool calls)
|
||||
and the `/api/setup` checklist (the panel was omitted rather than rendered).
|
||||
Both are closed by `archie-core-ml30`: `ConfigView` gained a `chat` section
|
||||
carrying `show_tool_calls`, the operator name, and whether any chat channel is
|
||||
configured, and both surfaces now read the projection rather than a live
|
||||
holder. The end-to-end suite asserts the checklist renders from the published
|
||||
snapshot.
|
||||
|
||||
## Non-goals and open work
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
@@ -34,6 +33,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
domainembedding "github.com/samcharles93/archie-core/internal/domain/embedding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
@@ -124,7 +124,25 @@ type boot struct {
|
||||
bus *events.Bus
|
||||
restartTelegram func() error
|
||||
channelManager *status.Manager
|
||||
web *webui.Server
|
||||
// cfgHolder is the daemon's one configuration Holder. Boot owns it and
|
||||
// the daemon reads through it, so a reload swaps one snapshot and every
|
||||
// reader sees it: there is no second holder to keep in step.
|
||||
cfgHolder *config.Holder
|
||||
// chat is the dashboard-shaped chat surface. It survives the UI
|
||||
// extraction because the readiness gateway probe and the Telegram task
|
||||
// actor both read the same contract.
|
||||
chat *webui.ChatService
|
||||
// healthRegistry backs /health/detailed on the daemon's own listener.
|
||||
healthRegistry *health.Registry
|
||||
// lastReload reports the most recent reload outcome for the published
|
||||
// configuration projection. Nil until reload wiring installs it.
|
||||
lastReload func() config.ReloadStatus
|
||||
// web holds the dashboard adapters the daemon still produces for
|
||||
// surfaces that have no contract to cross on yet (skills, memory,
|
||||
// curators, channels, dashboard work requests). The daemon serves no
|
||||
// HTTP for them -- it never calls web.Handler() -- so this is the
|
||||
// producer half waiting on a route contract, not a live listener.
|
||||
web *webui.Server
|
||||
|
||||
natsClient *nats.Client
|
||||
// natsURL is the endpoint the daemon's own client connected with at
|
||||
@@ -383,18 +401,12 @@ func (b *boot) setupObservability(ctx context.Context) {
|
||||
{ID: "email", Name: "Email", Configured: cfg.Chat.Email.ListenAddr != ""},
|
||||
{ID: "webhook", Name: "Webhook gateway", Configured: cfg.Chat.WebhookAddr != ""},
|
||||
})
|
||||
configProvenance := make([]webui.ConfigOrigin, 0, len(b.doc.Provenance.Origins))
|
||||
for _, origin := range b.doc.Provenance.Origins {
|
||||
configProvenance = append(configProvenance, webui.ConfigOrigin{
|
||||
Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature),
|
||||
})
|
||||
}
|
||||
b.web = &webui.Server{Log: log.With("component", "webui"), Cfg: config.NewHolder(cfg), Channels: b.channelManager, Skills: skillCatalogAdapter{config.NewHolder(cfg)}}
|
||||
b.cfgHolder = config.NewHolder(cfg)
|
||||
b.web = &webui.Server{Log: log.With("component", "webui"), Channels: b.channelManager, Skills: skillCatalogAdapter{b.cfgHolder}}
|
||||
// The watchdog leaves its verdict in a file on this host, so the daemon
|
||||
// reads it and publishes the outcome as an event; the dashboard renders
|
||||
// what it receives, wherever it runs (archie-core-8cda.5.4).
|
||||
b.startUpdateRelay(ctx, updateReportPath(cfg.WorkDir, "webui"))
|
||||
b.web.SetProvenance(configProvenance)
|
||||
sink := bus.Subscribe(256)
|
||||
go persistEvents(ctx, sink, b.stateStore, log)
|
||||
}
|
||||
@@ -533,7 +545,7 @@ func (b *boot) setupLLMAndChat() error {
|
||||
b.addCleanup(cleanup)
|
||||
// Channel routers execute turns locally and need the SQLite TurnLedger.
|
||||
// The remote contract serves web chat; it must not replace their store.
|
||||
b.web.Chat = &webui.ChatService{Contract: contract, Updates: b.updateService}
|
||||
b.chat = &webui.ChatService{Contract: contract, Updates: b.updateService}
|
||||
b.web.WorkRequests = b.chatTasks
|
||||
b.setupReadinessProbes()
|
||||
return nil
|
||||
@@ -557,8 +569,8 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b
|
||||
},
|
||||
ChatTaskActor: chatTaskActorAdapter{
|
||||
contract: func() gateway.ChatContract {
|
||||
if b.web != nil && b.web.Chat != nil {
|
||||
return b.web.Chat.Contract
|
||||
if b.chat != nil {
|
||||
return b.chat.Contract
|
||||
}
|
||||
return nil
|
||||
}(),
|
||||
@@ -1205,9 +1217,9 @@ func (b *boot) registerMinimaxTool(cfg config.Config, log *slog.Logger) {
|
||||
// buildDaemon constructs the daemon and hands the dashboard the handles
|
||||
// it shares with it.
|
||||
func (b *boot) buildDaemon() {
|
||||
cfg, log := b.cfg, b.log
|
||||
log := b.log
|
||||
b.d = &daemon.Daemon{
|
||||
Cfg: config.NewHolder(cfg),
|
||||
Cfg: b.cfgHolder,
|
||||
ConnectedNATS: daemon.NATSEndpoint{URL: b.natsURL, Token: b.natsToken},
|
||||
ConnectedStateStore: daemon.StateStoreEndpoint{URL: strings.TrimSpace(b.cfg.Services.State.Target), Token: b.stateStoreToken},
|
||||
Store: b.stateStore,
|
||||
@@ -1232,12 +1244,6 @@ func (b *boot) buildDaemon() {
|
||||
// off the live registry the daemon already holds, narrowed to the
|
||||
// webui's own view type.
|
||||
b.web.Curators = curatorsUIAdapter{b.curatorRegistry}
|
||||
// web and the daemon must share ONE Holder: a reload swaps d.Cfg and
|
||||
// the dashboard reads the running config from the same snapshot. The
|
||||
// webui Holder seeded in the literal above is replaced here; after
|
||||
// this point /api/config and the daemon can never disagree about the
|
||||
// published config.
|
||||
b.web.Cfg = b.d.Cfg
|
||||
// Consumer mapping/binding surfaces resolve from b.stateStore (the State
|
||||
// Store contract adapter): local by default, remote *staterpc.Client when
|
||||
// [services.state].target is set. See docs/prds/state-store-contract.md §10.
|
||||
@@ -1314,21 +1320,62 @@ func (b *boot) setupForgeWebhook() {
|
||||
})
|
||||
}
|
||||
|
||||
// publishConfig publishes a config snapshot and its provenance to both
|
||||
// the daemon and the dashboard (they share one Holder). Reload and the
|
||||
// PATCH path both go through it, so the two can never diverge.
|
||||
// currentProvenance (an atomic) is the last published provenance chain;
|
||||
// the PATCH path appends the runtime-overlay origin to it.
|
||||
func (b *boot) publishConfig(ctx context.Context, cfg config.Config, provenance configuration.Provenance) {
|
||||
b.d.Cfg.Set(cfg)
|
||||
// publishConfig makes a new configuration the running one and republishes
|
||||
// the dashboard's projection from it. Every path that changes configuration
|
||||
// goes through here, so the running config and the published page can never
|
||||
// diverge. The provenance chain it renders is b.currentProvenance, which the
|
||||
// caller stores before publishing.
|
||||
func (b *boot) publishConfig(ctx context.Context, cfg config.Config) {
|
||||
b.cfgHolder.Set(cfg)
|
||||
b.publishConfigSnapshot(ctx)
|
||||
}
|
||||
|
||||
// configOrigins projects the current provenance chain into the dashboard's
|
||||
// view type.
|
||||
func (b *boot) configOrigins() []webui.ConfigOrigin {
|
||||
provenance := b.currentProvenance.Load()
|
||||
if provenance == nil {
|
||||
return nil
|
||||
}
|
||||
origins := make([]webui.ConfigOrigin, 0, len(provenance.Origins))
|
||||
for _, origin := range provenance.Origins {
|
||||
origins = append(origins, webui.ConfigOrigin{
|
||||
Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature),
|
||||
})
|
||||
}
|
||||
b.web.SetProvenance(origins)
|
||||
b.publishConfigSnapshot(ctx)
|
||||
return origins
|
||||
}
|
||||
|
||||
// configOverrides lists the dotted keys the runtime overlay currently sets,
|
||||
// so the dashboard can mark those rows: their file value is shadowed until
|
||||
// reset. A disabled overlay store reports no overrides.
|
||||
func (b *boot) configOverrides(ctx context.Context) []string {
|
||||
if b.overlayStore == nil {
|
||||
return nil
|
||||
}
|
||||
keys, err := b.overlayStore.Keys(ctx)
|
||||
if err != nil {
|
||||
// A failed read omits the list rather than failing the whole
|
||||
// view; the reload status carries the overlay degrade reason.
|
||||
return nil
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// configViewInput assembles the dashboard's configuration projection from
|
||||
// the daemon's own configuration state. The daemon is the configuration
|
||||
// owner, so it is the process that renders this view (archie-core-ml30).
|
||||
func (b *boot) configViewInput(ctx context.Context) webui.ConfigViewInput {
|
||||
in := webui.ConfigViewInput{
|
||||
Config: b.cfgHolder.Get(),
|
||||
Provenance: b.configOrigins(),
|
||||
Overridden: b.configOverrides(ctx),
|
||||
}
|
||||
if b.lastReload != nil {
|
||||
status := b.lastReload()
|
||||
in.Reload = &status
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
// publishConfigSnapshot sends the dashboard's projection to the State Store,
|
||||
@@ -1341,7 +1388,7 @@ func (b *boot) publishConfig(ctx context.Context, cfg config.Config, provenance
|
||||
// the new configuration, both of which have already taken effect.
|
||||
func (b *boot) publishConfigSnapshot(ctx context.Context) {
|
||||
snapshots, ok := b.stateStore.(storecontract.ConfigSnapshotStore)
|
||||
if !ok || b.web == nil {
|
||||
if !ok || b.cfgHolder == nil {
|
||||
return
|
||||
}
|
||||
// Detached from the caller: a dashboard edit's request context is
|
||||
@@ -1350,14 +1397,7 @@ func (b *boot) publishConfigSnapshot(ctx context.Context) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
view, found, err := b.web.LocalConfigView(ctx)
|
||||
if err != nil || !found {
|
||||
if err != nil {
|
||||
b.log.Warn("config snapshot not published", "err", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
document, err := json.Marshal(view)
|
||||
document, err := json.Marshal(webui.BuildConfigView(b.configViewInput(ctx)))
|
||||
if err != nil {
|
||||
b.log.Warn("config snapshot not published", "err", err)
|
||||
return
|
||||
@@ -1388,7 +1428,7 @@ func (b *boot) wireConfigPublishing(ctx context.Context, cfgPath, overlayPath st
|
||||
applyModelCatalog(&doc.Config, b.catalog)
|
||||
old := b.d.Cfg.Get()
|
||||
b.currentProvenance.Store(&doc.Provenance)
|
||||
b.publishConfig(ctx, doc.Config, doc.Provenance)
|
||||
b.publishConfig(ctx, doc.Config)
|
||||
if fields := changedNonReloadableFields(old, doc.Config); len(fields) > 0 {
|
||||
log.Warn("config reloaded; some changes require a restart",
|
||||
"fields", fields, "paths", doc.Provenance.Paths())
|
||||
@@ -1399,10 +1439,10 @@ func (b *boot) wireConfigPublishing(ctx context.Context, cfgPath, overlayPath st
|
||||
if b.overlayStore != nil {
|
||||
reloadController.WithOverlay(func() (map[string]any, error) { return b.overlayStore.Snapshot(ctx) })
|
||||
}
|
||||
// LastReload merges the reload controller's outcome with the boot-time
|
||||
// lastReload merges the reload controller's outcome with the boot-time
|
||||
// overlay degrade, so /api/config carries both the last reload result
|
||||
// and whether the runtime overlay is in effect at all.
|
||||
b.web.LastReload = func() config.ReloadStatus {
|
||||
b.lastReload = func() config.ReloadStatus {
|
||||
st := reloadController.Status()
|
||||
if p := b.bootOverlayErr.Load(); p != nil {
|
||||
st.OverlayUnavailable = *p
|
||||
@@ -1422,33 +1462,6 @@ func (b *boot) wireConfigPublishing(ctx context.Context, cfgPath, overlayPath st
|
||||
b.chatController.WithRuntime(b.d)
|
||||
}
|
||||
|
||||
// installConfigHandlers installs the configuration renderer's override
|
||||
// listing. The write handlers behind PATCH /api/config, POST
|
||||
// /api/config/reset and the per-repository field update are gone with the
|
||||
// cutover (archie-core-8cda.5.4, archie-core-ymut): editing is config.toml
|
||||
// plus reload, the UI process answers 503 for the write routes, and the
|
||||
// renderer only needs to know which keys an overlay currently overrides.
|
||||
func (b *boot) installConfigHandlers() {
|
||||
// ConfigOverrides lists the dotted keys currently overridden by the
|
||||
// runtime overlay, so the dashboard can mark those rows and offer a
|
||||
// reset. A disabled store reports no overrides.
|
||||
b.web.ConfigOverrides = func(ctx context.Context) ([]string, error) {
|
||||
if b.overlayStore == nil {
|
||||
return nil, nil
|
||||
}
|
||||
rows, err := b.overlayStore.Snapshot(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keys := make([]string, 0, len(rows))
|
||||
for k := range rows {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys, nil
|
||||
}
|
||||
}
|
||||
|
||||
// shutdownCapabilityHost returns a cleanup that stops the capability
|
||||
// host; same Background reasoning as shutdownCuratorRuntime. Defined
|
||||
// before startServices so the Stop-before-Start ordering stays visible
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestRemoteChatCompositionPreservesChannelTurnLedger(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
b := &boot{cfg: cfg, log: slog.Default(), web: &webui.Server{Cfg: config.NewHolder(cfg)}, stateStore: st}
|
||||
b := &boot{cfg: cfg, log: slog.Default(), web: &webui.Server{}, cfgHolder: config.NewHolder(cfg), stateStore: st}
|
||||
t.Cleanup(b.cleanup)
|
||||
if err := b.openStores(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
// TestPublishConfigSnapshotRendersTheDaemonsConfiguration: the daemon is the
|
||||
// configuration owner, so it is the process that renders the dashboard's
|
||||
// projection and publishes it for the UI process to read. It builds that view
|
||||
// from its own state rather than from a webui.Server it never serves
|
||||
// (archie-core-ml30).
|
||||
func TestPublishConfigSnapshotRendersTheDaemonsConfiguration(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
cfg := config.Config{
|
||||
BotUser: "archie-bot",
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "widget", Base: "main"}},
|
||||
Chat: config.ChatConfig{
|
||||
Operator: "Sam",
|
||||
ShowToolCalls: true,
|
||||
WebhookAddr: "127.0.0.1:9099",
|
||||
},
|
||||
}
|
||||
b := &boot{
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
stateStore: st,
|
||||
cfgHolder: config.NewHolder(cfg),
|
||||
lastReload: func() config.ReloadStatus {
|
||||
return config.ReloadStatus{LastError: "poll_interval must be positive"}
|
||||
},
|
||||
}
|
||||
b.currentProvenance.Store(&configuration.Provenance{Origins: []configuration.Origin{
|
||||
{Path: "/etc/archie/config.toml", Role: configuration.RoleMain, Layer: configuration.LayerBase},
|
||||
}})
|
||||
|
||||
b.publishConfigSnapshot(t.Context())
|
||||
|
||||
snapshot, found, err := st.ConfigSnapshot(context.Background())
|
||||
if err != nil || !found {
|
||||
t.Fatalf("ConfigSnapshot = (found %v, %v), want the published document", found, err)
|
||||
}
|
||||
if snapshot.Schema != webui.ConfigViewSchema {
|
||||
t.Fatalf("Schema = %q, want %q", snapshot.Schema, webui.ConfigViewSchema)
|
||||
}
|
||||
|
||||
var view webui.ConfigView
|
||||
if err := json.Unmarshal(snapshot.Document, &view); err != nil {
|
||||
t.Fatalf("decode published document: %v", err)
|
||||
}
|
||||
if view.Identity.BotUser != "archie-bot" || len(view.Repositories) != 1 {
|
||||
t.Errorf("view = %+v, want the daemon's identity and repositories", view)
|
||||
}
|
||||
// The chat page and the setup checklist are rendered by a process that
|
||||
// holds no configuration, so the projection has to carry what they read.
|
||||
if !view.Chat.ShowToolCalls {
|
||||
t.Error("Chat.ShowToolCalls = false; the chat page would never expand tool calls")
|
||||
}
|
||||
if view.Chat.Operator != "Sam" {
|
||||
t.Errorf("Chat.Operator = %q, want Sam", view.Chat.Operator)
|
||||
}
|
||||
if !view.Chat.ChannelConfigured {
|
||||
t.Error("Chat.ChannelConfigured = false despite a configured webhook address")
|
||||
}
|
||||
if len(view.Provenance) != 1 || view.Provenance[0].Path != "/etc/archie/config.toml" {
|
||||
t.Errorf("Provenance = %+v, want the daemon's file chain", view.Provenance)
|
||||
}
|
||||
if view.Reload == nil || view.Reload.LastError != "poll_interval must be positive" {
|
||||
t.Errorf("Reload = %+v, want the last reload outcome", view.Reload)
|
||||
}
|
||||
// Editable describes the rendering process's write path, never the
|
||||
// published document.
|
||||
if view.Editable {
|
||||
t.Error("the published document claims to be editable")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishedSnapshotCarriesOverlayOverrides: the dashboard marks rows the
|
||||
// runtime overlay shadows, so the projection has to name those keys. The
|
||||
// daemon reads them from the overlay store it owns.
|
||||
func TestPublishedSnapshotCarriesOverlayOverrides(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
overlayStore, err := overlay.Open(t.Context(), filepath.Join(t.TempDir(), "config.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = overlayStore.Close() })
|
||||
if err := overlayStore.Set(t.Context(), "label", `"archie"`, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := overlayStore.Set(t.Context(), "budgets.max_steps", "40", "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
b := &boot{
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
stateStore: st,
|
||||
cfgHolder: config.NewHolder(config.Config{}),
|
||||
overlayStore: overlayStore,
|
||||
}
|
||||
b.publishConfigSnapshot(t.Context())
|
||||
|
||||
snapshot, found, err := st.ConfigSnapshot(context.Background())
|
||||
if err != nil || !found {
|
||||
t.Fatalf("ConfigSnapshot = (found %v, %v), want the published document", found, err)
|
||||
}
|
||||
var view webui.ConfigView
|
||||
if err := json.Unmarshal(snapshot.Document, &view); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"budgets.max_steps", "label"}
|
||||
if len(view.Overridden) != len(want) {
|
||||
t.Fatalf("Overridden = %+v, want %+v", view.Overridden, want)
|
||||
}
|
||||
for i, key := range want {
|
||||
if view.Overridden[i] != key {
|
||||
t.Errorf("Overridden[%d] = %q, want %q (sorted)", i, view.Overridden[i], key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishConfigSnapshotWithoutConfiguration: called before the daemon has
|
||||
// a configuration Holder, publishing is a no-op rather than a panic.
|
||||
func TestPublishConfigSnapshotWithoutConfiguration(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
b := &boot{log: slog.New(slog.DiscardHandler), stateStore: st}
|
||||
b.publishConfigSnapshot(t.Context())
|
||||
|
||||
if _, found, err := st.ConfigSnapshot(context.Background()); found || err != nil {
|
||||
t.Fatalf("ConfigSnapshot = (found %v, %v), want nothing published", found, err)
|
||||
}
|
||||
}
|
||||
@@ -83,12 +83,7 @@ func (h *healthSurface) handleDetailed(w http.ResponseWriter, r *http.Request) {
|
||||
// updates verified, and the watchdog would roll back every release it
|
||||
// installs.
|
||||
func (b *boot) startHealth(ctx context.Context) error {
|
||||
b.health = &healthSurface{registry: func() *health.Registry {
|
||||
if b.web == nil {
|
||||
return nil
|
||||
}
|
||||
return b.web.Health
|
||||
}}
|
||||
b.health = &healthSurface{registry: func() *health.Registry { return b.healthRegistry }}
|
||||
addr := b.cfg.Health.Listen
|
||||
if err := b.serveHealth(ctx, addr, b.health.handler(), "daemon health"); err != nil {
|
||||
b.log.Error("health listener failed", "addr", addr, "err", err)
|
||||
|
||||
@@ -453,7 +453,6 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del
|
||||
// renderer needs stay wired.
|
||||
func (b *boot) wireConfigSurfaces(ctx context.Context, cfgPath, overlayPath string) {
|
||||
b.wireConfigPublishing(ctx, cfgPath, overlayPath)
|
||||
b.installConfigHandlers()
|
||||
// Publish once at boot. Every later change goes through publishConfig,
|
||||
// which republishes; without this the UI process would render nothing
|
||||
// until the first reload or dashboard edit.
|
||||
|
||||
@@ -20,23 +20,27 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
// setupReadinessProbes assembles the readiness probes and publishes the
|
||||
// registry to the dashboard. It must be called after setupObservability (so
|
||||
// b.web.Cfg and b.web.Channels are set) and after the chat wiring (so
|
||||
// b.web.Chat exposes the model manager and session store).
|
||||
// setupReadinessProbes assembles the readiness probes over the daemon's own
|
||||
// subsystems. It must be called after setupObservability (so the config
|
||||
// Holder and channel manager exist) and after the chat wiring (so b.chat
|
||||
// exposes the contract).
|
||||
//
|
||||
// The probes read the daemon's state directly rather than through a
|
||||
// webui.Server: the daemon serves /health/detailed on its own listener and
|
||||
// has served no dashboard since the UI process cutover (archie-core-ml30).
|
||||
func (b *boot) setupReadinessProbes() {
|
||||
cfg := b.cfg
|
||||
probes := []health.Probe{
|
||||
readiness.NewStoreProbe(b.stateStore),
|
||||
readiness.NewConfigProbe(func() config.Config { return b.web.Cfg.Get() }, configuration.Validate),
|
||||
readiness.NewConfigProbe(b.cfgHolder.Get, configuration.Validate),
|
||||
readiness.NewDiskProbe(diskProbePath(cfg)),
|
||||
readiness.NewModelProbe(b.chatModels.ActiveModel, b.chatModels.Models, modelReachProbe(cfg, b.chatModels.ActiveModel)),
|
||||
readiness.NewGatewayProbe(
|
||||
func() []readiness.ChannelState { return channelStates(b.web.Channels) },
|
||||
func(ctx context.Context) int { return sessionCount(ctx, b.web.Chat) },
|
||||
func() []readiness.ChannelState { return channelStates(b.channelManager) },
|
||||
func(ctx context.Context) int { return sessionCount(ctx, b.chat) },
|
||||
),
|
||||
}
|
||||
b.web.Health = health.NewRegistry(probes...)
|
||||
b.healthRegistry = health.NewRegistry(probes...)
|
||||
}
|
||||
|
||||
// channelStates projects a channel lifecycle snapshot into the readiness
|
||||
|
||||
@@ -92,16 +92,14 @@ func TestSetupReadinessProbes_WiresEverySubsystem(t *testing.T) {
|
||||
}
|
||||
|
||||
b := &boot{
|
||||
st: st,
|
||||
web: &webui.Server{
|
||||
Cfg: config.NewHolder(cfg),
|
||||
Channels: status.NewManager([]status.Descriptor{{ID: "telegram", Name: "Telegram", Configured: true}}),
|
||||
Chat: &webui.ChatService{
|
||||
Contract: &gateway.LocalChatAdapter{
|
||||
Router: &gateway.Router{},
|
||||
Sessions: gateway.NewSessionStoreMemory(),
|
||||
Models: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil),
|
||||
},
|
||||
st: st,
|
||||
cfgHolder: config.NewHolder(cfg),
|
||||
channelManager: status.NewManager([]status.Descriptor{{ID: "telegram", Name: "Telegram", Configured: true}}),
|
||||
chat: &webui.ChatService{
|
||||
Contract: &gateway.LocalChatAdapter{
|
||||
Router: &gateway.Router{},
|
||||
Sessions: gateway.NewSessionStoreMemory(),
|
||||
Models: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil),
|
||||
},
|
||||
},
|
||||
chatModels: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil),
|
||||
@@ -109,11 +107,11 @@ func TestSetupReadinessProbes_WiresEverySubsystem(t *testing.T) {
|
||||
}
|
||||
|
||||
b.setupReadinessProbes()
|
||||
if b.web.Health == nil {
|
||||
t.Fatal("b.web.Health is nil after setupReadinessProbes")
|
||||
if b.healthRegistry == nil {
|
||||
t.Fatal("b.healthRegistry is nil after setupReadinessProbes")
|
||||
}
|
||||
|
||||
report := b.web.Health.Run(context.Background())
|
||||
report := b.healthRegistry.Run(context.Background())
|
||||
if len(report.Components) != 5 {
|
||||
t.Fatalf("components = %d, want 5: %+v", len(report.Components), report.Components)
|
||||
}
|
||||
|
||||
@@ -94,8 +94,8 @@ func TestSetupObservabilityKeepsStoreSurfacesOutOfTheDaemonWebui(t *testing.T) {
|
||||
t.Cleanup(b.cleanup)
|
||||
b.setupObservability(t.Context())
|
||||
|
||||
if b.web.Cfg == nil {
|
||||
t.Fatal("webui Cfg is nil; the daemon renders the configuration snapshot it publishes (archie-core-ymut)")
|
||||
if b.cfgHolder == nil {
|
||||
t.Fatal("cfgHolder is nil; the daemon renders the configuration snapshot it publishes (archie-core-ymut)")
|
||||
}
|
||||
for name, surface := range map[string]any{
|
||||
"Store": b.web.Store,
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
|
||||
@@ -17,7 +16,7 @@ import (
|
||||
func (b *boot) taskActions() taskactions.Service {
|
||||
return taskactionstore.NewService(
|
||||
taskactionstore.Store{TaskStore: b.stateStore},
|
||||
taskactionstore.MaxRetries(config.NewHolder(b.cfg)),
|
||||
taskactionstore.MaxRetries(b.cfgHolder),
|
||||
b.cancelTask,
|
||||
b.closeIssue,
|
||||
b.removeTaskLogs,
|
||||
|
||||
@@ -105,10 +105,14 @@ func runDashboardAction(t *testing.T, ctx context.Context, st store.TaskStore, a
|
||||
// in production carries them back to this daemon's own service. Wiring
|
||||
// that service behind a local adapter keeps both surfaces in this test
|
||||
// driving the one implementation, which is the whole point of it.
|
||||
actor := testTaskActor{&boot{st: st, stateStore: st, cfg: config.Config{MaxRetries: 3}, log: slog.New(slog.DiscardHandler)}}
|
||||
actor := testTaskActor{&boot{
|
||||
st: st, stateStore: st,
|
||||
cfg: config.Config{MaxRetries: 3},
|
||||
cfgHolder: config.NewHolder(config.Config{MaxRetries: 3}),
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
}}
|
||||
srv := &webui.Server{
|
||||
Store: st,
|
||||
Cfg: config.NewHolder(config.Config{MaxRetries: 3}),
|
||||
Chat: &webui.ChatService{Contract: &gateway.LocalChatAdapter{TaskActor: actor}},
|
||||
}
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost,
|
||||
|
||||
@@ -32,10 +32,13 @@ func isNil(v any) bool {
|
||||
|
||||
// TestComposeUIServerHoldsNoDaemonState is the acceptance criterion the parent
|
||||
// bead names first: the UI process's dashboard "no longer receives the
|
||||
// daemon's live config.Holder". It pins the whole composition: the two
|
||||
// contract-backed fields hold remote clients, and every daemon-local runtime
|
||||
// handle stays nil so the process cannot hold in-process daemon state by
|
||||
// accident (docs/prds/ui-service-boundary.md, "Boundary and ownership").
|
||||
// daemon's live config.Holder". webui.Server no longer has a holder field to
|
||||
// receive (archie-core-ml30), so that clause is now enforced by the type
|
||||
// rather than asserted here. What remains to pin is the rest of the
|
||||
// composition: the two contract-backed fields hold remote clients, and every
|
||||
// daemon-local runtime handle stays nil so the process cannot hold in-process
|
||||
// daemon state by accident (docs/prds/ui-service-boundary.md, "Boundary and
|
||||
// ownership").
|
||||
func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
|
||||
stateConn, err := grpc.NewClient("passthrough:///127.0.0.1:1", grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
@@ -55,9 +58,6 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
|
||||
Chat: gatewayrpc.NewClient(gatewayConn),
|
||||
})
|
||||
|
||||
if srv.Cfg != nil {
|
||||
t.Fatal("UI server holds a config.Holder; the UI process must not share the daemon's live configuration (docs/prds/ui-service-boundary.md:95-96)")
|
||||
}
|
||||
if _, ok := srv.Store.(*staterpc.Client); !ok {
|
||||
t.Fatalf("Store = %T, want *staterpc.Client", srv.Store)
|
||||
}
|
||||
@@ -80,9 +80,7 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
|
||||
unwired := map[string]any{
|
||||
"UpdateConfig": srv.UpdateConfig,
|
||||
"ResetConfig": srv.ResetConfig,
|
||||
"ConfigOverrides": srv.ConfigOverrides,
|
||||
"UpdateRepoField": srv.UpdateRepoField,
|
||||
"LastReload": srv.LastReload,
|
||||
"ReloadChannel": srv.ReloadChannel,
|
||||
"RunningVersions": srv.RunningVersions,
|
||||
"Events": srv.Events,
|
||||
|
||||
@@ -125,6 +125,29 @@ func (s *Store) Delete(ctx context.Context, key string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Keys lists the dotted keys the overlay sets, in sorted order. Snapshot
|
||||
// nests them into a config-shaped map for decoding, which loses the paths --
|
||||
// "budgets.max_steps" becomes out["budgets"]["max_steps"] and ranging over
|
||||
// that map yields "budgets". The dashboard marks overridden rows and offers a
|
||||
// per-row reset by dotted key, so it needs the keys as stored.
|
||||
func (s *Store) Keys(ctx context.Context) ([]string, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT key FROM config_overlay ORDER BY key`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var keys []string
|
||||
for rows.Next() {
|
||||
var key string
|
||||
if err := rows.Scan(&key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys, rows.Err()
|
||||
}
|
||||
|
||||
// Snapshot returns every stored override as a nested map of typed
|
||||
// values ready to decode into config.Config. Dotted keys are nested:
|
||||
// "budgets.max_steps" becomes map["budgets"]["max_steps"]. Values are
|
||||
|
||||
@@ -139,3 +139,47 @@ func TestOpenIdempotentAndVersioned(t *testing.T) {
|
||||
}
|
||||
_ = s2.Close()
|
||||
}
|
||||
|
||||
// TestKeysReportsDottedPaths: Snapshot nests keys for decoding, so it cannot
|
||||
// answer "which keys are overridden" -- ranging over its result yields the
|
||||
// top-level section ("budgets"), not the stored key ("budgets.max_steps").
|
||||
// The dashboard marks rows and resets them by stored key, so Keys reports
|
||||
// those.
|
||||
func TestKeysReportsDottedPaths(t *testing.T) {
|
||||
store, ctx := openTest(t)
|
||||
for key, value := range map[string]string{
|
||||
"budgets.max_steps": "40",
|
||||
"budgets.wall_clock": `"30m"`,
|
||||
"label": `"archie"`,
|
||||
} {
|
||||
if err := store.Set(ctx, key, value, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
keys, err := store.Keys(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"budgets.max_steps", "budgets.wall_clock", "label"}
|
||||
if len(keys) != len(want) {
|
||||
t.Fatalf("Keys = %v, want %v", keys, want)
|
||||
}
|
||||
for i, key := range want {
|
||||
if keys[i] != key {
|
||||
t.Errorf("Keys[%d] = %q, want %q (sorted, dotted)", i, keys[i], key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestKeysOnAnEmptyOverlay: nothing overridden is an empty list, not an error.
|
||||
func TestKeysOnAnEmptyOverlay(t *testing.T) {
|
||||
store, ctx := openTest(t)
|
||||
keys, err := store.Keys(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(keys) != 0 {
|
||||
t.Fatalf("Keys = %v, want none", keys)
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ func (s *Server) handleCapabilities(w http.ResponseWriter, _ *http.Request) {
|
||||
"skills": s.Skills != nil,
|
||||
"memory": s.Memory != nil,
|
||||
"curators": s.Curators != nil,
|
||||
"channels": s.Channels != nil || s.Cfg != nil,
|
||||
"channels": s.Channels != nil,
|
||||
"captures": s.Captures != nil,
|
||||
"mappings": s.Mappings != nil,
|
||||
"bindings": s.Bindings != nil,
|
||||
|
||||
@@ -381,14 +381,19 @@ func (s chatStreamSink) Media(event messaging.MediaEvent) {
|
||||
}
|
||||
|
||||
// chatShowToolCalls reports config.ChatConfig.ShowToolCalls, the one setting
|
||||
// shared by every chat channel. Off (the default) when Cfg is nil, matching
|
||||
// the field's own off-by-default doc comment: a dashboard embedded without
|
||||
// live config must not narrate tool activity nobody opted into.
|
||||
func (s *Server) chatShowToolCalls() bool {
|
||||
if s.Cfg == nil {
|
||||
// shared by every chat channel. It reads the configuration projection this
|
||||
// process renders, so a dashboard that displays a published snapshot honours
|
||||
// the operator's setting instead of assuming it off.
|
||||
//
|
||||
// Off (the default) when no projection is available, matching the field's own
|
||||
// off-by-default doc comment: a dashboard without config must not narrate tool
|
||||
// activity nobody opted into.
|
||||
func (s *Server) chatShowToolCalls(ctx context.Context) bool {
|
||||
view, found, err := s.configSource()(ctx)
|
||||
if err != nil || !found {
|
||||
return false
|
||||
}
|
||||
return s.Cfg.Get().Chat.ShowToolCalls
|
||||
return view.Chat.ShowToolCalls
|
||||
}
|
||||
|
||||
func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -419,7 +424,7 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
|
||||
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, "")
|
||||
return
|
||||
}
|
||||
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls()}
|
||||
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls(r.Context())}
|
||||
for event := range events {
|
||||
sink.write = func(frame chatStreamEvent) { writeChatEvent(frame, event.SessionID) }
|
||||
switch event.Kind {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
@@ -14,7 +15,6 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
@@ -636,7 +636,9 @@ func TestChatStreamReportsToolCalls(t *testing.T) {
|
||||
// Enabled explicitly: this test exercises the tool-narration
|
||||
// path itself, which is off by default (see
|
||||
// TestChatStreamHidesToolCallsWhenShowToolCallsIsOff).
|
||||
server.Cfg = config.NewHolder(config.Config{Chat: config.ChatConfig{ShowToolCalls: true}})
|
||||
server.ConfigSource = func(context.Context) (ConfigView, bool, error) {
|
||||
return ConfigView{Chat: ChatView{ShowToolCalls: true}}, true, nil
|
||||
}
|
||||
if tc.queued {
|
||||
testLocalChat(server.Chat).Turns = gateway.NewTurns(slog.Default())
|
||||
}
|
||||
@@ -759,19 +761,35 @@ func TestChatStreamHidesToolCallsWhenShowToolCallsIsOff(t *testing.T) {
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg *config.Holder
|
||||
name string
|
||||
source ConfigViewSource
|
||||
}{
|
||||
{name: "no Cfg wired at all", cfg: nil},
|
||||
{name: "Cfg present but show_tool_calls unset", cfg: config.NewHolder(config.Config{})},
|
||||
{name: "show_tool_calls explicitly false", cfg: config.NewHolder(config.Config{Chat: config.ChatConfig{ShowToolCalls: false}})},
|
||||
{name: "no configuration source wired at all"},
|
||||
{
|
||||
name: "projection available but show_tool_calls unset",
|
||||
source: func(context.Context) (ConfigView, bool, error) {
|
||||
return ConfigView{}, true, nil
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "show_tool_calls explicitly false",
|
||||
source: func(context.Context) (ConfigView, bool, error) {
|
||||
return ConfigView{Chat: ChatView{ShowToolCalls: false}}, true, nil
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "projection unavailable",
|
||||
source: func(context.Context) (ConfigView, bool, error) {
|
||||
return ConfigView{}, false, errors.New("state store unreachable")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server, sessions := chatTestServer(t)
|
||||
testLocalChat(server.Chat).Router.LLMStream = stream
|
||||
server.Cfg = tc.cfg
|
||||
server.ConfigSource = tc.source
|
||||
saveWebSession(t, sessions, "web-1")
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/stream",
|
||||
@@ -916,18 +934,23 @@ func TestChatStreamEmitsNavigateChip(t *testing.T) {
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg *config.Holder
|
||||
name string
|
||||
source ConfigViewSource
|
||||
}{
|
||||
{name: "show_tool_calls off (navigate is unconditional)", cfg: config.NewHolder(config.Config{Chat: config.ChatConfig{ShowToolCalls: false}})},
|
||||
{name: "no Cfg wired at all", cfg: nil},
|
||||
{
|
||||
name: "show_tool_calls off (navigate is unconditional)",
|
||||
source: func(context.Context) (ConfigView, bool, error) {
|
||||
return ConfigView{Chat: ChatView{ShowToolCalls: false}}, true, nil
|
||||
},
|
||||
},
|
||||
{name: "no configuration source wired at all"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server, sessions := chatTestServer(t)
|
||||
testLocalChat(server.Chat).Router.LLMStream = stream
|
||||
server.Cfg = tc.cfg
|
||||
server.ConfigSource = tc.source
|
||||
saveWebSession(t, sessions, "web-1")
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/stream",
|
||||
|
||||
+73
-114
@@ -7,7 +7,6 @@ import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
@@ -57,19 +56,7 @@ func (s *Server) handleChannels(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"channels": views})
|
||||
return
|
||||
}
|
||||
if s.Cfg == nil {
|
||||
writeJSON(w, map[string]any{"channels": []ChannelView{}})
|
||||
return
|
||||
}
|
||||
|
||||
chat := s.Cfg.Get().Chat
|
||||
views := []ChannelView{
|
||||
telegramChannelView(chat.Telegram),
|
||||
webhookChannelView(chat.WebhookAddr),
|
||||
emailChannelView(chat.Email),
|
||||
}
|
||||
|
||||
writeJSON(w, map[string]any{"channels": views})
|
||||
writeJSON(w, map[string]any{"channels": []ChannelView{}})
|
||||
}
|
||||
|
||||
func (s *Server) handleChannelReload(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -138,70 +125,6 @@ func channelStateDetail(state status.State, configured bool) string {
|
||||
}
|
||||
}
|
||||
|
||||
func telegramChannelView(t config.TelegramConfig) ChannelView {
|
||||
configured := t.Token != (config.SecretRef{}) || strings.TrimSpace(t.TokenEnv) != ""
|
||||
detail := "Not configured."
|
||||
if configured {
|
||||
n := len(t.AllowedUserIDs)
|
||||
switch n {
|
||||
case 0:
|
||||
detail = "Token set, but the allowlist is empty -- the bot answers nobody."
|
||||
case 1:
|
||||
detail = "1 user allowed."
|
||||
default:
|
||||
detail = strconv.Itoa(n) + " users allowed."
|
||||
}
|
||||
}
|
||||
return ChannelView{
|
||||
ID: "telegram",
|
||||
Name: "Telegram",
|
||||
Configured: configured,
|
||||
Detail: detail,
|
||||
Description: "Talk to Archie and approve its work from your phone.",
|
||||
State: string(status.StateConfigured),
|
||||
ReloadSupported: true,
|
||||
}
|
||||
}
|
||||
|
||||
func webhookChannelView(addr string) ChannelView {
|
||||
configured := strings.TrimSpace(addr) != ""
|
||||
detail := "Not configured."
|
||||
if configured {
|
||||
detail = "Listening for inbound chat requests."
|
||||
}
|
||||
return ChannelView{
|
||||
ID: "webhook",
|
||||
Name: "Webhook gateway",
|
||||
Configured: configured,
|
||||
Detail: detail,
|
||||
Description: "Lets another service (e.g. a Telegram webhook, a custom front-end) push messages to Archie over HTTP instead of long-polling.",
|
||||
State: staticChannelState(configured),
|
||||
}
|
||||
}
|
||||
|
||||
func emailChannelView(e config.EmailConfig) ChannelView {
|
||||
configured := strings.TrimSpace(e.ListenAddr) != ""
|
||||
detail := "Not configured."
|
||||
if configured {
|
||||
detail = "Archie accepts inbound mail and can reply through the configured relay."
|
||||
}
|
||||
return ChannelView{
|
||||
ID: "email",
|
||||
Name: "Email",
|
||||
Configured: configured,
|
||||
Detail: detail,
|
||||
Description: "Email Archie a task and it replies from its own inbound SMTP listener.",
|
||||
State: staticChannelState(configured),
|
||||
}
|
||||
}
|
||||
|
||||
func staticChannelState(configured bool) string {
|
||||
if configured {
|
||||
return string(status.StateConfigured)
|
||||
}
|
||||
return string(status.StateStopped)
|
||||
}
|
||||
|
||||
// ConfigView is the read-only, secret-free projection of config.Config
|
||||
// shown on the dashboard's Configuration page. Every field here is an
|
||||
// explicit, hand-picked allowlist -- see handleConfig for why this is
|
||||
@@ -215,7 +138,11 @@ type ConfigView struct {
|
||||
Storage StorageView `json:"storage"`
|
||||
Containers ContainersView `json:"containers"`
|
||||
Web WebView `json:"web"`
|
||||
Provenance []ConfigOrigin `json:"provenance"`
|
||||
// Chat carries the dashboard's own chat-page settings. They are
|
||||
// daemon configuration the page cannot otherwise see: a process that
|
||||
// renders a published snapshot has no [chat] section to read.
|
||||
Chat ChatView `json:"chat"`
|
||||
Provenance []ConfigOrigin `json:"provenance"`
|
||||
// Reload reports the most recent config reload outcome. Omitted when
|
||||
// the reload status is unavailable.
|
||||
Reload *config.ReloadStatus `json:"reload,omitempty"`
|
||||
@@ -314,6 +241,20 @@ type ContainersView struct {
|
||||
}
|
||||
|
||||
// WebView is the dashboard's own listen address and proxy header trust settings.
|
||||
// ChatView carries the chat page's own settings and the facts the setup
|
||||
// checklist needs. Secret-free by construction: whether a channel has
|
||||
// credentials, never the credentials.
|
||||
type ChatView struct {
|
||||
ShowToolCalls bool `json:"show_tool_calls"`
|
||||
// Operator is the name the dashboard greets, configured once in
|
||||
// [chat]. Empty when unset, which the page renders as no greeting
|
||||
// rather than a hardcoded name.
|
||||
Operator string `json:"operator,omitempty"`
|
||||
// ChannelConfigured reports that at least one conversational
|
||||
// front-end has credentials.
|
||||
ChannelConfigured bool `json:"channel_configured"`
|
||||
}
|
||||
|
||||
type WebView struct {
|
||||
Listen string `json:"listen"`
|
||||
TrustForwardedHeaders bool `json:"trust_forwarded_headers"`
|
||||
@@ -341,11 +282,14 @@ const ConfigViewSchema = "webui.ConfigView/1"
|
||||
// empty object rather than an error.
|
||||
type ConfigViewSource func(ctx context.Context) (ConfigView, bool, error)
|
||||
|
||||
// configSource returns the projection source, or an empty one when
|
||||
// composition wired none: this process then renders no configuration rather
|
||||
// than inventing any.
|
||||
func (s *Server) configSource() ConfigViewSource {
|
||||
if s.ConfigSource != nil {
|
||||
return s.ConfigSource
|
||||
}
|
||||
return s.LocalConfigView
|
||||
return func(context.Context) (ConfigView, bool, error) { return ConfigView{}, false, nil }
|
||||
}
|
||||
|
||||
func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -359,26 +303,42 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{})
|
||||
return
|
||||
}
|
||||
// Editable belongs to the process that would perform the write, not to
|
||||
// the document: whoever holds the update path is the writer.
|
||||
view.Editable = s.UpdateConfig != nil
|
||||
writeJSON(w, view)
|
||||
}
|
||||
|
||||
// LocalConfigView builds the projection from the configuration this process
|
||||
// holds. It is what the daemon serves and, byte for byte, what it publishes
|
||||
// for the UI process to render (see storecontract.ConfigSnapshot).
|
||||
//
|
||||
// Every value here is read from one config snapshot taken up front: under the
|
||||
// Holder a reload swaps the whole value, which is what a read-only view
|
||||
// always wanted.
|
||||
func (s *Server) LocalConfigView(ctx context.Context) (ConfigView, bool, error) {
|
||||
if s.Cfg == nil {
|
||||
return ConfigView{}, false, nil
|
||||
}
|
||||
cfg := s.Cfg.Get()
|
||||
// ConfigViewInput is everything BuildConfigView needs. The configuration
|
||||
// owner assembles it: the config snapshot plus the display data it holds
|
||||
// alongside, already resolved, so building the view is pure and cannot fail.
|
||||
type ConfigViewInput struct {
|
||||
// Config is one snapshot, read once. Under a Holder a reload swaps the
|
||||
// whole value, which is what a read-only view always wanted.
|
||||
Config config.Config
|
||||
// Provenance is the file chain that produced Config, in precedence
|
||||
// order.
|
||||
Provenance []ConfigOrigin
|
||||
// Overridden lists the dotted keys the runtime overlay currently sets.
|
||||
Overridden []string
|
||||
// Reload is the most recent reload outcome, or nil when unavailable.
|
||||
Reload *config.ReloadStatus
|
||||
}
|
||||
|
||||
var provenance []ConfigOrigin
|
||||
if p := s.ConfigProvenance.Load(); p != nil {
|
||||
provenance = append([]ConfigOrigin(nil), (*p)...)
|
||||
}
|
||||
// BuildConfigView renders the dashboard's secret-free configuration
|
||||
// projection. The configuration owner calls it -- the daemon publishes the
|
||||
// result as a snapshot (storecontract.ConfigSnapshot) and a process that only
|
||||
// displays configuration reads that snapshot back through RemoteConfigView.
|
||||
//
|
||||
// It is deliberately a function, not a method: rendering the view is not a
|
||||
// property of an HTTP server, and the process that owns configuration is not
|
||||
// the process that serves this page (archie-core-ml30).
|
||||
//
|
||||
// Editable is not set here. It describes the rendering process's own write
|
||||
// path, so handleConfig decides it -- see ConfigView.Editable.
|
||||
func BuildConfigView(in ConfigViewInput) ConfigView {
|
||||
cfg := in.Config
|
||||
provenance := append([]ConfigOrigin(nil), in.Provenance...)
|
||||
|
||||
view := ConfigView{
|
||||
Identity: IdentityView{
|
||||
@@ -417,27 +377,27 @@ func (s *Server) LocalConfigView(ctx context.Context) (ConfigView, bool, error)
|
||||
Listen: cfg.Web.Listen,
|
||||
TrustForwardedHeaders: cfg.Web.TrustForwardedHeaders,
|
||||
},
|
||||
Chat: ChatView{
|
||||
ShowToolCalls: cfg.Chat.ShowToolCalls,
|
||||
Operator: strings.TrimSpace(cfg.Chat.Operator),
|
||||
ChannelConfigured: chatChannelConfigured(cfg.Chat),
|
||||
},
|
||||
Provenance: provenance,
|
||||
Overridden: in.Overridden,
|
||||
Reload: in.Reload,
|
||||
Locked: lockedConfigKeys(),
|
||||
// Editable is a property of this process, not of the
|
||||
// configuration, so it is set by the source rather than carried
|
||||
// in a published document: the writer is whoever holds the
|
||||
// update path.
|
||||
Editable: s.UpdateConfig != nil,
|
||||
}
|
||||
if s.ConfigOverrides != nil {
|
||||
if overridden, err := s.ConfigOverrides(ctx); err == nil {
|
||||
view.Overridden = overridden
|
||||
}
|
||||
// A failed read omits the list rather than failing the whole
|
||||
// view; the reload status carries the overlay degrade reason.
|
||||
}
|
||||
if s.LastReload != nil {
|
||||
rs := s.LastReload()
|
||||
view.Reload = &rs
|
||||
}
|
||||
view.Schema = buildConfigSchema(view)
|
||||
return view, true, nil
|
||||
return view
|
||||
}
|
||||
|
||||
// chatChannelConfigured reports whether any conversational front-end has
|
||||
// credentials. The setup checklist needs the answer, not the tokens, so the
|
||||
// projection carries the boolean.
|
||||
func chatChannelConfigured(chat config.ChatConfig) bool {
|
||||
return chat.Telegram.Token != (config.SecretRef{}) ||
|
||||
strings.TrimSpace(chat.Telegram.TokenEnv) != "" ||
|
||||
strings.TrimSpace(chat.WebhookAddr) != ""
|
||||
}
|
||||
|
||||
// RemoteConfigView reads the projection the configuration owner published.
|
||||
@@ -456,7 +416,6 @@ func RemoteConfigView(snapshots storecontract.ConfigSnapshotStore) ConfigViewSou
|
||||
if err := json.Unmarshal(snapshot.Document, &view); err != nil {
|
||||
return ConfigView{}, false, fmt.Errorf("webui: decode published config snapshot: %w", err)
|
||||
}
|
||||
view.Editable = false
|
||||
return view, true, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +73,26 @@ func leakCandidates() []string {
|
||||
return []string{fakeForgeToken, fakeProviderKey, fakeBWSKeyName, fakeNATSToken}
|
||||
}
|
||||
|
||||
// localView installs the projection a configuration owner publishes, built by
|
||||
// the same function the daemon calls. Tests that used to hand the server a
|
||||
// live config.Holder now hand it that holder's projection, which is what every
|
||||
// process renders from since the server stopped holding configuration
|
||||
// (archie-core-ml30).
|
||||
func localView(srv *Server, in ConfigViewInput) {
|
||||
srv.ConfigSource = func(context.Context) (ConfigView, bool, error) {
|
||||
return BuildConfigView(in), true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// localConfig is localView for the common case: a config snapshot and nothing
|
||||
// else.
|
||||
func localConfig(srv *Server, cfg *config.Holder) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
localView(srv, ConfigViewInput{Config: cfg.Get()})
|
||||
}
|
||||
|
||||
func TestHandleConfigNeverLeaksSecrets(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
@@ -86,7 +106,7 @@ func TestHandleConfigNeverLeaksSecrets(t *testing.T) {
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = tc.cfg
|
||||
localConfig(srv, tc.cfg)
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -116,7 +136,7 @@ func TestHandleConfigNeverLeaksSecrets(t *testing.T) {
|
||||
// secrets could pass trivially by returning {}.
|
||||
func TestHandleConfigSafeFieldsPresent(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -164,13 +184,13 @@ func TestHandleConfigSafeFieldsPresent(t *testing.T) {
|
||||
// without reading logs.
|
||||
func TestHandleConfigIncludesReloadStatus(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
srv.LastReload = func() config.ReloadStatus {
|
||||
return config.ReloadStatus{
|
||||
localView(srv, ConfigViewInput{
|
||||
Config: configWithFakeSecrets().Get(),
|
||||
Reload: &config.ReloadStatus{
|
||||
LastError: "poll_interval must be positive",
|
||||
LastErrorAt: "2026-08-09T12:00:00Z",
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -195,7 +215,7 @@ func TestHandleConfigIncludesReloadStatus(t *testing.T) {
|
||||
// field is absent (not empty) when the server has no reload seam wired.
|
||||
func TestHandleConfigOmitsReloadStatusWhenUnavailable(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -210,14 +230,16 @@ func TestHandleConfigOmitsReloadStatusWhenUnavailable(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetProvenancePublishesForConfigView proves a reloaded provenance
|
||||
// list reaches /api/config.
|
||||
func TestSetProvenancePublishesForConfigView(t *testing.T) {
|
||||
// TestConfigViewCarriesProvenance proves the provenance list the
|
||||
// configuration owner supplies reaches /api/config.
|
||||
func TestConfigViewCarriesProvenance(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
srv.SetProvenance([]ConfigOrigin{
|
||||
{Path: "/etc/archie/config.toml", Role: "main", Layer: "base"},
|
||||
{Path: "/etc/archie/conf.d/docker.yaml", Role: "extra", Layer: "overlay", Feature: "docker"},
|
||||
localView(srv, ConfigViewInput{
|
||||
Config: configWithFakeSecrets().Get(),
|
||||
Provenance: []ConfigOrigin{
|
||||
{Path: "/etc/archie/config.toml", Role: "main", Layer: "base"},
|
||||
{Path: "/etc/archie/conf.d/docker.yaml", Role: "extra", Layer: "overlay", Feature: "docker"},
|
||||
},
|
||||
})
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
@@ -241,7 +263,7 @@ func TestSetProvenancePublishesForConfigView(t *testing.T) {
|
||||
// instead of silently omitting the edit affordance.
|
||||
func TestHandleConfigReportsLockedKeys(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -264,12 +286,12 @@ func TestHandleConfigReportsLockedKeys(t *testing.T) {
|
||||
// (archie-core-b6ew.4).
|
||||
func TestHandleConfigRepoViewIncludesReviewEnabled(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = config.NewHolder(config.Config{
|
||||
localView(srv, ConfigViewInput{Config: config.Config{
|
||||
Repos: []config.Repo{
|
||||
{Owner: "acme", Name: "widget", Base: "main", AllowConcurrent: true, MaxRetries: 3, ReviewEnabled: true},
|
||||
{Owner: "acme", Name: "gadget", Base: "main"},
|
||||
},
|
||||
})
|
||||
}})
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -297,7 +319,7 @@ func TestHandleConfigRepoViewIncludesReviewEnabled(t *testing.T) {
|
||||
// not a stale or empty catalog.
|
||||
func TestHandleConfigIncludesSchemaWithLiveValues(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -364,7 +386,7 @@ func TestHandleConfigIncludesSchemaWithLiveValues(t *testing.T) {
|
||||
// be caught even if leakCandidates never appears in the flat fields.
|
||||
func TestHandleConfigSchemaNeverLeaksSecrets(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -462,10 +484,10 @@ func TestHandleConfigUpdateWithoutSeamMapsTo503(t *testing.T) {
|
||||
// reach the view so the UI can mark rows shadowed by the runtime overlay.
|
||||
func TestHandleConfigIncludesOverridden(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
srv.ConfigOverrides = func(context.Context) ([]string, error) {
|
||||
return []string{"budgets.max_steps", "label"}, nil
|
||||
}
|
||||
localView(srv, ConfigViewInput{
|
||||
Config: configWithFakeSecrets().Get(),
|
||||
Overridden: []string{"budgets.max_steps", "label"},
|
||||
})
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -528,9 +550,13 @@ func TestHandleConfigResetRejectsEmptyKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleChannelsReportsConfiguredState(t *testing.T) {
|
||||
// TestHandleChannelsWithoutManagerIsEmpty: channel lifecycle is the status
|
||||
// manager's to report. A process without one answers an empty list rather
|
||||
// than deriving channels from configuration, which could only ever describe
|
||||
// what was configured, never what is running.
|
||||
func TestHandleChannelsWithoutManagerIsEmpty(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/channels", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -539,46 +565,12 @@ func TestHandleChannelsReportsConfiguredState(t *testing.T) {
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
for _, leak := range leakCandidates() {
|
||||
if strings.Contains(body, leak) {
|
||||
t.Errorf("channels response leaked secret value %q:\n%s", leak, body)
|
||||
}
|
||||
}
|
||||
|
||||
var got struct {
|
||||
Channels []ChannelView `json:"channels"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
|
||||
var telegram *ChannelView
|
||||
for i := range got.Channels {
|
||||
if got.Channels[i].Name == "Telegram" {
|
||||
telegram = &got.Channels[i]
|
||||
}
|
||||
}
|
||||
if telegram == nil {
|
||||
t.Fatal("no Telegram channel in response")
|
||||
}
|
||||
if !telegram.Configured {
|
||||
t.Errorf("Telegram.Configured = false, want true (TokenEnv is set)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleChannelsNilConfig(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = nil
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/channels", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var got struct {
|
||||
Channels []ChannelView `json:"channels"`
|
||||
}
|
||||
@@ -586,13 +578,12 @@ func TestHandleChannelsNilConfig(t *testing.T) {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(got.Channels) != 0 {
|
||||
t.Errorf("Channels = %+v, want empty when Cfg is nil", got.Channels)
|
||||
t.Errorf("Channels = %+v, want empty without a status manager", got.Channels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleChannelsUsesRuntimeManager(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
srv.Channels = status.NewManager([]status.Descriptor{{
|
||||
ID: "telegram", Name: "Telegram", Configured: true, ReloadSupported: true,
|
||||
}})
|
||||
@@ -615,14 +606,14 @@ func TestHandleChannelsUsesRuntimeManager(t *testing.T) {
|
||||
|
||||
// TestRemoteConfigViewRendersThePublishedSnapshot: the UI process has no
|
||||
// configuration of its own, so the page it serves is whatever the owner
|
||||
// published -- and it must never claim to be editable, because this process
|
||||
// has no write path and its PATCH routes answer 503.
|
||||
// published. Whether that page is editable is decided by the process that
|
||||
// renders it, not by the document -- see
|
||||
// TestConfigViewEditableFollowsThisProcessWritePath.
|
||||
func TestRemoteConfigViewRendersThePublishedSnapshot(t *testing.T) {
|
||||
published := ConfigView{
|
||||
Identity: IdentityView{BotUser: "archie", ForgeType: "github"},
|
||||
Models: map[string]string{"chat": "anthropic/claude"},
|
||||
Providers: map[string]ProviderView{"anthropic": {APIKeyEnv: "ANTHROPIC_API_KEY", Configured: true}},
|
||||
Editable: true, // the daemon's own view; publishing must not carry it
|
||||
Provenance: []ConfigOrigin{{Path: "/etc/archie/config.toml", Role: "main"}},
|
||||
}
|
||||
document, err := json.Marshal(published)
|
||||
@@ -641,8 +632,44 @@ func TestRemoteConfigViewRendersThePublishedSnapshot(t *testing.T) {
|
||||
if view.Identity.BotUser != "archie" || view.Providers["anthropic"].APIKeyEnv != "ANTHROPIC_API_KEY" {
|
||||
t.Fatalf("view = %+v, want the published values", view)
|
||||
}
|
||||
if view.Editable {
|
||||
t.Error("a rendered snapshot claims to be editable; this process has no write path")
|
||||
if len(view.Provenance) != 1 || view.Provenance[0].Path != "/etc/archie/config.toml" {
|
||||
t.Errorf("Provenance = %+v, want the published chain", view.Provenance)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfigViewEditableFollowsThisProcessWritePath: Editable describes the
|
||||
// rendering process, not the document. A published snapshot cannot make a
|
||||
// reader editable, and a process that holds the update path says so even
|
||||
// when the document it renders says otherwise.
|
||||
func TestConfigViewEditableFollowsThisProcessWritePath(t *testing.T) {
|
||||
render := func(t *testing.T, wireUpdate bool) ConfigView {
|
||||
t.Helper()
|
||||
srv := newTestServer(t)
|
||||
srv.ConfigSource = func(context.Context) (ConfigView, bool, error) {
|
||||
// The document claims editable; only the process decides.
|
||||
return ConfigView{Editable: true}, true, nil
|
||||
}
|
||||
if wireUpdate {
|
||||
srv.UpdateConfig = func(context.Context, map[string]any) error { return nil }
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/config = %d, want 200", w.Code)
|
||||
}
|
||||
var got ConfigView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
if render(t, false).Editable {
|
||||
t.Error("Editable = true without an update path; the write routes answer 503")
|
||||
}
|
||||
if !render(t, true).Editable {
|
||||
t.Error("Editable = false with UpdateConfig wired; the page would hide controls that work")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -725,7 +752,7 @@ func TestCapabilitiesReportWhatThisProcessCanServe(t *testing.T) {
|
||||
}
|
||||
|
||||
wired := newTestServer(t)
|
||||
wired.Cfg = config.NewHolder(config.Config{})
|
||||
wired.Channels = status.NewManager([]status.Descriptor{{ID: "telegram", Name: "Telegram"}})
|
||||
wired.LogFeed = logging.NewFeed(10)
|
||||
wired.Memory = stubMemory{}
|
||||
wired.Curators = stubCurators{}
|
||||
|
||||
@@ -126,12 +126,13 @@ func mergeComponents(history []string, live []logging.Entry) []string {
|
||||
return components
|
||||
}
|
||||
|
||||
// logFile reports the configured log path, or "" when file logging is off.
|
||||
// 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 {
|
||||
if s.Cfg == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(s.Cfg.Get().Log.File)
|
||||
return strings.TrimSpace(s.LogFile)
|
||||
}
|
||||
|
||||
func splitCSV(v string) []string {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
@@ -26,7 +25,7 @@ func TestLogEndpointsValidateAndBoundLimit(t *testing.T) {
|
||||
if err := closer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.Cfg = config.NewHolder(config.Config{Log: config.Log{File: daemonLogPath}})
|
||||
srv.LogFile = daemonLogPath
|
||||
|
||||
taskLogDir := t.TempDir()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(taskLogDir, nil, logging.TaskSinkOptions{})
|
||||
|
||||
+11
-19
@@ -3,8 +3,6 @@ package webui
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// SetupStep is one item in the dashboard's getting-started checklist.
|
||||
@@ -27,9 +25,13 @@ type SetupStep struct {
|
||||
func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
steps := []SetupStep{}
|
||||
|
||||
if s.Cfg == nil {
|
||||
// No config wired in: report nothing rather than guessing, so the
|
||||
// dashboard simply omits the panel.
|
||||
// Every step is read from the configuration projection this process
|
||||
// renders, so the checklist works the same whether configuration is
|
||||
// held here or published by its owner.
|
||||
view, found, err := s.configSource()(r.Context())
|
||||
if err != nil || !found {
|
||||
// No configuration available: report nothing rather than
|
||||
// guessing, so the dashboard simply omits the panel.
|
||||
writeJSON(w, map[string]any{"steps": steps})
|
||||
return
|
||||
}
|
||||
@@ -37,25 +39,24 @@ func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
// The operator's name is deployment data, configured once in [chat]. The
|
||||
// dashboard greets with it rather than hardcoding a name, which would be
|
||||
// wrong on every deployment but one.
|
||||
cfg := s.Cfg.Get()
|
||||
operator := strings.TrimSpace(cfg.Chat.Operator)
|
||||
operator := view.Chat.Operator
|
||||
|
||||
steps = append(steps, SetupStep{
|
||||
Title: "Give Archie an identity",
|
||||
Detail: "The account it commits and comments as.",
|
||||
Done: strings.TrimSpace(cfg.BotUser) != "",
|
||||
Done: strings.TrimSpace(view.Identity.BotUser) != "",
|
||||
})
|
||||
|
||||
steps = append(steps, SetupStep{
|
||||
Title: "Connect a repository",
|
||||
Detail: "Archie polls these for issues assigned to it.",
|
||||
Done: len(cfg.Repos) > 0,
|
||||
Done: len(view.Repositories) > 0,
|
||||
})
|
||||
|
||||
steps = append(steps, SetupStep{
|
||||
Title: "Connect a chat channel",
|
||||
Detail: "Talk to Archie and approve its work from your phone.",
|
||||
Done: s.hasChannel(),
|
||||
Done: view.Chat.ChannelConfigured,
|
||||
})
|
||||
|
||||
// Only meaningful once there is somewhere to run work.
|
||||
@@ -73,12 +74,3 @@ func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
writeJSON(w, map[string]any{"steps": steps, "operator": operator})
|
||||
}
|
||||
|
||||
// hasChannel reports whether any conversational front-end is configured.
|
||||
// Chat is disabled entirely when no channel token is set, so the presence of
|
||||
// one is the honest signal here.
|
||||
func (s *Server) hasChannel() bool {
|
||||
cfg := s.Cfg.Get()
|
||||
return cfg.Chat.Telegram.Token != (config.SecretRef{}) || strings.TrimSpace(cfg.Chat.Telegram.TokenEnv) != "" ||
|
||||
strings.TrimSpace(cfg.Chat.WebhookAddr) != ""
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// TestSetupChecklistRendersFromTheProjection: the checklist is derived from
|
||||
// the configuration projection, so it works in a process that holds no
|
||||
// configuration of its own. It reported nothing there while it read a live
|
||||
// holder, which the extracted dashboard never receives (archie-core-ml30).
|
||||
func TestSetupChecklistRendersFromTheProjection(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg config.Config
|
||||
wantOperator string
|
||||
wantDone map[string]bool
|
||||
}{
|
||||
{
|
||||
name: "nothing configured yet",
|
||||
cfg: config.Config{},
|
||||
wantDone: map[string]bool{
|
||||
"Give Archie an identity": false,
|
||||
"Connect a repository": false,
|
||||
"Connect a chat channel": false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "identity, repository and a telegram token",
|
||||
cfg: config.Config{
|
||||
BotUser: "archie-bot",
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "widget"}},
|
||||
Chat: config.ChatConfig{
|
||||
Operator: "Sam",
|
||||
Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"},
|
||||
},
|
||||
},
|
||||
wantOperator: "Sam",
|
||||
wantDone: map[string]bool{
|
||||
"Give Archie an identity": true,
|
||||
"Connect a repository": true,
|
||||
"Connect a chat channel": true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a webhook address counts as a channel",
|
||||
cfg: config.Config{
|
||||
Chat: config.ChatConfig{WebhookAddr: "127.0.0.1:9099"},
|
||||
},
|
||||
wantDone: map[string]bool{
|
||||
"Give Archie an identity": false,
|
||||
"Connect a repository": false,
|
||||
"Connect a chat channel": true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
// Round-tripped through the published document, which is how
|
||||
// the dashboard actually receives it.
|
||||
published := BuildConfigView(ConfigViewInput{Config: tc.cfg})
|
||||
document, err := json.Marshal(published)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.ConfigSource = func(context.Context) (ConfigView, bool, error) {
|
||||
var view ConfigView
|
||||
if err := json.Unmarshal(document, &view); err != nil {
|
||||
return ConfigView{}, false, err
|
||||
}
|
||||
return view, true, nil
|
||||
}
|
||||
|
||||
got := getSetup(t, srv)
|
||||
if got.Operator != tc.wantOperator {
|
||||
t.Errorf("operator = %q, want %q", got.Operator, tc.wantOperator)
|
||||
}
|
||||
done := map[string]bool{}
|
||||
for _, step := range got.Steps {
|
||||
done[step.Title] = step.Done
|
||||
}
|
||||
for title, want := range tc.wantDone {
|
||||
if done[title] != want {
|
||||
t.Errorf("step %q done = %v, want %v", title, done[title], want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupChecklistOmittedWithoutAProjection: no configuration to read means
|
||||
// the panel is omitted, not guessed at from zeroes.
|
||||
func TestSetupChecklistOmittedWithoutAProjection(t *testing.T) {
|
||||
got := getSetup(t, newTestServer(t))
|
||||
if len(got.Steps) != 0 {
|
||||
t.Errorf("steps = %+v, want none without a configuration projection", got.Steps)
|
||||
}
|
||||
}
|
||||
|
||||
type setupResponse struct {
|
||||
Steps []SetupStep `json:"steps"`
|
||||
Operator string `json:"operator"`
|
||||
}
|
||||
|
||||
func getSetup(t *testing.T, srv *Server) setupResponse {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/setup", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/setup = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var got setupResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
@@ -81,21 +80,11 @@ type forgeCoordinates struct {
|
||||
// resolveForge reads the forge layout once for a request and returns each
|
||||
// task's coordinates from it.
|
||||
//
|
||||
// The daemon holds the configuration and resolves per task, so a deployment
|
||||
// with several identities links each task to its own forge. The UI process
|
||||
// holds none and reads the projection the daemon published instead, which
|
||||
// carries the default identity alone -- so where that is not the whole
|
||||
// picture it withholds the links rather than pointing them at the wrong
|
||||
// The projection carries the default identity alone, so where that is not
|
||||
// the whole picture the links are withheld rather than pointed at the wrong
|
||||
// forge. Publishing per-identity forges is what a multi-identity dashboard
|
||||
// needs, and it is a projection change, not a rendering one.
|
||||
func (s *Server) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates {
|
||||
if s.Cfg != nil {
|
||||
cfg := s.Cfg.Get()
|
||||
return func(t task.Task) forgeCoordinates {
|
||||
forge := forgeConfigForTask(cfg, t)
|
||||
return forgeCoordinates{host: forge.Host, forgeType: forge.Type}
|
||||
}
|
||||
}
|
||||
unlinked := func(task.Task) forgeCoordinates { return forgeCoordinates{} }
|
||||
view, ok, err := s.configSource()(ctx)
|
||||
if err != nil || !ok || view.MultiIdentity {
|
||||
@@ -123,31 +112,6 @@ func taskURLs(task task.Task, forge forgeCoordinates) (repoURL, issueURL, prURL
|
||||
return repoURL, issueURL, prURL
|
||||
}
|
||||
|
||||
func forgeConfigForTask(cfg config.Config, task task.Task) config.Forge {
|
||||
for _, identity := range cfg.Identities {
|
||||
if task.Identity != "" && identity.Name == task.Identity {
|
||||
return identity.Forge
|
||||
}
|
||||
}
|
||||
var matched *config.Forge
|
||||
for i := range cfg.Identities {
|
||||
identity := &cfg.Identities[i]
|
||||
for _, repo := range identity.Repos {
|
||||
if repo.Owner == task.Owner && repo.Name == task.Repo {
|
||||
if matched != nil {
|
||||
return cfg.Forge
|
||||
}
|
||||
forgeCopy := identity.Forge
|
||||
matched = &forgeCopy
|
||||
}
|
||||
}
|
||||
}
|
||||
if matched != nil {
|
||||
return *matched
|
||||
}
|
||||
return cfg.Forge
|
||||
}
|
||||
|
||||
func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
|
||||
@@ -52,7 +52,11 @@ func (r *recordingCloser) CloseIssue(_ context.Context, owner, repo string, numb
|
||||
// The service is rebuilt per call because tests attach collaborators after
|
||||
// the server exists, exactly as the daemon rebuilds it per request.
|
||||
type daemonActions struct {
|
||||
srv *Server
|
||||
srv *Server
|
||||
// cfg is the daemon's configuration, held by the stand-in daemon
|
||||
// rather than by the dashboard: retry caps are the task owner's
|
||||
// policy and the dashboard does not hold configuration.
|
||||
cfg *config.Holder
|
||||
issues *recordingCloser
|
||||
stopper *recordingTaskStopper
|
||||
// scopes records the identity each action arrived with, one per call.
|
||||
@@ -65,7 +69,7 @@ func (d *daemonActions) ApplyChatTaskAction(
|
||||
d.scopes = append(d.scopes, identity)
|
||||
service := taskactionstore.NewService(
|
||||
taskactionstore.Store{TaskStore: d.srv.Store},
|
||||
taskactionstore.MaxRetries(d.srv.Cfg),
|
||||
taskactionstore.MaxRetries(d.cfg),
|
||||
d.cancelTask(),
|
||||
d.closeIssue(),
|
||||
d.removeLogs(),
|
||||
@@ -109,7 +113,7 @@ func (d *daemonActions) publish() func(events.Event) {
|
||||
// wireOperatorActions gives srv a task-action owner, the way composition
|
||||
// gives the dashboard a Gateway contract.
|
||||
func wireOperatorActions(srv *Server) *daemonActions {
|
||||
actions := &daemonActions{srv: srv}
|
||||
actions := &daemonActions{srv: srv, cfg: config.NewHolder(config.Config{})}
|
||||
srv.Chat = &ChatService{Contract: &gateway.LocalChatAdapter{TaskActor: actions}}
|
||||
return actions
|
||||
}
|
||||
@@ -153,7 +157,7 @@ func actionServer(t *testing.T, status, parkReason string) (*Server, *workflow.T
|
||||
|
||||
operatorActions(t, srv).issues = closer
|
||||
srv.Events = bus
|
||||
srv.Cfg = config.NewHolder(config.Config{MaxRetries: 3})
|
||||
operatorActions(t, srv).cfg = config.NewHolder(config.Config{MaxRetries: 3})
|
||||
return srv, task, closer, bus, sub
|
||||
}
|
||||
|
||||
@@ -219,7 +223,7 @@ func TestRetryEnforcesMaxRetries(t *testing.T) {
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusParked, "it broke")
|
||||
srv.Cfg = config.NewHolder(config.Config{MaxRetries: tc.maxRetries})
|
||||
operatorActions(t, srv).cfg = config.NewHolder(config.Config{MaxRetries: tc.maxRetries})
|
||||
ctx := t.Context()
|
||||
for range tc.priorCount {
|
||||
if err := srv.Store.IncrementRetryCount(ctx, task.ID); err != nil {
|
||||
@@ -294,7 +298,7 @@ func TestRejectDoesNotCloseAChatTaskIssue(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
closer := &recordingCloser{}
|
||||
operatorActions(t, srv).issues = closer
|
||||
srv.Cfg = config.NewHolder(config.Config{MaxRetries: 3})
|
||||
operatorActions(t, srv).cfg = config.NewHolder(config.Config{MaxRetries: 3})
|
||||
|
||||
task, err := srv.Store.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "")
|
||||
if err != nil {
|
||||
@@ -516,9 +520,8 @@ func TestTaskActionStoreFailureIs500(t *testing.T) {
|
||||
srv := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, requeueErr: errors.New("db locked")},
|
||||
Log: base.Log,
|
||||
Cfg: config.NewHolder(config.Config{MaxRetries: 3}),
|
||||
}
|
||||
wireOperatorActions(srv)
|
||||
wireOperatorActions(srv).cfg = config.NewHolder(config.Config{MaxRetries: 3})
|
||||
w := postAction(t, srv, task.ID, "approve")
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500: a store failure is not a conflict", w.Code)
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
@@ -16,7 +15,6 @@ func TestAuthorizeTaskMutationOrigin(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
trustForwardedDirect bool
|
||||
trustForwardedCfg *bool
|
||||
forwardedProto string
|
||||
forwardedHost string
|
||||
requestHost string
|
||||
@@ -37,17 +35,6 @@ func TestAuthorizeTaskMutationOrigin(t *testing.T) {
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "1b. proxied https: trust enabled via Cfg holder, X-Forwarded-Proto https, plain HTTP, Origin https",
|
||||
trustForwardedCfg: new(true),
|
||||
forwardedProto: "https",
|
||||
requestHost: "archie.catlow.cloud",
|
||||
tls: false,
|
||||
origin: "https://archie.catlow.cloud",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "1c. proxied https: comma-separated X-Forwarded-Proto list",
|
||||
trustForwardedDirect: true,
|
||||
@@ -183,13 +170,6 @@ func TestAuthorizeTaskMutationOrigin(t *testing.T) {
|
||||
}
|
||||
|
||||
srv.TrustForwardedHeaders = tc.trustForwardedDirect
|
||||
if tc.trustForwardedCfg != nil {
|
||||
srv.Cfg = config.NewHolder(config.Config{
|
||||
Web: config.Web{
|
||||
TrustForwardedHeaders: *tc.trustForwardedCfg,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
path := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/action"
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost, path, strings.NewReader(`{"action":"cancel"}`))
|
||||
|
||||
@@ -17,35 +17,10 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
func TestTaskURLsUseOwningForgeRoutes(t *testing.T) {
|
||||
srv := &Server{Cfg: config.NewHolder(config.Config{
|
||||
Forge: config.Forge{Type: "github", Host: "https://github.example"},
|
||||
Identities: []config.IdentityConfig{{
|
||||
Name: "gitea", Forge: config.Forge{Type: "gitea", Host: "https://gitea.example"},
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "widget"}},
|
||||
}},
|
||||
})}
|
||||
task := workflow.Task{Owner: "acme", Repo: "widget", IssueNumber: 12, PRNumber: 34, Identity: "gitea"}
|
||||
|
||||
forge := srv.resolveForge(t.Context())
|
||||
repoURL, issueURL, prURL := taskURLs(task, forge(task))
|
||||
if repoURL != "https://gitea.example/acme/widget" || issueURL != repoURL+"/issues/12" || prURL != repoURL+"/pulls/34" {
|
||||
t.Fatalf("URLs = %q, %q, %q; want canonical Gitea routes", repoURL, issueURL, prURL)
|
||||
}
|
||||
|
||||
task.Identity = ""
|
||||
task.Owner, task.Repo = "other", "repo"
|
||||
_, _, prURL = taskURLs(task, forge(task))
|
||||
if prURL != "https://github.example/other/repo/pull/34" {
|
||||
t.Fatalf("GitHub PR URL = %q", prURL)
|
||||
}
|
||||
}
|
||||
|
||||
// A process with no configuration of its own still has to render the links,
|
||||
// or the extracted dashboard loses every click-through to the issue and the
|
||||
// pull request it opened. The daemon's published projection is where they
|
||||
|
||||
@@ -20,7 +20,6 @@ import (
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
@@ -66,7 +65,6 @@ func newRemoteTestServer(t *testing.T) *Server {
|
||||
t.Cleanup(closeConn)
|
||||
|
||||
return &Server{
|
||||
Cfg: config.NewHolder(config.Config{}),
|
||||
Store: client,
|
||||
Captures: client,
|
||||
Mappings: client,
|
||||
|
||||
@@ -14,10 +14,8 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
@@ -31,18 +29,6 @@ type Server struct {
|
||||
Store storecontract.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
|
||||
|
||||
// ConfigSource supplies the configuration projection GET /api/config
|
||||
// renders. Composition sets it to RemoteConfigView in a process that
|
||||
// only displays configuration; unset means this process builds the view
|
||||
@@ -62,20 +48,6 @@ type Server struct {
|
||||
// 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
|
||||
@@ -83,12 +55,6 @@ type Server struct {
|
||||
// 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
|
||||
@@ -199,6 +165,11 @@ type Server struct {
|
||||
// than Confirmed.
|
||||
RunningVersions func() map[string]string
|
||||
|
||||
// LogFile is the log file this process can read history from, for
|
||||
// GET /api/logs. Process-local: the file is on the daemon's disk, so
|
||||
// only a dashboard sharing that host can set it.
|
||||
LogFile 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).
|
||||
@@ -213,13 +184,7 @@ 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
|
||||
return s.TrustForwardedHeaders
|
||||
}
|
||||
|
||||
// ConfigOrigin explains one source file contributing to the effective
|
||||
@@ -232,9 +197,6 @@ type ConfigOrigin struct {
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
Reference in new issue
Block a user