fix(webui): give dashboard-initiated updates a phase-2 report

handleChatUpdateInstall called Install with InstallMeta{Channel:
"webui"} and no ReportPath, so the update watchdog's write_report()
silently returned without ever persisting a phase-2 outcome
(restart/health-check/version verification). Telegram had this via
reportPendingUpdate/SendPendingReport; the dashboard had nothing --
an operator who approved an update from the webui only ever saw the
synchronous phase-1 install result, never whether the daemon came
back up on the version it claimed.

Give webui its own report path (updateReportPath(cfg.WorkDir,
"webui"), hashed the same way as Telegram's per-identity path so the
two can never collide) and a boot-time reportPendingUpdate, mirroring
Telegram's but emitting a structured events.KindUpdateReport onto the
existing SSE/activity stream instead of a chat message -- the
dashboard has no session-scoped recipient to route text to the way a
chat ID gives Telegram one. Report.Verify's Confirmed/Drift/Unverified
partition (c25799e) is reused as-is; only the surface differs.

Closes archie-core-nln7 / GH#531.
This commit is contained in:
sam committed 2026-08-23 22:58:05 +10:00
1 parent 1f93eab94b
commit 01dd72ab04
8 files changed
+363 -34

No files matched your search

+7
View File
@@ -53,6 +53,13 @@ const (
// never produces this kind, so derived work cannot feed its own
// trigger. data: session, channel.
KindTurnCompleted = "turn_completed"
// KindUpdateReport carries the phase-2 outcome of a dashboard-initiated
// update -- whether the restarted daemon came back up healthy and on
// the version it claimed, relayed once on the boot that finds the
// pending report left by the update watchdog (archie-core-nln7).
// data: health_check, rolled_back, confirmed, drift, unverified.
KindUpdateReport = "update_report"
)
// Event is the single wire type: task lifecycle, stage progress, agent
+2 -1
View File
@@ -509,7 +509,8 @@ func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request)
}()
progress := make([]string, 0, 4)
result, err := chat.Updates.Install(r.Context(), releaseupdate.InstallMeta{Channel: "webui"}, func(message string) { progress = append(progress, message) })
meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: s.UpdateReportPath}
result, err := chat.Updates.Install(r.Context(), meta, func(message string) { progress = append(progress, message) })
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
+10 -8
View File
@@ -57,9 +57,10 @@ func (s *chatProviderModelStub) ModelsForProvider(provider string) []string {
func (*chatProviderModelStub) SetActiveProvider(context.Context, string) error { return nil }
type chatUpdateStub struct {
snapshot releaseupdate.Snapshot
deferred releaseupdate.Snapshot
installed bool
snapshot releaseupdate.Snapshot
deferred releaseupdate.Snapshot
installed bool
installedMeta releaseupdate.InstallMeta
}
type webDangerousStub struct {
@@ -90,8 +91,9 @@ func (s *chatUpdateStub) Defer(_ context.Context, _ int64, snapshot releaseupdat
return nil
}
func (s *chatUpdateStub) Install(_ context.Context, _ releaseupdate.InstallMeta, progress func(string)) (releaseupdate.Result, error) {
func (s *chatUpdateStub) Install(_ context.Context, meta releaseupdate.InstallMeta, progress func(string)) (releaseupdate.Result, error) {
s.installed = true
s.installedMeta = meta
progress("install started")
return releaseupdate.Result{}, nil
}
@@ -706,14 +708,14 @@ func TestChatStreamRendersMediaAsALinkFallback(t *testing.T) {
t.Fatalf("status = %d, body = %s", res.Code, res.Body)
}
var joined string
var joined strings.Builder
for _, ev := range parseChatSSE(t, res.Body.String()) {
if ev.Type == "delta" {
joined += ev.Text
joined.WriteString(ev.Text)
}
}
if !strings.Contains(joined, "https://example.com/v.mp4") {
t.Fatalf("delta stream = %q, want it to contain the asset URL", joined)
if !strings.Contains(joined.String(), "https://example.com/v.mp4") {
t.Fatalf("delta stream = %q, want it to contain the asset URL", joined.String())
}
}
+16
View File
@@ -154,6 +154,21 @@ type Server struct {
// the dashboard failing to start.
Mappings store.MappingStore
// UpdateReportPath is where the update watchdog leaves the phase-2
// outcome of a dashboard-initiated install for this process to relay on
// its next boot -- the webui counterpart of
// channels/telegram.Gateway.UpdateReportPath. Empty (the default unless
// composition wires it) means dashboard-initiated updates get no
// phase-2 report (archie-core-nln7): the operator only sees the
// synchronous install result, never restart/health/version outcome.
UpdateReportPath string
// RunningVersions reports, per component ID (see releaseupdate.Report.Verify),
// the version that component reports for itself right now. Optional:
// nil leaves every claim in a relayed update report Unverified rather
// than Confirmed.
RunningVersions func() map[string]string
mu sync.Mutex
conns map[chan events.Event]struct{}
}
@@ -291,6 +306,7 @@ func trimLeadingSlash(p string) string {
// Run serves until ctx ends.
func (s *Server) Run(ctx context.Context, listen string) error {
s.reportPendingUpdate(ctx)
srv := &http.Server{Addr: listen, Handler: s.Handler(), ReadHeaderTimeout: 5 * time.Second}
go func() {
<-ctx.Done()
+117
View File
@@ -0,0 +1,117 @@
package webui
import (
"context"
"fmt"
"sort"
"strings"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
// reportPendingUpdate checks for a phase-2 outcome left by the update
// watchdog for a dashboard-initiated install and relays it onto the
// activity stream, mirroring internal/channels/telegram/update.go's
// reportPendingUpdate for the Telegram channel. Called once on every daemon
// boot (Server.Run), so it fires whether this is the restart the update
// itself triggered or a later, unrelated restart.
//
// A report is cleared as soon as it's handled -- relayed, or found
// unreadable -- so a later boot never retries it and two boots never race
// to relay the same outcome.
func (s *Server) reportPendingUpdate(ctx context.Context) {
if s.UpdateReportPath == "" {
return
}
report, found, err := releaseupdate.ReadPendingReport(s.UpdateReportPath)
if err != nil {
s.logf("read pending update report failed; discarding it", "err", err)
if clearErr := releaseupdate.ClearPendingReport(s.UpdateReportPath); clearErr != nil {
s.logf("clear unreadable update report failed", "err", clearErr)
}
return
}
if !found {
return
}
s.emit(ctx, updateReportEvent(report, s.runningVersions()))
if err := releaseupdate.ClearPendingReport(s.UpdateReportPath); err != nil {
s.logf("clear pending update report failed", "err", err)
}
}
// runningVersions returns the versions components report for themselves, or
// nil when the composition root wired none -- see the identical seam on
// internal/channels/telegram.Gateway. Nil is not a no-op: with nothing to
// check against, every claim comes back Unverified rather than Confirmed.
func (s *Server) runningVersions() map[string]string {
if s.RunningVersions == nil {
return nil
}
return s.RunningVersions()
}
// updateReportEvent turns a phase-2 Report, plus its verification against
// the versions actually running, into the activity-stream event the
// dashboard renders. Unlike Telegram's formatPendingReport, this ships the
// structured Verification rather than pre-rendered prose, so the frontend
// controls presentation -- the two channels' operators read the same facts
// through different UIs, not necessarily the same sentence.
func updateReportEvent(report releaseupdate.Report, running map[string]string) events.Event {
verification := report.Verify(running)
drift := make([]map[string]any, 0, len(verification.Drift))
for _, d := range verification.Drift {
drift = append(drift, map[string]any{
"id": d.ID,
"claimed": d.Claimed,
"running": d.Running,
"running_is_previous": d.RunningIsPrevious,
})
}
return events.Event{
Kind: events.KindUpdateReport,
Detail: summarizeUpdateReport(report, verification),
Data: map[string]any{
"health_check": report.HealthCheck,
"rolled_back": report.RolledBack,
"previous": report.Previous,
"installed": report.Installed,
"confirmed": verification.Confirmed,
"drift": drift,
"unverified": verification.Unverified,
},
}
}
// summarizeUpdateReport is the one-line summary shown in the dashboard's
// activity feed, which renders event.Detail generically for every event
// kind (see ui/src/dashboard/dashboard.js activityRow). It condenses the
// same facts internal/channels/telegram/update.go's formatPendingReport
// spells out at length -- not a byte-identical wording, since the two
// surfaces render differently, but the same four outcomes: confirmed,
// drifted, unverified, or rolled back.
func summarizeUpdateReport(report releaseupdate.Report, verification releaseupdate.Verification) string {
if report.RolledBack {
return "Update failed its health check and was rolled back to the previous version."
}
if report.HealthCheck != "passed" {
return "Update failed its health check and could NOT be rolled back automatically -- manual intervention required."
}
if len(verification.Drift) > 0 {
ids := make([]string, 0, len(verification.Drift))
for _, d := range verification.Drift {
ids = append(ids, fmt.Sprintf("%s reports %s, not the installed %s", d.ID, d.Running, d.Claimed))
}
sort.Strings(ids)
return "Update did NOT take effect: " + strings.Join(ids, "; ") + "."
}
if len(verification.Confirmed) == 0 {
return "Update complete. Health check passed, but no version could be confirmed running."
}
text := "Update complete. Health check passed -- confirmed running on the new version (" + strings.Join(verification.Confirmed, ", ") + ")."
if len(verification.Unverified) > 0 {
text += " Not independently checked: " + strings.Join(verification.Unverified, ", ") + "."
}
return text
}
+161
View File
@@ -0,0 +1,161 @@
package webui
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
// TestReportPendingUpdateEmitsAndClearsReport is the webui counterpart of
// telegram's TestReportPendingUpdateSendsAndClearsReport: a dashboard-
// initiated install must produce a phase-2 report that reaches the
// dashboard, and must never be relayed twice (archie-core-nln7).
func TestReportPendingUpdateEmitsAndClearsReport(t *testing.T) {
s := newTestServer(t)
path := filepath.Join(t.TempDir(), "update-report.json")
report := releaseupdate.Report{
Channel: "webui",
Previous: map[string]string{releaseupdate.ComponentDaemon: "1.0.0"},
Installed: map[string]string{releaseupdate.ComponentDaemon: "1.1.0"},
HealthCheck: "passed",
}
if err := releaseupdate.WritePendingReport(path, report); err != nil {
t.Fatal(err)
}
s.UpdateReportPath = path
s.RunningVersions = func() map[string]string {
return map[string]string{releaseupdate.ComponentDaemon: "1.1.0"}
}
ctx := context.Background()
s.reportPendingUpdate(ctx)
evs, err := s.Store.EventsSince(ctx, 0, 10)
if err != nil {
t.Fatal(err)
}
if len(evs) != 1 {
t.Fatalf("events = %#v, want exactly one", evs)
}
if evs[0].Kind != events.KindUpdateReport {
t.Errorf("kind = %q, want %q", evs[0].Kind, events.KindUpdateReport)
}
confirmed, _ := evs[0].Data["confirmed"].([]any)
if len(confirmed) != 1 || confirmed[0] != releaseupdate.ComponentDaemon {
t.Errorf("confirmed = %#v, want [%q]", evs[0].Data["confirmed"], releaseupdate.ComponentDaemon)
}
if !strings.Contains(evs[0].Detail, "confirmed running") {
t.Errorf("Detail = %q, want it to say confirmed running", evs[0].Detail)
}
if _, found, err := releaseupdate.ReadPendingReport(path); err != nil || found {
t.Errorf("report still present after reportPendingUpdate: found=%v err=%v", found, err)
}
}
// TestReportPendingUpdateClearsUnreadableReport mirrors the telegram
// behaviour: a corrupt report must not jam every future boot.
func TestReportPendingUpdateClearsUnreadableReport(t *testing.T) {
s := newTestServer(t)
path := filepath.Join(t.TempDir(), "update-report.json")
if err := os.WriteFile(path, []byte("{not valid json"), 0o600); err != nil {
t.Fatal(err)
}
s.UpdateReportPath = path
s.reportPendingUpdate(context.Background())
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("corrupt report file still exists after reportPendingUpdate: err = %v", err)
}
}
func TestReportPendingUpdateNoFileIsNoop(t *testing.T) {
s := newTestServer(t)
s.UpdateReportPath = filepath.Join(t.TempDir(), "does-not-exist.json")
s.reportPendingUpdate(context.Background())
evs, err := s.Store.EventsSince(context.Background(), 0, 10)
if err != nil {
t.Fatal(err)
}
if len(evs) != 0 {
t.Fatalf("events = %#v, want none", evs)
}
}
func TestReportPendingUpdateDisabledWhenPathEmpty(t *testing.T) {
s := newTestServer(t)
s.reportPendingUpdate(context.Background())
evs, err := s.Store.EventsSince(context.Background(), 0, 10)
if err != nil {
t.Fatal(err)
}
if len(evs) != 0 {
t.Fatalf("events = %#v, want none", evs)
}
}
// TestSummarizeUpdateReportDistinguishesDriftFromConfirmed is the false-
// success regression the whole verification mechanism (c25799e,
// archie-core-3jag's sibling) exists to catch: a passed health probe alone
// must never be worded as a confirmed version.
func TestSummarizeUpdateReportDistinguishesDriftFromConfirmed(t *testing.T) {
report := releaseupdate.Report{
HealthCheck: "passed",
Previous: map[string]string{releaseupdate.ComponentDaemon: "1.0.0"},
Installed: map[string]string{releaseupdate.ComponentDaemon: "1.1.0"},
}
running := map[string]string{releaseupdate.ComponentDaemon: "1.0.0"}
verification := report.Verify(running)
got := summarizeUpdateReport(report, verification)
if !strings.Contains(got, "did NOT take effect") {
t.Errorf("summary = %q, want it to flag drift rather than claim success", got)
}
if strings.Contains(got, "confirmed running") {
t.Errorf("summary = %q, must not claim confirmed running when drift was detected", got)
}
}
// TestHandleChatUpdateInstallSetsReportPath is the regression proof: before
// this fix, the webui install handler passed
// releaseupdate.InstallMeta{Channel: "webui"} with no ReportPath, so the
// watchdog's write_report() (scripts/archie-update-watchdog) silently
// returned without ever writing a phase-2 report.
func TestHandleChatUpdateInstallSetsReportPath(t *testing.T) {
reportPath := filepath.Join(t.TempDir(), "update-report.json")
updates := &chatUpdateStub{snapshot: releaseupdate.Snapshot{
Components: []releaseupdate.Component{{ID: "gateway", Label: "Gateway", Installed: "1.0", Available: "1.1"}},
}}
sessions := gateway.NewSessionStoreMemory()
t.Cleanup(func() { _ = sessions.Close() })
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Updates: updates}, UpdateReportPath: reportPath}
body, err := json.Marshal(chatUpdateRequest{Snapshot: updates.snapshot})
if err != nil {
t.Fatal(err)
}
res := httptest.NewRecorder()
server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/update/install", bytes.NewReader(body)))
if res.Code != http.StatusOK || !updates.installed {
t.Fatalf("update install = %d, body = %s", res.Code, res.Body.String())
}
if updates.installedMeta.ReportPath != reportPath {
t.Errorf("ReportPath = %q, want %q", updates.installedMeta.ReportPath, reportPath)
}
}