From c7c1a75924eaa4aa99ce43ed6a135fb5b30a2299 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:39:51 +0100 Subject: [PATCH 01/20] feat(health): derive a ranked issue list from the node state Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/httpapi/healthissues.go | 110 ++++++++++++++ .../internal/httpapi/healthissues_test.go | 137 ++++++++++++++++++ dashboard/internal/nodeagent/liveness.go | 23 ++- dashboard/internal/nodeagent/liveness_test.go | 10 ++ 4 files changed, 275 insertions(+), 5 deletions(-) create mode 100644 dashboard/internal/httpapi/healthissues.go create mode 100644 dashboard/internal/httpapi/healthissues_test.go diff --git a/dashboard/internal/httpapi/healthissues.go b/dashboard/internal/httpapi/healthissues.go new file mode 100644 index 000000000..180f98d0d --- /dev/null +++ b/dashboard/internal/httpapi/healthissues.go @@ -0,0 +1,110 @@ +package httpapi + +import ( + "math" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/mqttclient" + "github.com/Developer-Simon/energy-node-dashboard/internal/nodeagent" + "github.com/Developer-Simon/energy-node-dashboard/internal/runtimecache" +) + +const ( + healthCPUHotC = 80.0 + healthRAMFullPct = 90.0 +) + +// healthIssue is one finding about the node state. Key is a catalog key the +// UI translates, Params fill its placeholders. +type healthIssue struct { + Key string `json:"key"` + Level string `json:"level"` // "warn" | "bad" + Params map[string]any `json:"params,omitempty"` +} + +// healthIssueInput is the node state the issue list is derived from. +type healthIssueInput struct { + MQTT *mqttclient.Status // nil = no MQTT provider, no issue + Cache runtimecache.Status + StorageErr error // error returned by storageProvider.Check + Telemetry *nodeagent.Telemetry // nil = no telemetry + Services []nodeagent.ServiceLiveness + Installed func(id string) bool // nil = every service installed + Window func(id string) time.Duration // nil = no grace + Uptime time.Duration +} + +// collectHealthIssues returns the issues of the node state, bad ones first, +// then the warnings in table order. It never returns nil. +func collectHealthIssues(in healthIssueInput) []healthIssue { + bad := []healthIssue{} + warn := []healthIssue{} + + if in.MQTT != nil && !in.MQTT.Connected { + bad = append(bad, healthIssue{Key: "mqtt_disconnected", Level: "bad"}) + } + if in.Cache.Degraded() { + warn = append(warn, healthIssue{Key: "cache_error", Level: "warn"}) + } + if in.StorageErr != nil { + warn = append(warn, healthIssue{ + Key: "storage_error", + Level: "warn", + Params: map[string]any{"reason": in.StorageErr.Error()}, + }) + } + if in.Telemetry != nil { + if in.Telemetry.UndervoltageNow { + warn = append(warn, healthIssue{Key: "undervoltage", Level: "warn"}) + } + if t := in.Telemetry.CPUTempC; t != nil && *t >= healthCPUHotC { + warn = append(warn, healthIssue{ + Key: "cpu_hot", + Level: "warn", + Params: map[string]any{"value": math.Round(*t*10) / 10}, + }) + } + if r := in.Telemetry.RAMUsedPct; r != nil && *r >= healthRAMFullPct { + warn = append(warn, healthIssue{ + Key: "ram_full", + Level: "warn", + Params: map[string]any{"value": int(math.Round(*r))}, + }) + } + } + for _, svc := range in.Services { + if svc.State == "active" { + continue + } + if in.Installed != nil && !in.Installed(svc.ID) { + continue + } + var window time.Duration + if in.Window != nil { + window = in.Window(svc.ID) + } + if in.Uptime < window { + continue + } + warn = append(warn, healthIssue{ + Key: "service_down", + Level: "warn", + Params: map[string]any{"service": svc.ID}, + }) + } + return append(bad, warn...) +} + +// healthLevelOf returns the worst level of the issues: "bad", "warn" or "ok". +func healthLevelOf(issues []healthIssue) string { + level := "ok" + for _, i := range issues { + if i.Level == "bad" { + return "bad" + } + if i.Level == "warn" { + level = "warn" + } + } + return level +} diff --git a/dashboard/internal/httpapi/healthissues_test.go b/dashboard/internal/httpapi/healthissues_test.go new file mode 100644 index 000000000..a78346695 --- /dev/null +++ b/dashboard/internal/httpapi/healthissues_test.go @@ -0,0 +1,137 @@ +package httpapi + +import ( + "errors" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/mqttclient" + "github.com/Developer-Simon/energy-node-dashboard/internal/nodeagent" + "github.com/Developer-Simon/energy-node-dashboard/internal/runtimecache" +) + +func f64(v float64) *float64 { return &v } + +func healthBase() healthIssueInput { + return healthIssueInput{ + MQTT: &mqttclient.Status{Connected: true}, + Telemetry: &nodeagent.Telemetry{CPUTempC: f64(50), RAMUsedPct: f64(40)}, + Services: []nodeagent.ServiceLiveness{{ID: "apsystems", State: "active"}}, + Uptime: time.Hour, + } +} + +func issueKeys(issues []healthIssue) []string { + keys := make([]string, 0, len(issues)) + for _, i := range issues { + keys = append(keys, i.Key) + } + return keys +} + +func TestHealthIssuesEmptyWhenAllFine(t *testing.T) { + issues := collectHealthIssues(healthBase()) + if issues == nil || len(issues) != 0 { + t.Fatalf("issues = %#v, want empty non-nil slice", issues) + } + if got := healthLevelOf(issues); got != "ok" { + t.Fatalf("level = %q, want ok", got) + } +} + +func TestHealthIssuesMQTTDisconnectedIsBad(t *testing.T) { + in := healthBase() + in.MQTT = &mqttclient.Status{Connected: false} + issues := collectHealthIssues(in) + if len(issues) != 1 || issues[0].Key != "mqtt_disconnected" || issues[0].Level != "bad" { + t.Fatalf("issues = %+v, want [mqtt_disconnected bad]", issues) + } + if got := healthLevelOf(issues); got != "bad" { + t.Fatalf("level = %q, want bad", got) + } +} + +func TestHealthIssuesOrderBadFirst(t *testing.T) { + in := healthBase() + in.MQTT = &mqttclient.Status{Connected: false} + in.Cache = runtimecache.Status{WriteError: "x"} + got := issueKeys(collectHealthIssues(in)) + want := []string{"mqtt_disconnected", "cache_error"} + if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("keys = %v, want %v", got, want) + } +} + +func TestHealthIssuesThresholds(t *testing.T) { + in := healthBase() + in.Telemetry = &nodeagent.Telemetry{CPUTempC: f64(79.9), RAMUsedPct: f64(89.9)} + if issues := collectHealthIssues(in); len(issues) != 0 { + t.Fatalf("below threshold: issues = %+v, want none", issues) + } + + in.Telemetry = &nodeagent.Telemetry{CPUTempC: f64(80.0), RAMUsedPct: f64(90.0)} + issues := collectHealthIssues(in) + if len(issues) != 2 { + t.Fatalf("at threshold: issues = %+v, want 2", issues) + } + if issues[0].Key != "cpu_hot" || issues[0].Level != "warn" || issues[0].Params["value"] != 80.0 { + t.Fatalf("cpu issue = %+v, want cpu_hot warn value 80", issues[0]) + } + if issues[1].Key != "ram_full" || issues[1].Level != "warn" || issues[1].Params["value"] != 90 { + t.Fatalf("ram issue = %+v, want ram_full warn value 90", issues[1]) + } +} + +func TestHealthIssuesUndervoltage(t *testing.T) { + in := healthBase() + in.Telemetry = &nodeagent.Telemetry{CPUTempC: f64(50), RAMUsedPct: f64(40), UndervoltageNow: true} + issues := collectHealthIssues(in) + if len(issues) != 1 || issues[0].Key != "undervoltage" || issues[0].Level != "warn" { + t.Fatalf("issues = %+v, want [undervoltage warn]", issues) + } +} + +func TestHealthIssuesStorageError(t *testing.T) { + in := healthBase() + in.StorageErr = errors.New("lsblk failed") + issues := collectHealthIssues(in) + if len(issues) != 1 || issues[0].Key != "storage_error" || issues[0].Params["reason"] != "lsblk failed" { + t.Fatalf("issues = %+v, want storage_error with reason", issues) + } +} + +func TestHealthIssuesSkipsUninstalledService(t *testing.T) { + in := healthBase() + in.Services = []nodeagent.ServiceLiveness{{ID: "tuya", State: "configured"}} + in.Installed = func(id string) bool { return false } + if issues := collectHealthIssues(in); len(issues) != 0 { + t.Fatalf("issues = %+v, want none", issues) + } +} + +func TestHealthIssuesServiceGrace(t *testing.T) { + in := healthBase() + in.Services = []nodeagent.ServiceLiveness{{ID: "tuya", State: "configured"}} + in.Installed = func(id string) bool { return true } + in.Window = func(id string) time.Duration { return 120 * time.Second } + + in.Uptime = 60 * time.Second + if issues := collectHealthIssues(in); len(issues) != 0 { + t.Fatalf("within grace: issues = %+v, want none", issues) + } + + in.Uptime = 200 * time.Second + issues := collectHealthIssues(in) + if len(issues) != 1 || issues[0].Key != "service_down" || issues[0].Params["service"] != "tuya" { + t.Fatalf("after grace: issues = %+v, want service_down tuya", issues) + } +} + +func TestHealthIssuesActiveServiceIsFine(t *testing.T) { + in := healthBase() + in.Services = []nodeagent.ServiceLiveness{{ID: "tuya", State: "active"}} + in.Window = func(id string) time.Duration { return 120 * time.Second } + if issues := collectHealthIssues(in); len(issues) != 0 { + t.Fatalf("issues = %+v, want none", issues) + } +} diff --git a/dashboard/internal/nodeagent/liveness.go b/dashboard/internal/nodeagent/liveness.go index 0b5f78bf4..fc6181fe8 100644 --- a/dashboard/internal/nodeagent/liveness.go +++ b/dashboard/internal/nodeagent/liveness.go @@ -127,17 +127,30 @@ func (a *Agent) ServiceLiveness(now time.Time) []ServiceLiveness { return out } -func (a *Agent) fresh(id string, st *serviceState, now time.Time) bool { - if st.lastUpdate == 0 { - return false - } +// ServiceWindow is how long a service's last settings/status stays fresh: +// its diagnostic poll interval plus a slack. Without poll settings the poll +// interval counts as 60 s. +func (a *Agent) ServiceWindow(id string) time.Duration { + a.live.mu.RLock() + defer a.live.mu.RUnlock() + return a.serviceWindow(id) +} + +func (a *Agent) serviceWindow(id string) time.Duration { p := a.live.poll[id] window := p.PollIntervalS * p.DiagnosticPollMultiplier if window <= 0 { window = 60 } window += livenessSlackSeconds - return now.Unix()-st.lastUpdate <= int64(window) + return time.Duration(window * float64(time.Second)) +} + +func (a *Agent) fresh(id string, st *serviceState, now time.Time) bool { + if st.lastUpdate == 0 { + return false + } + return now.Unix()-st.lastUpdate <= int64(a.serviceWindow(id)/time.Second) } // ServiceStatus returns the last settings/status a service published. diff --git a/dashboard/internal/nodeagent/liveness_test.go b/dashboard/internal/nodeagent/liveness_test.go index 83a6d1ce3..715354f2c 100644 --- a/dashboard/internal/nodeagent/liveness_test.go +++ b/dashboard/internal/nodeagent/liveness_test.go @@ -123,3 +123,13 @@ func TestObserveLivenessReadsPollRound(t *testing.T) { t.Fatalf("ServiceRoundS without field = %v, %v; want false", d, ok) } } + +func TestServiceWindowUsesPollSettings(t *testing.T) { + a := livenessAgent(t, time.Unix(10_000, 0)) + if got := a.ServiceWindow("apsystems"); got != 660*time.Second { + t.Fatalf("apsystems window = %v, want 660s", got) + } + if got := a.ServiceWindow("unknown"); got != 120*time.Second { + t.Fatalf("unknown window = %v, want 120s", got) + } +} From f290fb2d244f9a46e5faa58c8d6c282e31d60447 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:41:30 +0100 Subject: [PATCH 02/20] feat(health): report issues and level, count only installed services Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 7 ++-- dashboard/internal/httpapi/httpapi.go | 39 ++++++++++++------ dashboard/internal/httpapi/httpapi_test.go | 47 +++++++++++++++++++++- 3 files changed, 76 insertions(+), 17 deletions(-) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 313f47563..7f16cbbad 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -1565,9 +1565,10 @@ func main() { "tailscale": cfg.ServiceInstalled("tailscale"), "tuya": cfg.ServiceInstalled("tuya"), }, - MQTTBase: mqttBase, - NodeAgent: nodeAgent, - NodeSimulation: nodeSimPublisher, + ServiceInstalled: cfg.ServiceInstalled, + MQTTBase: mqttBase, + NodeAgent: nodeAgent, + NodeSimulation: nodeSimPublisher, // Die API zeigt alle passenden Sensoren, ungefiltert, damit der // MQTT-Tab sie abwaehlen kann. EnergySensorOptions: func() []energydiscovery.OptionalSensor { diff --git a/dashboard/internal/httpapi/httpapi.go b/dashboard/internal/httpapi/httpapi.go index ca6600cfb..007f78199 100644 --- a/dashboard/internal/httpapi/httpapi.go +++ b/dashboard/internal/httpapi/httpapi.go @@ -215,6 +215,10 @@ type RouterDependencies struct { // tuya. main.go fuellt sie ueber Config.ServiceInstalled; nil heisst // hier wie dort "alles an". InstalledServices map[string]bool + // ServiceInstalled ist dieselbe Auswahl als Funktion, fuer den Health- + // Befund service_down: nicht installierte Dienste melden nichts. main.go + // fuellt sie ueber Config.ServiceInstalled; nil heisst "alles installiert". + ServiceInstalled func(id string) bool // InstallerStateDir ist das Zustandsverzeichnis von Installer und Updater // (installed-manifest.json, selection.json, changelog.json), aus dem die // Versionsseite liest. Leer heisst versions.DefaultStateDir. @@ -353,7 +357,7 @@ func NewRouterWithDependencies(reg *registry.Registry, configs *config.Manager, if now == nil { now = func() time.Time { return time.Now().UTC() } } - g.HandleFunc("/api/v1/health", handleHealth(cache, storageProvider, dependencies.MQTT, dependencies.NodeAgent, dependencies.StartedAt, dependencies.Version, now)) + g.HandleFunc("/api/v1/health", handleHealth(cache, storageProvider, dependencies.MQTT, dependencies.NodeAgent, dependencies.ServiceInstalled, dependencies.StartedAt, dependencies.Version, now)) g.HandleFunc("/api/v1/runtime-cache", handleRuntimeCache(cache)) g.Handle("/static/", webui.Static()) g.Handle("/i18n/", webui.I18nScript()) @@ -1381,7 +1385,11 @@ func handleShellyPresets(store *shellypresets.Store) http.HandlerFunc { } type healthResponse struct { - Status string `json:"status"` + Status string `json:"status"` + // Level ist der schlimmste Befund: "ok", "warn" oder "bad". + Level string `json:"level"` + // Issues listet die Befunde, schlimme zuerst. Immer ein Array. + Issues []healthIssue `json:"issues"` RuntimeCache runtimecache.Status `json:"runtime_cache"` Version string `json:"version"` UptimeSeconds *int64 `json:"uptime_seconds,omitempty"` @@ -1405,29 +1413,25 @@ type nodeStatus struct { } // nodeAgent is threaded through for Task 6/7 (healthResponse.Node). -func handleHealth(cache runtimecache.StatusProvider, storageProvider storagehealth.Provider, mqttStatus mqttclient.StatusProvider, nodeAgent *nodeagent.Agent, startedAt time.Time, version string, now func() time.Time) http.HandlerFunc { +func handleHealth(cache runtimecache.StatusProvider, storageProvider storagehealth.Provider, mqttStatus mqttclient.StatusProvider, nodeAgent *nodeagent.Agent, installed func(string) bool, startedAt time.Time, version string, now func() time.Time) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { methodNotAllowed(w) return } status := runtimecache.Status{} - result := "ok" if cache != nil { status = cache.Status() - if status.Degraded() { - result = "degraded" - } } currentTime := now() if version == "" { version = "dev" } response := healthResponse{ - Status: result, RuntimeCache: status, Version: version, } + issueInput := healthIssueInput{Cache: status, Installed: installed} if !startedAt.IsZero() { uptime := currentTime.Sub(startedAt) if uptime < 0 { @@ -1435,20 +1439,20 @@ func handleHealth(cache runtimecache.StatusProvider, storageProvider storageheal } uptimeSeconds := int64(uptime / time.Second) response.UptimeSeconds = &uptimeSeconds + issueInput.Uptime = uptime } if mqttStatus != nil { mqtt := mqttStatus.Status() response.MQTT = &mqtt - if !mqtt.Connected { - result = "degraded" - } + issueInput.MQTT = &mqtt } + var storageErr error storage := map[string]any{"available": false, "reason": "Speichermedium-Diagnose ist nicht verfügbar"} if storageProvider != nil { report, err := storageProvider.Check(r.Context()) if err != nil { storage["reason"] = err.Error() - result = "degraded" + storageErr = err } else { storage = map[string]any{ "available": report.Available, @@ -1462,7 +1466,6 @@ func handleHealth(cache runtimecache.StatusProvider, storageProvider storageheal } } } - response.Status = result response.Storage = storage response.Features = map[string]int{"history_exchange": exchangeProtocolVersion} if nodeAgent != nil { @@ -1471,6 +1474,16 @@ func handleHealth(cache runtimecache.StatusProvider, storageProvider storageheal ns.Telemetry = &tel } response.Node = ns + issueInput.Telemetry = ns.Telemetry + issueInput.Services = ns.Services + issueInput.Window = nodeAgent.ServiceWindow + } + issueInput.StorageErr = storageErr + response.Issues = collectHealthIssues(issueInput) + response.Level = healthLevelOf(response.Issues) + response.Status = "ok" + if len(response.Issues) > 0 { + response.Status = "degraded" } writeJSON(w, response) } diff --git a/dashboard/internal/httpapi/httpapi_test.go b/dashboard/internal/httpapi/httpapi_test.go index 97027942c..ecc7ae15b 100644 --- a/dashboard/internal/httpapi/httpapi_test.go +++ b/dashboard/internal/httpapi/httpapi_test.go @@ -547,7 +547,7 @@ func TestHealthVersionDefaultsToDev(t *testing.T) { func TestHealthReportsServiceLiveness(t *testing.T) { a := nodeagent.New(nodeagent.Options{NodeID: "energy_node"}) a.SetServiceCatalog([]string{"apsystems"}, map[string]appconfig.ServicePoll{"apsystems": {PollIntervalS: 60, DiagnosticPollMultiplier: 10}}) - h := handleHealth(nil, nil, nil, a, time.Now(), "test", time.Now) + h := handleHealth(nil, nil, nil, a, nil, time.Now(), "test", time.Now) rec := httptest.NewRecorder() h(rec, httptest.NewRequest(http.MethodGet, "/api/v1/health", nil)) var body map[string]any @@ -2792,3 +2792,48 @@ func TestEntityCommandObserverSkippedWhenPublishFails(t *testing.T) { t.Fatalf("observer calls after failed publish = %d, want 0", calls) } } + +func TestHealthCarriesIssuesAndLevel(t *testing.T) { + disconnected := fakeMQTTStatusProvider{status: mqttclient.Status{Connected: false}} + h := handleHealth(nil, nil, disconnected, nil, nil, time.Now(), "test", time.Now) + rec := httptest.NewRecorder() + h(rec, httptest.NewRequest(http.MethodGet, "/api/v1/health", nil)) + var body struct { + Status string `json:"status"` + Level string `json:"level"` + Issues []struct { + Key string `json:"key"` + } `json:"issues"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode health body: %v", err) + } + if body.Level != "bad" || body.Status != "degraded" { + t.Fatalf("level=%q status=%q, want bad/degraded: %s", body.Level, body.Status, rec.Body) + } + if len(body.Issues) == 0 || body.Issues[0].Key != "mqtt_disconnected" { + t.Fatalf("issues = %+v, want mqtt_disconnected first", body.Issues) + } + + connected := fakeMQTTStatusProvider{status: mqttclient.Status{Connected: true}} + h = handleHealth(nil, nil, connected, nil, nil, time.Now(), "test", time.Now) + rec = httptest.NewRecorder() + h(rec, httptest.NewRequest(http.MethodGet, "/api/v1/health", nil)) + var raw map[string]json.RawMessage + if err := json.Unmarshal(rec.Body.Bytes(), &raw); err != nil { + t.Fatalf("decode health body: %v", err) + } + var ok struct { + Status string `json:"status"` + Level string `json:"level"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &ok); err != nil { + t.Fatal(err) + } + if ok.Level != "ok" || ok.Status != "ok" { + t.Fatalf("level=%q status=%q, want ok/ok: %s", ok.Level, ok.Status, rec.Body) + } + if string(raw["issues"]) != "[]" { + t.Fatalf("issues = %s, want []", raw["issues"]) + } +} From b6538e8a632925dfad619fb4e752302bd6e89e05 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:42:21 +0100 Subject: [PATCH 03/20] test(demo): keep bridges without device files alive in the fake broker Co-Authored-By: Claude Sonnet 5.5 --- demo/fakes/minibroker.py | 35 ++++++++++++++++++++++----- demo/fakes/test_minibroker_control.py | 10 ++++++++ demo/lib/env.sh | 1 + 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/demo/fakes/minibroker.py b/demo/fakes/minibroker.py index 048878c79..5aaf21bc7 100644 --- a/demo/fakes/minibroker.py +++ b/demo/fakes/minibroker.py @@ -27,7 +27,8 @@ schalten. python3 minibroker.py [PORT] [FIXTURE.json] [--simulate] - [--service-status DEVICES_DIR] [--reject-config NAME ...] + [--service-status DEVICES_DIR] [--alive-service ID ...] + [--reject-config NAME ...] [--login USER PASSWORD] [--control-port PORT] PORT Standard 18883. @@ -51,6 +52,11 @@ So zeigt die Konfigurationsseite ihren Dienststatus, auch nach einem Speichern (erst Ausstehend, dann Angewendet). Ein Herzschlag alle SERVICE_HEARTBEAT Sekunden haelt die Dienste "active". +--alive-service ID + Spielt einen Dienst ohne Geraetedatei (z. B. tuya, trucki): jeder + Herzschlag meldet retained outstation//status/online "1" und + outstation//settings/status mit runtime_status "ok". Nur + zusammen mit --service-status wirksam. Mehrfach angebbar. --reject-config NAME Meldet die Konfiguration NAME (z. B. battery_soc_devices) als abgelehnt: runtime_status "rejected", applied_revision bleibt die @@ -689,13 +695,14 @@ def service_id_for_config(name): return None -def service_status_scan(devices_dir, state, beat): +def service_status_scan(devices_dir, state, beat, alive=()): # Ein Durchlauf von service_status_loop. Ein Dienst liest seine Datei, # meldet das Ergebnis retained auf settings/status und nennt dabei die # Pruefsumme der Datei. Genau diese vergleicht die Konfigurationsseite mit # der Datei, die sie geschrieben hat - deshalb hier die echte SHA-256 der # Bytes auf der Platte. Der Modus kommt aus dem Zustand (accept, reject, # silent); silent meldet weder Status noch Herzschlag. + with_file = set() for path in sorted(Path(devices_dir).glob("*.json")): name = path.stem if name.endswith(".schema"): @@ -703,6 +710,7 @@ def service_status_scan(devices_dir, state, beat): service_id = service_id_for_config(name) if not service_id: continue + with_file.add(service_id) try: revision = hashlib.sha256(path.read_bytes()).hexdigest() except OSError: @@ -728,14 +736,26 @@ def service_status_scan(devices_dir, state, beat): broadcast(state.messages, state.connections, f"{base}/status/online", b"1", True) broadcast(state.messages, state.connections, f"{base}/settings/status", json.dumps(status).encode("utf-8"), True) + if not beat: + return + # Dienste ohne Geraetedatei halten sich nur per Herzschlag aktiv. Hat ein + # Dienst eine Datei, meldet der Scan oben seinen Status schon. + for service_id in alive: + if service_id in with_file: + continue + base = f"outstation/{service_id}" + status = {"last_update": int(time.time()), "runtime_status": "ok", "error": ""} + broadcast(state.messages, state.connections, f"{base}/status/online", b"1", True) + broadcast(state.messages, state.connections, f"{base}/settings/status", + json.dumps(status).encode("utf-8"), True) -def service_status_loop(devices_dir, state): +def service_status_loop(devices_dir, state, alive=()): last_beat = 0.0 while True: now = time.time() beat = now - last_beat >= SERVICE_HEARTBEAT - service_status_scan(devices_dir, state, beat) + service_status_scan(devices_dir, state, beat, alive) if beat: last_beat = now time.sleep(SERVICE_SCAN_INTERVAL) @@ -817,7 +837,7 @@ def _respond(self): def parse_args(argv): - opts = {"simulate": False, "service_status": None, "rejected": set(), "login": None, + opts = {"simulate": False, "service_status": None, "alive": [], "rejected": set(), "login": None, "control_port": None, "positional": []} i = 0 while i < len(argv): @@ -830,6 +850,9 @@ def parse_args(argv): elif arg == "--service-status": i += 1 opts["service_status"] = argv[i] + elif arg == "--alive-service": + i += 1 + opts["alive"].append(argv[i]) elif arg == "--reject-config": i += 1 opts["rejected"].add(argv[i]) @@ -853,7 +876,7 @@ def main(): threading.Thread(target=simulate_loop, args=(state,), daemon=True).start() if opts["service_status"]: threading.Thread(target=service_status_loop, - args=(opts["service_status"], state), + args=(opts["service_status"], state, opts["alive"]), daemon=True).start() if opts["control_port"] is not None: control = make_control_server(state, opts["control_port"]) diff --git a/demo/fakes/test_minibroker_control.py b/demo/fakes/test_minibroker_control.py index f216ade3a..562924b0d 100644 --- a/demo/fakes/test_minibroker_control.py +++ b/demo/fakes/test_minibroker_control.py @@ -306,3 +306,13 @@ def test_control_pv_throttle_and_reset(control): assert state.pv_throttle is True call(base, "POST", "/reset", {}) assert state.pv_throttle is False + + +def test_alive_service_is_published(tmp_path): + state = make_state() + minibroker.service_status_scan(str(tmp_path), state, True, alive=["tuya"]) + assert state.messages["outstation/tuya/status/online"] == b"1" + status = settings_status(state, "tuya") + assert status["runtime_status"] == "ok" + assert status["error"] == "" + assert isinstance(status["last_update"], int) diff --git a/demo/lib/env.sh b/demo/lib/env.sh index 0513a4025..8ab22b4d2 100644 --- a/demo/lib/env.sh +++ b/demo/lib/env.sh @@ -316,6 +316,7 @@ env_build_dashboard() { # Startet den Fake-MQTT-Broker (Log: $WORK/broker.log). env_start_broker() { local args=("$MQTT_PORT" "$FIXTURE" "--service-status" "$WORK/devices") + args+=("--alive-service" apsystems "--alive-service" trucki "--alive-service" tuya) [[ "${SIMULATE:-0}" == "1" ]] && args+=("--simulate") [[ -n "${MQTT_BROKER_PASSWORD:-}" ]] && args+=("--login" "$MQTT_USERNAME" "$MQTT_BROKER_PASSWORD") [[ -n "${BROKER_CONTROL_PORT:-}" ]] && args+=("--control-port" "$BROKER_CONTROL_PORT") From 4a944fbe4be6caca6af217a5e99e56b6076fb6a6 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:43:54 +0100 Subject: [PATCH 04/20] refactor(settings): retire status_bar_items, the status popover shows every value Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/onboarding/seed.go | 8 +-- dashboard/internal/onboarding/seed_test.go | 20 ++++++ dashboard/internal/onboarding/steps.go | 3 +- dashboard/internal/onboarding/steps_test.go | 7 ++ dashboard/internal/settings/settings.go | 5 -- .../internal/settings/settings.schema.json | 9 +-- dashboard/internal/settings/settings_test.go | 64 +++++-------------- dashboard/internal/webui/catalogs/de.json | 2 +- dashboard/internal/webui/catalogs/en.json | 2 +- dashboard/internal/webui/templates/base.html | 2 +- dashboard/internal/webui/webui.go | 3 - dashboard/internal/webui/webui_test.go | 2 +- 12 files changed, 51 insertions(+), 76 deletions(-) diff --git a/dashboard/internal/onboarding/seed.go b/dashboard/internal/onboarding/seed.go index 680be9dd1..6abc0ddd8 100644 --- a/dashboard/internal/onboarding/seed.go +++ b/dashboard/internal/onboarding/seed.go @@ -37,7 +37,6 @@ type seedFile struct { Theme *string `json:"theme"` Title *string `json:"title"` Subtitle *string `json:"subtitle"` - StatusBarItems *[]string `json:"status_bar_items"` ShowRuntimeStatus *bool `json:"show_runtime_status"` WidePanels *[]string `json:"wide_panels"` UpdateCheck *bool `json:"update_check"` @@ -145,7 +144,7 @@ func templateRoles(template string) ([]string, error) { // applySeedSettings setzt die Einstellungen, die die Vorgaben nennen. Gespeichert // wird nur, wenn mindestens eine davon gesetzt ist. func applySeedSettings(seed seedFile, st *settings.Store) error { - if seed.Theme == nil && seed.Title == nil && seed.Subtitle == nil && seed.StatusBarItems == nil && + if seed.Theme == nil && seed.Title == nil && seed.Subtitle == nil && seed.ShowRuntimeStatus == nil && seed.WidePanels == nil && seed.UpdateCheck == nil { return nil } @@ -162,9 +161,6 @@ func applySeedSettings(seed seedFile, st *settings.Store) error { if seed.Subtitle != nil { set.DashboardSubtitle = *seed.Subtitle } - if seed.StatusBarItems != nil { - set.StatusBarItems = slices.Clone(*seed.StatusBarItems) - } if seed.ShowRuntimeStatus != nil { set.ShowRuntimeStatus = *seed.ShowRuntimeStatus } @@ -238,7 +234,7 @@ func seedSets(seed seedFile, id string) bool { case "title": return nonEmpty(seed.Title) || nonEmpty(seed.Subtitle) case "statusbar": - return seed.StatusBarItems != nil || seed.ShowRuntimeStatus != nil + return seed.ShowRuntimeStatus != nil case "tabwidth": return seed.WidePanels != nil case "updates": diff --git a/dashboard/internal/onboarding/seed_test.go b/dashboard/internal/onboarding/seed_test.go index e5159e3b9..9c6d1a88d 100644 --- a/dashboard/internal/onboarding/seed_test.go +++ b/dashboard/internal/onboarding/seed_test.go @@ -5,6 +5,7 @@ import ( "log/slog" "os" "path/filepath" + "reflect" "slices" "strings" "testing" @@ -212,6 +213,25 @@ func TestSeedMarksStepsInstaller(t *testing.T) { } } +func TestSeedIgnoresStatusBarItems(t *testing.T) { + f := newSeedFixture(t) + before, err := f.settings.LoadSettings() + if err != nil { + t.Fatal(err) + } + f.write(t, `{"version":1,"status_bar_items":["mqtt"]}`) + if err := f.apply(t); err != nil { + t.Fatalf("seed with retired status_bar_items: %v", err) + } + after, err := f.settings.LoadSettings() + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(before, after) { + t.Fatalf("retired status_bar_items changed settings: before %+v, after %+v", before, after) + } +} + func TestSeedLaterMarksStepLater(t *testing.T) { f := newSeedFixture(t) f.write(t, `{"version":1,"later":["theme","guest","nicht_da"]}`) diff --git a/dashboard/internal/onboarding/steps.go b/dashboard/internal/onboarding/steps.go index ab7191d68..09b62233c 100644 --- a/dashboard/internal/onboarding/steps.go +++ b/dashboard/internal/onboarding/steps.go @@ -87,8 +87,7 @@ func Detect(in DetectInput) map[string]StepState { mark("title", strings.TrimSpace(set.DashboardTitle) != "" || strings.TrimSpace(set.DashboardSubtitle) != "" || set.DashboardTitleHidden || set.DashboardSubtitleHidden) - mark("statusbar", !slices.Equal(set.StatusBarItems, defaults.StatusBarItems) || - set.ShowRuntimeStatus != defaults.ShowRuntimeStatus) + mark("statusbar", set.ShowRuntimeStatus != defaults.ShowRuntimeStatus) mark("tabwidth", !slices.Equal(set.WidePanels, defaults.WidePanels)) mark("updates", set.UpdateCheckDisabled) mark("roles", hasAssignedRole(in.Energy)) diff --git a/dashboard/internal/onboarding/steps_test.go b/dashboard/internal/onboarding/steps_test.go index ab95d58ac..c5f20cf65 100644 --- a/dashboard/internal/onboarding/steps_test.go +++ b/dashboard/internal/onboarding/steps_test.go @@ -187,6 +187,13 @@ func TestDetectRuntimeStatusOffIsDone(t *testing.T) { } } +func TestDetectRuntimeStatusDefaultIsOpen(t *testing.T) { + in := defaultInput() + if got := Detect(in); got["statusbar"] == StepDone { + t.Fatalf("statusbar = %q with the default (shown), want open", got["statusbar"]) + } +} + func TestDetectPartiallyConfiguredInstall(t *testing.T) { in := defaultInput() in.Settings.Theme = settings.ThemeSignalgelb diff --git a/dashboard/internal/settings/settings.go b/dashboard/internal/settings/settings.go index 489e18f0e..d74cb1791 100644 --- a/dashboard/internal/settings/settings.go +++ b/dashboard/internal/settings/settings.go @@ -70,7 +70,6 @@ type Settings struct { ShowDiagnosticEntitiesOnTile bool `json:"show_diagnostic_entities_on_tile"` LiveUpdateIntervalSeconds int `json:"live_update_interval_seconds"` WidePanels []string `json:"wide_panels"` - StatusBarItems []string `json:"status_bar_items"` // Verlaufs-Historie. Die Messwerte selbst liegen ausschliesslich in der // IndexedDB des Browsers - hier steht nur, wie aufgezeichnet und wie @@ -653,7 +652,6 @@ func Default() Settings { NumberFormat: numfmt.FormatAuto, NumberGrouping: numfmt.GroupingMatch, ShowConfigEntitiesOnTile: false, ShowDiagnosticEntitiesOnTile: false, LiveUpdateIntervalSeconds: 3, WidePanels: []string{"overview", "devices", "history", "layout", "settings"}, - StatusBarItems: []string{"mqtt", "storage", "uptime", "version"}, HistorySampleIntervalSeconds: 10, HistoryRetentionMode: HistoryRetentionModeTime, HistoryRetentionHours: 6, @@ -2115,9 +2113,6 @@ func normalizeSettings(value Settings) Settings { if value.WidePanels == nil { value.WidePanels = Default().WidePanels } - if value.StatusBarItems == nil { - value.StatusBarItems = Default().StatusBarItems - } if value.HistorySampleIntervalSeconds == 0 { value.HistorySampleIntervalSeconds = Default().HistorySampleIntervalSeconds } diff --git a/dashboard/internal/settings/settings.schema.json b/dashboard/internal/settings/settings.schema.json index 4d8632b72..f7dbcfa28 100644 --- a/dashboard/internal/settings/settings.schema.json +++ b/dashboard/internal/settings/settings.schema.json @@ -3,7 +3,7 @@ "description": "Operational settings for the Energy Node dashboard.", "type": "object", "additionalProperties": false, - "required": ["health_score_threshold", "sweep_interval_seconds", "show_runtime_status", "device_view_mode", "theme", "number_format", "number_grouping", "show_config_entities_on_tile", "show_diagnostic_entities_on_tile", "live_update_interval_seconds", "wide_panels", "status_bar_items", "history_sample_interval_seconds", "history_retention_mode", "history_retention_hours", "history_budget_mb", "history_raw_window_hours", "history_minute_window_days", "history_extra_entities", "history_exchange_disabled", "history_views", "energy_stats_recording", "changelog_history", "update_check_disabled", "language_switch_hidden", "dashboard_title", "dashboard_subtitle", "dashboard_title_hidden", "dashboard_subtitle_hidden", "performance_target_pct", "automation_patterns_disabled", "automation_habits_disabled", "automation_reliability_disabled", "automation_energy_disabled", "learning_season_year_disabled", "learning_excluded_devices", "learning_profile_days", "learning_acknowledged", "learning_level", "learning_minutes_mode", "learning_minutes_location", "learning_minutes_days", "learning_ha_reconcile_disabled", "automation_outdoor_entity"], + "required": ["health_score_threshold", "sweep_interval_seconds", "show_runtime_status", "device_view_mode", "theme", "number_format", "number_grouping", "show_config_entities_on_tile", "show_diagnostic_entities_on_tile", "live_update_interval_seconds", "wide_panels", "history_sample_interval_seconds", "history_retention_mode", "history_retention_hours", "history_budget_mb", "history_raw_window_hours", "history_minute_window_days", "history_extra_entities", "history_exchange_disabled", "history_views", "energy_stats_recording", "changelog_history", "update_check_disabled", "language_switch_hidden", "dashboard_title", "dashboard_subtitle", "dashboard_title_hidden", "dashboard_subtitle_hidden", "performance_target_pct", "automation_patterns_disabled", "automation_habits_disabled", "automation_reliability_disabled", "automation_energy_disabled", "learning_season_year_disabled", "learning_excluded_devices", "learning_profile_days", "learning_acknowledged", "learning_level", "learning_minutes_mode", "learning_minutes_location", "learning_minutes_days", "learning_ha_reconcile_disabled", "automation_outdoor_entity"], "properties": { "health_score_threshold": { "type": "integer", @@ -82,13 +82,6 @@ "title": "Tabs ohne Breitendeckelung", "description": "Tabs, die die volle Fensterbreite nutzen duerfen statt der 1180px-Lesebreite." }, - "status_bar_items": { - "type": "array", - "items": {"type": "string", "enum": ["mqtt", "cache", "storage", "uptime", "version", "cpu_temp", "cpu_load", "ram", "undervoltage"]}, - "default": ["mqtt", "storage", "uptime", "version"], - "title": "Angaben im Systemstatus", - "description": "Welche Angaben die Statuszeile unterhalb der Kopfzeile zeigt, wenn der globale Systemstatus aktiv ist." - }, "history_sample_interval_seconds": { "type": "integer", "minimum": 5, diff --git a/dashboard/internal/settings/settings_test.go b/dashboard/internal/settings/settings_test.go index 46e73be10..dc02af8c1 100644 --- a/dashboard/internal/settings/settings_test.go +++ b/dashboard/internal/settings/settings_test.go @@ -1167,73 +1167,41 @@ func TestSettingsRejectsUnknownWidePanel(t *testing.T) { } } -// TestSettingsStatusBarItemsDefault: die Vorgabe zeigt MQTT, Storage, -// Uptime und die Dashboard-Version, aber nicht den Cache-Status. -func TestSettingsStatusBarItemsDefault(t *testing.T) { - value, err := NewStore(t.TempDir()).LoadSettings() - if err != nil { - t.Fatal(err) - } - want := []string{"mqtt", "storage", "uptime", "version"} - if !reflect.DeepEqual(value.StatusBarItems, want) { - t.Fatalf("StatusBarItems = %v, want %v", value.StatusBarItems, want) - } -} - -func TestSettingsStatusBarItemsAcceptsEmptySelection(t *testing.T) { +// TestSettingsIgnoresRetiredStatusBarItems: die Einstellung status_bar_items +// ist entfallen. Alte settings.json mit dem Schluessel laden ohne Fehler und +// schreiben ihn beim naechsten Speichern nicht mehr. +func TestSettingsIgnoresRetiredStatusBarItems(t *testing.T) { dir := t.TempDir() - store := NewStore(dir) - value, err := store.LoadSettings() + raw, err := json.Marshal(Default()) if err != nil { t.Fatal(err) } - value.StatusBarItems = []string{} - if err := store.SaveSettings(value); err != nil { + var document map[string]any + if err := json.Unmarshal(raw, &document); err != nil { t.Fatal(err) } - reloaded, err := NewStore(dir).LoadSettings() + document["status_bar_items"] = []string{"mqtt"} + legacy, err := json.Marshal(document) if err != nil { t.Fatal(err) } - if len(reloaded.StatusBarItems) != 0 { - t.Fatalf("StatusBarItems = %v, want leer", reloaded.StatusBarItems) - } -} - -func TestSettingsRejectsUnknownStatusBarItem(t *testing.T) { - store := NewStore(t.TempDir()) - value, err := store.LoadSettings() - if err != nil { + if err := os.WriteFile(filepath.Join(dir, "settings.json"), legacy, 0600); err != nil { t.Fatal(err) } - value.StatusBarItems = []string{"gibt-es-nicht"} - if err := store.SaveSettings(value); err == nil { - t.Fatal("unbekannter Statuszeilen-Schluessel wurde angenommen") - } -} - -func TestSettingsAcceptsTelemetryStatusBarItems(t *testing.T) { - store := NewStore(t.TempDir()) + store := NewStore(dir) value, err := store.LoadSettings() if err != nil { - t.Fatal(err) + t.Fatalf("LoadSettings with retired status_bar_items: %v", err) } - value.StatusBarItems = []string{"cpu_temp", "ram", "undervoltage"} if err := store.SaveSettings(value); err != nil { - t.Fatalf("SaveSettings failed for telemetry status bar items: %v", err) + t.Fatal(err) } - reloaded, err := store.LoadSettings() + written, err := os.ReadFile(filepath.Join(dir, "settings.json")) if err != nil { t.Fatal(err) } - if len(reloaded.StatusBarItems) != 3 { - t.Fatalf("StatusBarItems = %v, want 3 items", reloaded.StatusBarItems) - } - expected := map[string]bool{"cpu_temp": true, "ram": true, "undervoltage": true} - for _, item := range reloaded.StatusBarItems { - if !expected[item] { - t.Fatalf("unexpected StatusBarItem %q", item) - } + if strings.Contains(string(written), "status_bar_items") { + t.Fatalf("saved settings still contain status_bar_items: %s", written) } } diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 00dc0facd..c81433806 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -4279,7 +4279,7 @@ "onboarding.setup.roles.title": "Energierollen zuordnen", "onboarding.setup.services.sub": "Welche Dienste installiert sind", "onboarding.setup.services.title": "Dienste", - "onboarding.setup.statusbar.text": "Die Leiste oben zeigt gerade MQTT, Speicher, Laufzeit und Version. Wähle, ob und was du davon dauerhaft sehen möchtest.", + "onboarding.setup.statusbar.text": "Oben rechts zeigt ein Chip, ob das System läuft. Ein Klick öffnet alle Werte. Wähle, ob er sichtbar sein soll.", "onboarding.setup.statusbar.title": "Systemstatus", "onboarding.setup.tabwidth.text": "Auf großen Bildschirmen dürfen Tabs die volle Fensterbreite nutzen. Mit Alle gilt das für jeden Tab.", "onboarding.setup.tabwidth.title": "Tab-Breite", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 8c264f67f..99d614de6 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -4279,7 +4279,7 @@ "onboarding.setup.roles.title": "Assign energy roles", "onboarding.setup.services.sub": "Which services are installed", "onboarding.setup.services.title": "Services", - "onboarding.setup.statusbar.text": "The bar at the top currently shows MQTT, storage, uptime and version. Choose whether and what you want to see there permanently.", + "onboarding.setup.statusbar.text": "A chip at the top right shows whether the system is running. A click opens all values. Choose whether it is shown.", "onboarding.setup.statusbar.title": "System status", "onboarding.setup.tabwidth.text": "On large screens, tabs may use the full window width. With All, this applies to every tab.", "onboarding.setup.tabwidth.title": "Tab width", diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 80729df2f..407f3360c 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -114,7 +114,7 @@

{{.Masthead. -
+
{{t "status.title"}} diff --git a/dashboard/internal/webui/webui.go b/dashboard/internal/webui/webui.go index 0dbffc0b3..1daff5d7c 100644 --- a/dashboard/internal/webui/webui.go +++ b/dashboard/internal/webui/webui.go @@ -974,7 +974,6 @@ func OverviewWithOnboarding(reg *registry.Registry, configs *config.Manager, sto showConfigEntitiesOnTile := false showDiagnosticEntitiesOnTile := false widePanels := settings.Default().WidePanels - statusBarItems := settings.Default().StatusBarItems showLanguageSwitch := true masthead := mastheadView{Title: settings.DefaultDashboardTitle, ShowTitle: true, ShowSubtitle: true} historyViews := []settings.HistoryView{} @@ -987,7 +986,6 @@ func OverviewWithOnboarding(reg *registry.Registry, configs *config.Manager, sto showConfigEntitiesOnTile = value.ShowConfigEntitiesOnTile showDiagnosticEntitiesOnTile = value.ShowDiagnosticEntitiesOnTile widePanels = value.WidePanels - statusBarItems = value.StatusBarItems showLanguageSwitch = !value.LanguageSwitchHidden masthead = mastheadFrom(value) historyViews = value.HistoryViews @@ -1086,7 +1084,6 @@ func OverviewWithOnboarding(reg *registry.Registry, configs *config.Manager, sto "Theme": theme, "IgnoredDevices": []devicefilter.Summary{}, "WidePanels": strings.Join(widePanels, ","), - "StatusBarItems": strings.Join(statusBarItems, ","), "InstalledServices": resolvedInstalledServices, "Lang": lang, "Languages": translator.Options(lang), diff --git a/dashboard/internal/webui/webui_test.go b/dashboard/internal/webui/webui_test.go index 26a17ad58..3abbda874 100644 --- a/dashboard/internal/webui/webui_test.go +++ b/dashboard/internal/webui/webui_test.go @@ -60,7 +60,7 @@ func TestOverviewRendersManagerControls(t *testing.T) { "id=\"overview-live\"", "dashboardShell", "setActivePanel('history-panel')", "x-on:click", "x-bind:class", "x-show=\"activePanel === 'config-panel'\"", "role=\"tablist\"", "role=\"tab\"", "role=\"tabpanel\"", "aria-controls=\"overview-panel\"", "id=\"overview-panel\" class=\"panel\" role=\"tabpanel\"", "x-bind:class=\"{ active: activePanel === 'overview-panel' }\"", "id=\"devices-live\"", "hx-get=\"/?fragment=devices-live\"", - "id=\"runtime-status\"", "runtimeStatusPanel", "data-runtime-status-enabled=\"true\"", "data-status-bar-items=\"mqtt,storage,uptime,version\"", "aria-live=\"polite\"", + "id=\"runtime-status\"", "runtimeStatusPanel", "data-runtime-status-enabled=\"true\"", "aria-live=\"polite\"", "device-detail", "device-modal-warning", "discovery-diagnostics", "discovery_errors", "duplicateIDs", "discovery-error", "Konfiguration", "Einstellungen", "Diagnose", "license-footer", "(0BSD)", "(MIT, Copyright Caleb Porzio)", "ApexCharts 4.7.0", "(MIT, Copyright ApexCharts)", "ApexCharts-Lizenz", "v2.0.6/LICENSE", "v3.14.9/README.md", "configPanel", "x-model=\"selectedName\"", "reloadService()", "show-runtime-status", "showRuntimeStatus", "role=\"switch\"", "settings-toggle-track", "id=\"config-panel\"", "id=\"energy-panel\"", "data-panel-script=\"/static/js/revisions.js?v=4,/static/js/schema-form.js?v=2,/static/js/config-status.js?v=4,/static/js/config.page.js?v=11\"", "data-panel-script=\"/static/js-deps/cytoscape.min.js,/static/js/revisions.js?v=4,/static/js/devicemap-model.js?v=16,/static/js/devicemap-subdevices.js?v=1,/static/js/energy-chains.js?v=2,/static/js/energy-chain-suggest.js?v=2,/static/js/devicemap-graph.js?v=12,/static/js/devicemap-wiring.js?v=3,/static/js/devicemap-dataflow.js?v=5,/static/js/devicemap-node-svg.js?v=7,/static/js/devicemap-labels.js?v=6,/static/js/energy-plant.js?v=7,/static/js/device-picker.js?v=2,/static/js/devicemap-switch.js?v=2,/static/js/energy.page.js?v=19\"", "data-panel-css=\"/static/css/manager.css?v=54\"", "schema-form", "revision-preview", "config-presets-error", From 1b4cce1a9e51ae2b3e27f595a9f2f90f81541a92 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:48:33 +0100 Subject: [PATCH 05/20] refactor(settings): drop the status field chooser from settings and installer Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 14 +----- dashboard/internal/webui/catalogs/en.json | 14 +----- .../webui/static/css/settings-controls.css | 4 +- .../internal/webui/static/js/settings.page.js | 28 ++--------- .../internal/webui/templates/settings.html | 16 ------ dashboard/internal/webui/webui_test.go | 1 - dashboard/test/settings.language.test.mjs | 4 +- dashboard/test/settings.learning.test.mjs | 3 +- dashboard/test/settings.masthead.test.mjs | 4 +- dashboard/test/settings.page.test.mjs | 50 ++++++++----------- dashboard/test/settings.updates.test.mjs | 8 +-- installer/webui/catalogs/de.json | 3 +- installer/webui/catalogs/en.json | 3 +- installer/webui/static/js/screen-dashboard.js | 9 +--- .../webui/templates/screen-dashboard.html | 5 -- .../webui/test/screen-dashboard.test.mjs | 16 +++--- 16 files changed, 49 insertions(+), 133 deletions(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index c81433806..ce1087453 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -4787,10 +4787,7 @@ "settings.number_format.point": "1,234.5", "settings.read_only": "Du kannst die Einstellungen ansehen, aber nicht ändern.", "settings.revisions.label": "Revisionen der Einstellungen", - "settings.runtime_status.bar_items": "Angaben im Systemstatus", - "settings.runtime_status.bar_items_help": "Nur wirksam, wenn \"Globalen Systemstatus anzeigen\" oben aktiv ist.", - "settings.runtime_status.bar_items_help_button": "Erklärung zu Angaben im Systemstatus", - "settings.runtime_status.show": "Globalen Systemstatus anzeigen", + "settings.runtime_status.show": "Systemstatus in der Kopfzeile anzeigen", "settings.runtime_status.title": "Systemstatus", "settings.saved": "Einstellungen gespeichert.", "settings.saving": "Speichere ...", @@ -4800,15 +4797,6 @@ "settings.stale.label": "Veraltet nach", "settings.stale.note": "Kommt so lange kein neuer Wert über MQTT, gilt der letzte als veraltet. Der Health-Score des Geräts fällt dann auf null.", "settings.stale.title": "Veraltete Werte", - "settings.status_bar.item.cache": "Cache", - "settings.status_bar.item.cpu_load": "CPU-Auslastung", - "settings.status_bar.item.cpu_temp": "CPU-Temperatur", - "settings.status_bar.item.mqtt": "MQTT", - "settings.status_bar.item.ram": "RAM", - "settings.status_bar.item.storage": "Storage", - "settings.status_bar.item.undervoltage": "Unterspannung", - "settings.status_bar.item.uptime": "Uptime", - "settings.status_bar.item.version": "Dashboard-Version", "settings.sweep.decrease": "Seltener sichern", "settings.sweep.increase": "Öfter sichern", "settings.sweep.label": "Sichern alle", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 99d614de6..08f9d1ff8 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -4787,10 +4787,7 @@ "settings.number_format.point": "1,234.5", "settings.read_only": "You can view the settings but not change them.", "settings.revisions.label": "Settings revisions", - "settings.runtime_status.bar_items": "Items in the system status", - "settings.runtime_status.bar_items_help": "Only takes effect when \"Show global system status\" above is on.", - "settings.runtime_status.bar_items_help_button": "About items in the system status", - "settings.runtime_status.show": "Show global system status", + "settings.runtime_status.show": "Show the system status in the header", "settings.runtime_status.title": "System status", "settings.saved": "Settings saved.", "settings.saving": "Saving ...", @@ -4800,15 +4797,6 @@ "settings.stale.label": "Stale after", "settings.stale.note": "If no new value arrives over MQTT for this long, the last one counts as stale. The health score of the device then drops to zero.", "settings.stale.title": "Stale values", - "settings.status_bar.item.cache": "Cache", - "settings.status_bar.item.cpu_load": "CPU load", - "settings.status_bar.item.cpu_temp": "CPU temperature", - "settings.status_bar.item.mqtt": "MQTT", - "settings.status_bar.item.ram": "RAM", - "settings.status_bar.item.storage": "Storage", - "settings.status_bar.item.undervoltage": "Undervoltage", - "settings.status_bar.item.uptime": "Uptime", - "settings.status_bar.item.version": "Dashboard version", "settings.sweep.decrease": "Save less often", "settings.sweep.increase": "Save more often", "settings.sweep.label": "Save every", diff --git a/dashboard/internal/webui/static/css/settings-controls.css b/dashboard/internal/webui/static/css/settings-controls.css index 02fc08435..ebbcc536c 100644 --- a/dashboard/internal/webui/static/css/settings-controls.css +++ b/dashboard/internal/webui/static/css/settings-controls.css @@ -504,8 +504,8 @@ /* --- Karten, die die volle Rasterbreite brauchen --------------------- Der Darstellungs-Tab hat Karten mit den breiten Choices.js-Mehrfach- - auswahlen (Tab-Breite, Angaben im Systemstatus) - die stehen ueber - beide Spalten, nicht halbbreit gequetscht. */ + auswahlen (Tab-Breite) - die stehen ueber beide Spalten, nicht + halbbreit gequetscht. */ .setting-card--wide { grid-column: 1 / -1; } /* Der Speicherzustand ist jetzt selbst eine .setting-card; das margin-top diff --git a/dashboard/internal/webui/static/js/settings.page.js b/dashboard/internal/webui/static/js/settings.page.js index 481d9de98..47a0db624 100644 --- a/dashboard/internal/webui/static/js/settings.page.js +++ b/dashboard/internal/webui/static/js/settings.page.js @@ -152,26 +152,12 @@ {key: 'efficiency', label: 'nav.efficiency'}, {key: 'monitoring', label: 'nav.monitoring'}, ], - statusBarItems: [], - // Schluessel, wie sie runtimeStatusPanel() in dashboard.js interpretiert. - statusBarItemOptions: [ - {key: 'mqtt', label: 'settings.status_bar.item.mqtt'}, - {key: 'cache', label: 'settings.status_bar.item.cache'}, - {key: 'storage', label: 'settings.status_bar.item.storage'}, - {key: 'uptime', label: 'settings.status_bar.item.uptime'}, - {key: 'version', label: 'settings.status_bar.item.version'}, - {key: 'cpu_temp', label: 'settings.status_bar.item.cpu_temp'}, - {key: 'cpu_load', label: 'settings.status_bar.item.cpu_load'}, - {key: 'ram', label: 'settings.status_bar.item.ram'}, - {key: 'undervoltage', label: 'settings.status_bar.item.undervoltage'}, - ], loading: false, saving: false, storageHealth: null, storageHealthLoading: false, storageHealthError: '', widePanelsChoices: null, - statusBarItemsChoices: null, // Konto-Karte: Benutzername, Sitzungsflags und CSRF-Token aus der Sitzung. // Gaeste und Sitzungen ueber die Home-Assistant-Kopplung bekommen keine Karte. accountUsername: '', @@ -217,7 +203,6 @@ this.showDiagnosticEntitiesOnTile = Boolean(value.show_diagnostic_entities_on_tile); this.liveUpdateIntervalSeconds = value.live_update_interval_seconds || 3; this.widePanels = Array.isArray(value.wide_panels) ? [...value.wide_panels] : []; - this.statusBarItems = Array.isArray(value.status_bar_items) ? [...value.status_bar_items] : []; this.historySampleIntervalSeconds = value.history_sample_interval_seconds || 10; this.historyRetentionMode = value.history_retention_mode === 'size' ? 'size' : 'time'; this.historyRetentionHours = value.history_retention_hours || 6; @@ -264,7 +249,6 @@ this.passwordMin = Number(session && session.password_min_length) || ACCOUNT_MIN_PASSWORD; this.csrfToken = (session && session.csrf_token) || ''; this.setChoicesSelection(this.widePanelsChoices, this.widePanels); - this.setChoicesSelection(this.statusBarItemsChoices, this.statusBarItems); this.loadEnergyStatsStatus(); } catch (error) { this.$store.toasts.push(error.message, 'critical'); @@ -331,7 +315,7 @@ }, // Choices.js liest die Auswahl nur beim Erstellen aus dem // erreicht sie nicht. Darum folgen sie dem Darstellungsrecht ueber die API. syncChoicesEnabled(enabled) { - for (const instance of [this.widePanelsChoices, this.statusBarItemsChoices]) { + for (const instance of [this.widePanelsChoices]) { if (!instance) continue; if (enabled && typeof instance.enable === 'function') instance.enable(); if (!enabled && typeof instance.disable === 'function') instance.disable(); @@ -352,7 +336,7 @@ // Choices.js feuert bei Auswahlaenderungen ein eigenes "change" mit // detail={value: ...}; Alpines x-model liest bei CustomEvents mit // gesetztem detail dieses Feld direkt als neuen Modellwert (fuer - // Web-Components gedacht) und ueberschreibt widePanels/statusBarItems damit + // Web-Components gedacht) und ueberschreibt widePanels damit // mit einem einzelnen Objekt statt einem Array. Deshalb kein x-model auf // diesen -
- - -
diff --git a/dashboard/internal/webui/webui_test.go b/dashboard/internal/webui/webui_test.go index 3abbda874..3a3990b30 100644 --- a/dashboard/internal/webui/webui_test.go +++ b/dashboard/internal/webui/webui_test.go @@ -68,7 +68,6 @@ func TestOverviewRendersManagerControls(t *testing.T) { "revision-diff", "revisionPanel(revisionConfig())", "setRevisionView('diff')", "diagnosticsPanel", "diagnostics-health-heading", "sortedHealthScores", "diagnostics-health-status", "sort('entity_id')", "settingsPanel", "item.entity_id || '-'", "storage-health-heading", "Speicherzustand", "Geschätzte Restlaufzeit", "loadStorageHealth()", "settings-wide-panels", "Tabs ohne Breitendeckelung", "widePanelOptions", "wide-panels-select", "initChoices()", - "settings-status-bar-items", "Angaben im Systemstatus", "statusBarItemOptions", "status-bar-items-select", } for _, marker := range markers { if !strings.Contains(body, marker) { diff --git a/dashboard/test/settings.language.test.mjs b/dashboard/test/settings.language.test.mjs index d0e5dbc93..6dbbad5f8 100644 --- a/dashboard/test/settings.language.test.mjs +++ b/dashboard/test/settings.language.test.mjs @@ -27,7 +27,7 @@ const settingsResponse = { health_score_threshold: 180, sweep_interval_seconds: 300, show_runtime_status: true, device_view_mode: 'compact', theme: 'mint', show_config_entities_on_tile: false, show_diagnostic_entities_on_tile: false, - live_update_interval_seconds: 3, wide_panels: [], status_bar_items: [], + live_update_interval_seconds: 3, wide_panels: [], language_switch_hidden: true, }; @@ -52,7 +52,7 @@ function load({ saveOk = true } = {}) { vm.runInContext(scriptSource, dom.getInternalVMContext()); const component = factories.settingsPanel(); attachStores(component); - component.$refs = { widePanelsSelect: dom.window.document.createElement('select'), statusBarItemsSelect: dom.window.document.createElement('select') }; + component.$refs = { widePanelsSelect: dom.window.document.createElement('select') }; return { dom, component, switched }; } diff --git a/dashboard/test/settings.learning.test.mjs b/dashboard/test/settings.learning.test.mjs index 91ed6d9db..0280bd95d 100644 --- a/dashboard/test/settings.learning.test.mjs +++ b/dashboard/test/settings.learning.test.mjs @@ -22,7 +22,7 @@ const settingsResponse = (overrides = {}) => ({ health_score_threshold: 180, sweep_interval_seconds: 300, show_runtime_status: true, device_view_mode: 'compact', theme: 'mint', show_config_entities_on_tile: false, show_diagnostic_entities_on_tile: false, - live_update_interval_seconds: 3, wide_panels: [], status_bar_items: [], + live_update_interval_seconds: 3, wide_panels: [], number_format: 'auto', number_grouping: 'match', ...overrides, }); @@ -43,7 +43,6 @@ function createPanel(fetchImpl) { attachStores(component); component.$refs = { widePanelsSelect: dom.window.document.createElement('select'), - statusBarItemsSelect: dom.window.document.createElement('select'), }; return { dom, component }; } diff --git a/dashboard/test/settings.masthead.test.mjs b/dashboard/test/settings.masthead.test.mjs index 0799f5a0d..4f2858979 100644 --- a/dashboard/test/settings.masthead.test.mjs +++ b/dashboard/test/settings.masthead.test.mjs @@ -27,7 +27,7 @@ const settingsResponse = { health_score_threshold: 180, sweep_interval_seconds: 300, show_runtime_status: true, device_view_mode: 'compact', theme: 'mint', show_config_entities_on_tile: false, show_diagnostic_entities_on_tile: false, - live_update_interval_seconds: 3, wide_panels: [], status_bar_items: [], + live_update_interval_seconds: 3, wide_panels: [], dashboard_title: 'Werkstatt', dashboard_subtitle: '', dashboard_title_hidden: false, dashboard_subtitle_hidden: true, }; @@ -56,7 +56,7 @@ function load() { vm.runInContext(scriptSource, dom.getInternalVMContext()); const component = factories.settingsPanel(); attachStores(component); - component.$refs = { widePanelsSelect: dom.window.document.createElement('select'), statusBarItemsSelect: dom.window.document.createElement('select') }; + component.$refs = { widePanelsSelect: dom.window.document.createElement('select') }; return { dom, component, saved }; } diff --git a/dashboard/test/settings.page.test.mjs b/dashboard/test/settings.page.test.mjs index d8c13a34b..6fa175ed1 100644 --- a/dashboard/test/settings.page.test.mjs +++ b/dashboard/test/settings.page.test.mjs @@ -1,8 +1,8 @@ // Regression tests for settings.page.js: the Choices.js wiring for the -// wide-panels/status-bar-items multi-selects. initChoices()/setChoicesSelection() -// bridge Alpine's widePanels/statusBarItems arrays to the Choices.js API (which -// only reads the underlying once, at construction time), so both need direct coverage +// independent of the vendored library itself. // Run with `npm test` from dashboard/, same approach as mqtt.page.test.mjs. import { test } from 'node:test'; import assert from 'node:assert/strict'; @@ -63,7 +63,6 @@ function createSettingsPanel({ fetchImpl, withChoices = true } = {}) { const stores = attachStores(component); component.$refs = { widePanelsSelect: dom.window.document.createElement('select'), - statusBarItemsSelect: dom.window.document.createElement('select'), }; return { component, window: dom.window, stores }; } @@ -74,7 +73,7 @@ const settingsResponse = (overrides = {}) => ({ health_score_threshold: 180, sweep_interval_seconds: 300, show_runtime_status: true, device_view_mode: 'compact', theme: 'mint', show_config_entities_on_tile: false, show_diagnostic_entities_on_tile: false, - live_update_interval_seconds: 3, wide_panels: [], status_bar_items: [], + live_update_interval_seconds: 3, wide_panels: [], number_format: 'auto', number_grouping: 'match', ...overrides, }); @@ -101,10 +100,10 @@ test('toggleWidePanel/toggleStatusBarItem were removed with the checkbox-list ma // Regression test for the actual bug reported after shipping: with x-model on // a Choices-controlled -
- -
diff --git a/installer/webui/test/screen-dashboard.test.mjs b/installer/webui/test/screen-dashboard.test.mjs index 3d236809a..529d528b0 100644 --- a/installer/webui/test/screen-dashboard.test.mjs +++ b/installer/webui/test/screen-dashboard.test.mjs @@ -32,7 +32,7 @@ test('init legt die Vorgaben am App-Store ab, alles unveraendert', () => { const { screen, shell } = mount(); assert.deepEqual(plain(shell.shared.dashboardPrefs), { admin_user: '', users: [], guest_access: null, theme: null, title: '', subtitle: '', - status_bar_items: null, show_runtime_status: null, wide_panels: null, update_check: null, + show_runtime_status: null, wide_panels: null, update_check: null, metrics: null, later: [], }); assert.equal(screen.groupState('theme'), 'default'); @@ -78,13 +78,15 @@ test('der Alle-Chip setzt alle Tabs, einzelne Chips schalten um', () => { assert.equal(screen.groupState('tabwidth'), 'set'); }); -test('Systemstatus beginnt mit den Vorgaben des Dashboards und behaelt die Reihenfolge', () => { +test('Systemstatus hat nur den Schalter, die Gruppe fasst nur show_runtime_status an', () => { const { screen, shell } = mount(); - assert.equal(screen.chipOn('statusbar', 'mqtt'), true); - assert.equal(screen.chipOn('statusbar', 'cache'), false); - screen.toggleChip('statusbar', 'cache'); - assert.deepEqual(plain(shell.shared.dashboardPrefs.status_bar_items), - ['mqtt', 'cache', 'storage', 'uptime', 'version']); + assert.equal(Object.prototype.hasOwnProperty.call(shell.shared.dashboardPrefs, 'status_bar_items'), false); + shell.shared.dashboardPrefs.show_runtime_status = false; + screen.toggleLater('statusbar'); + assert.equal(shell.shared.dashboardPrefs.show_runtime_status, null); + screen.toggleLater('statusbar'); + assert.equal(shell.shared.dashboardPrefs.show_runtime_status, false); + assert.equal(screen.groupState('statusbar'), 'set'); }); test('Benutzerzeile verlangt Namen nach [a-z0-9._-]{3,32}', () => { From 0c99637c1c032806f0297e3d097d72f624636fd5 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:53:02 +0100 Subject: [PATCH 06/20] feat(dashboard): one title row with a status chip that names its cause Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 34 ++++- dashboard/internal/webui/catalogs/en.json | 34 ++++- dashboard/internal/webui/localize_test.go | 6 +- dashboard/internal/webui/static/css/base.css | 39 ------ .../internal/webui/static/js/dashboard.js | 125 ++++++++++++++--- dashboard/internal/webui/templates/base.html | 41 +++--- dashboard/internal/webui/webui_test.go | 2 +- dashboard/test/dashboard.i18n.test.mjs | 27 ++-- dashboard/test/dashboard.overview.test.mjs | 17 +++ dashboard/test/dashboard.status-chip.test.mjs | 131 ++++++++++++++++++ 10 files changed, 356 insertions(+), 100 deletions(-) create mode 100644 dashboard/test/dashboard.status-chip.test.mjs diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index ce1087453..833d67365 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -4946,30 +4946,58 @@ "status.cache.impaired": "beeinträchtigt", "status.cache.loaded": "geladen", "status.cache.not_loaded": "nicht geladen", - "status.degraded": "Beeinträchtigt", + "status.count.bad.one": "{n} Störung", + "status.count.bad.other": "{n} Störungen", + "status.count.warn.one": "{n} Hinweis", + "status.count.warn.other": "{n} Hinweise", + "status.issue.cache_error.chip": "Cache-Fehler", + "status.issue.cache_error.label": "Cache", + "status.issue.cache_error.value": "Fehler", + "status.issue.cpu_hot.chip": "CPU heiß", + "status.issue.cpu_hot.label": "CPU", + "status.issue.cpu_hot.value": "{value} °C", + "status.issue.mqtt_disconnected.chip": "MQTT getrennt", + "status.issue.mqtt_disconnected.label": "MQTT", + "status.issue.mqtt_disconnected.value": "getrennt", + "status.issue.ram_full.chip": "RAM knapp", + "status.issue.ram_full.label": "RAM", + "status.issue.ram_full.value": "{value} %", + "status.issue.service_down.chip": "{service} läuft nicht", + "status.issue.service_down.label": "Dienst {service}", + "status.issue.service_down.value": "läuft nicht", + "status.issue.storage_error.chip": "Speicherfehler", + "status.issue.storage_error.label": "Storage", + "status.issue.storage_error.value": "{reason}", + "status.issue.undervoltage.chip": "Unterspannung", + "status.issue.undervoltage.label": "Spannung", + "status.issue.undervoltage.value": "Unterspannung", "status.label.cache": "Cache", "status.label.cpu_load": "CPU-Last", "status.label.cpu_temp": "CPU", + "status.label.mqtt": "MQTT", "status.label.ram": "RAM", "status.label.storage": "Storage", "status.label.uptime": "Uptime", "status.label.version": "Version", + "status.label.voltage": "Spannung", "status.loading": "Lade Status ...", "status.mqtt.connected": "verbunden", "status.mqtt.disconnected": "getrennt", "status.offline": "Offline", "status.ok": "Betriebsbereit", "status.online": "Online", + "status.open_diagnostics": "Diagnose öffnen", + "status.ready_short": "Bereit", "status.storage.available": "verfügbar", "status.storage.unavailable": "nicht verfügbar", "status.title": "Systemstatus", "status.unavailable": "Status nicht verfügbar", - "status.undervoltage.now": "⚠ Unterspannung", - "status.undervoltage.ok": "Spannung ok", "status.unknown": "Unbekannt", "status.uptime.days_hours": "{days} T {hours} h", "status.uptime.hours_minutes": "{hours} h {minutes} min", "status.uptime.minutes": "{minutes} min", + "status.voltage.low": "Unterspannung", + "status.voltage.ok": "ok", "storage.contents.disk": "Alle Partitionen auf diesem Stick werden gelöscht und durch eine einzige ersetzt.", "storage.contents.foreign": "Auf diesem Laufwerk liegt ein Dateisystem, das die Node nicht nutzt. Die Node kann nur ext4 nutzen, beim Formatieren gehen die Daten verloren.", "storage.contents.none": "Auf diesem Laufwerk gibt es kein Dateisystem. Die Node formatiert es vorher.", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 08f9d1ff8..89180b504 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -4946,30 +4946,58 @@ "status.cache.impaired": "impaired", "status.cache.loaded": "loaded", "status.cache.not_loaded": "not loaded", - "status.degraded": "Degraded", + "status.count.bad.one": "{n} problem", + "status.count.bad.other": "{n} problems", + "status.count.warn.one": "{n} notice", + "status.count.warn.other": "{n} notices", + "status.issue.cache_error.chip": "Cache error", + "status.issue.cache_error.label": "Cache", + "status.issue.cache_error.value": "error", + "status.issue.cpu_hot.chip": "CPU hot", + "status.issue.cpu_hot.label": "CPU", + "status.issue.cpu_hot.value": "{value} °C", + "status.issue.mqtt_disconnected.chip": "MQTT disconnected", + "status.issue.mqtt_disconnected.label": "MQTT", + "status.issue.mqtt_disconnected.value": "disconnected", + "status.issue.ram_full.chip": "RAM almost full", + "status.issue.ram_full.label": "RAM", + "status.issue.ram_full.value": "{value} %", + "status.issue.service_down.chip": "{service} not running", + "status.issue.service_down.label": "Service {service}", + "status.issue.service_down.value": "not running", + "status.issue.storage_error.chip": "Storage error", + "status.issue.storage_error.label": "Storage", + "status.issue.storage_error.value": "{reason}", + "status.issue.undervoltage.chip": "Undervoltage", + "status.issue.undervoltage.label": "Voltage", + "status.issue.undervoltage.value": "undervoltage", "status.label.cache": "Cache", "status.label.cpu_load": "CPU load", "status.label.cpu_temp": "CPU", + "status.label.mqtt": "MQTT", "status.label.ram": "RAM", "status.label.storage": "Storage", "status.label.uptime": "Uptime", "status.label.version": "Version", + "status.label.voltage": "Voltage", "status.loading": "Loading status ...", "status.mqtt.connected": "connected", "status.mqtt.disconnected": "disconnected", "status.offline": "Offline", "status.ok": "Operational", "status.online": "Online", + "status.open_diagnostics": "Open diagnostics", + "status.ready_short": "Ready", "status.storage.available": "available", "status.storage.unavailable": "unavailable", "status.title": "System status", "status.unavailable": "Status unavailable", - "status.undervoltage.now": "⚠ Undervoltage", - "status.undervoltage.ok": "Voltage ok", "status.unknown": "Unknown", "status.uptime.days_hours": "{days} d {hours} h", "status.uptime.hours_minutes": "{hours} h {minutes} min", "status.uptime.minutes": "{minutes} min", + "status.voltage.low": "Undervoltage", + "status.voltage.ok": "ok", "storage.contents.disk": "All partitions on this stick are deleted and replaced by a single one.", "storage.contents.foreign": "This drive holds a file system the node does not use. The node can only use ext4, and formatting deletes the data.", "storage.contents.none": "This drive has no file system. The node formats it first.", diff --git a/dashboard/internal/webui/localize_test.go b/dashboard/internal/webui/localize_test.go index 0e078ed07..4f88f394c 100644 --- a/dashboard/internal/webui/localize_test.go +++ b/dashboard/internal/webui/localize_test.go @@ -156,8 +156,8 @@ func TestMastheadAndStatusBarFollowTheLanguage(t *testing.T) { german := renderOverviewWithLang(t, "de") for _, want := range []string{ "Discovery-getriebene Live-Ansicht und lokaler Gerätemanager", - `Systemstatus`, - "$t('status.mqtt.connected')", + `
Discovery-driven live view and local device manager", - `System status`, + `
({ - status: null, + open: false, enabled: true, - items: ['mqtt', 'storage', 'uptime', 'version'], + status: null, loading: false, error: '', timer: null, settingChanged: null, - itemsChanged: null, - get statusLabel() { - if (this.loading && !this.status) return t('status.loading'); - if (this.error && !this.status) return t('status.unavailable'); - return this.status?.status === 'degraded' ? t('status.degraded') : t('status.ok'); + // Die Texte kommen aus dem Katalog. Die Schluessel werden aus dem + // issue-Schluessel gebaut, deshalb die Liste hier: + // i18n-keys: status.issue.mqtt_disconnected.chip, status.issue.mqtt_disconnected.label, status.issue.mqtt_disconnected.value + // i18n-keys: status.issue.cache_error.chip, status.issue.cache_error.label, status.issue.cache_error.value + // i18n-keys: status.issue.storage_error.chip, status.issue.storage_error.label, status.issue.storage_error.value + // i18n-keys: status.issue.undervoltage.chip, status.issue.undervoltage.label, status.issue.undervoltage.value + // i18n-keys: status.issue.cpu_hot.chip, status.issue.cpu_hot.label, status.issue.cpu_hot.value + // i18n-keys: status.issue.ram_full.chip, status.issue.ram_full.label, status.issue.ram_full.value + // i18n-keys: status.issue.service_down.chip, status.issue.service_down.label, status.issue.service_down.value + get issues() { + // Der Server liefert die Liste schon sortiert. Die Sortierung hier + // (bad vor warn, sonst Reihenfolge) haelt den Chip auch bei anderer + // Quelle richtig. + return (this.status?.issues || []) + .map(issue => ({ + key: issue.key, + level: issue.level, + chip: t(`status.issue.${issue.key}.chip`, issue.params), + label: t(`status.issue.${issue.key}.label`, issue.params), + value: t(`status.issue.${issue.key}.value`, issue.params), + })) + .sort((a, b) => (a.level === 'bad' ? 0 : 1) - (b.level === 'bad' ? 0 : 1)); + }, + + get level() { + if (!this.status) return this.error ? 'bad' : 'loading'; + if (this.issues.some(issue => issue.level === 'bad')) return 'bad'; + return this.issues.length ? 'warn' : 'ok'; + }, + + get chipLabel() { + if (this.level === 'loading') return t('status.loading'); + if (!this.status) return t('status.unavailable'); + const list = this.issues; + if (!list.length) return t('status.ok'); + if (list.length === 1) return list[0].chip; + return this.level === 'bad' + ? tn('status.count.bad', list.length) + : tn('status.count.warn', list.length); }, - get statusClass() { - if (this.error && !this.status) return 'runtime-status-error'; - return this.status?.status === 'degraded' ? 'runtime-status-degraded' : 'runtime-status-ok'; + get chipShort() { + return this.level === 'ok' ? t('status.ready_short') : this.chipLabel; + }, + + get rows() { + const s = this.status; + if (!s) return []; + const flagged = new Set(this.issues.map(issue => STATUS_ISSUE_ROW[issue.key]).filter(Boolean)); + const telemetry = s.node?.telemetry; + const rowOf = key => { + switch (key) { + case 'mqtt': + return s.mqtt == null ? null : { + label: t('status.label.mqtt'), + value: s.mqtt.connected ? t('status.mqtt.connected') : t('status.mqtt.disconnected'), + }; + case 'cache': { + const cache = s.runtime_cache; + if (cache == null) return null; + let value = t('status.cache.not_loaded'); + if (cache.load_error || cache.write_error) value = t('status.cache.impaired'); + else if (cache.loaded) value = t('status.cache.loaded'); + return {label: t('status.label.cache'), value}; + } + case 'storage': + return s.storage == null ? null : { + label: t('status.label.storage'), + value: s.storage.available ? t('status.storage.available') : t('status.storage.unavailable'), + }; + case 'uptime': + return {label: t('status.label.uptime'), value: this.formatUptime(s.uptime_seconds)}; + case 'version': + return {label: t('status.label.version'), value: s.version || '-'}; + case 'cpu_temp': + return telemetry?.cpu_temp_c === undefined ? null : {label: t('status.label.cpu_temp'), value: this.formatTemp(telemetry.cpu_temp_c)}; + case 'cpu_load': + return telemetry?.cpu_load_pct === undefined ? null : {label: t('status.label.cpu_load'), value: this.formatPct(telemetry.cpu_load_pct)}; + case 'ram': + return telemetry?.ram_used_pct === undefined ? null : {label: t('status.label.ram'), value: this.formatPct(telemetry.ram_used_pct)}; + case 'undervoltage': + return telemetry == null ? null : { + label: t('status.label.voltage'), + value: telemetry.undervoltage_now ? t('status.voltage.low') : t('status.voltage.ok'), + }; + default: + return null; + } + }; + return STATUS_ROWS + .filter(key => !flagged.has(key)) + .map(key => { + const row = rowOf(key); + return row && {key, ...row}; + }) + .filter(Boolean); + }, + + get canDiagnose() { + return Boolean(document.getElementById('tab-diagnostics')); }, formatUptime(seconds) { @@ -806,8 +901,8 @@ try { this.status = await requestJSON('/api/v1/health'); } catch (error) { - // Das Feld bleibt: statusLabel/statusClass leiten das Badge daraus ab. - // Der 30-s-Poll wuerde ohne die Entdopplung im Toast-Store die Liste + // Ohne Status zeigt der Chip "nicht verfuegbar" (level bad). Der + // 30-s-Poll wuerde ohne die Entdopplung im Toast-Store die Liste // fluten - der Zaehler fasst ihn zu einem hochzaehlenden Toast zusammen. this.error = error.message; this.$store.toasts.push(error.message, 'critical'); @@ -823,7 +918,6 @@ // Fragment-Nachladen oder ein Panel-Wechsel doppelt einsteigen. if (this.timer) return; this.enabled = this.$root.dataset.runtimeStatusEnabled !== 'false'; - this.items = (this.$root.dataset.statusBarItems || '').split(',').filter(Boolean); this.settingChanged = event => { this.enabled = Boolean(event.detail.enabled); if (!this.enabled) { @@ -836,11 +930,7 @@ this.load(); if (!this.timer) this.timer = window.setInterval(() => this.load(), 30000); }; - this.itemsChanged = event => { - this.items = event.detail?.items || []; - }; document.addEventListener('runtime-status-setting-changed', this.settingChanged); - document.addEventListener('status-bar-items-changed', this.itemsChanged); if (this.enabled) { this.load(); this.timer = window.setInterval(() => this.load(), 30000); @@ -850,7 +940,6 @@ destroy() { if (this.timer) window.clearInterval(this.timer); if (this.settingChanged) document.removeEventListener('runtime-status-setting-changed', this.settingChanged); - if (this.itemsChanged) document.removeEventListener('status-bar-items-changed', this.itemsChanged); }, }); diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 407f3360c..8c193ff7e 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -89,7 +89,27 @@

{{.Masthead.Title}}

- {{template "lang-pill" .}} +
+
+ +
+ +
+ +
+ +
+
+ {{template "lang-pill" .}} +
{{if .Masthead.Subtitle}}{{.Masthead.Subtitle}}{{else}}{{t "masthead.subtitle"}}{{end}}
@@ -114,25 +134,6 @@

{{.Masthead.

-
-
- {{t "status.title"}} - -
-
- MQTT: - {{t "status.label.cache"}}: - {{t "status.label.storage"}}: - {{t "status.label.uptime"}}: - {{t "status.label.version"}}: - {{t "status.label.cpu_temp"}}: - {{t "status.label.cpu_load"}}: - {{t "status.label.ram"}}: - - - -
-
{{if .OnboardingGuestNote}}

{{t "onboarding.guest_note.title"}} {{t "onboarding.guest_note.text"}}

diff --git a/dashboard/internal/webui/webui_test.go b/dashboard/internal/webui/webui_test.go index 3a3990b30..17ab4f812 100644 --- a/dashboard/internal/webui/webui_test.go +++ b/dashboard/internal/webui/webui_test.go @@ -60,7 +60,7 @@ func TestOverviewRendersManagerControls(t *testing.T) { "id=\"overview-live\"", "dashboardShell", "setActivePanel('history-panel')", "x-on:click", "x-bind:class", "x-show=\"activePanel === 'config-panel'\"", "role=\"tablist\"", "role=\"tab\"", "role=\"tabpanel\"", "aria-controls=\"overview-panel\"", "id=\"overview-panel\" class=\"panel\" role=\"tabpanel\"", "x-bind:class=\"{ active: activePanel === 'overview-panel' }\"", "id=\"devices-live\"", "hx-get=\"/?fragment=devices-live\"", - "id=\"runtime-status\"", "runtimeStatusPanel", "data-runtime-status-enabled=\"true\"", "aria-live=\"polite\"", + "id=\"runtime-status\"", "runtimeStatusPanel", "data-runtime-status-enabled=\"true\"", "class=\"masthead-tools\"", "status-chip", "device-detail", "device-modal-warning", "discovery-diagnostics", "discovery_errors", "duplicateIDs", "discovery-error", "Konfiguration", "Einstellungen", "Diagnose", "license-footer", "(0BSD)", "(MIT, Copyright Caleb Porzio)", "ApexCharts 4.7.0", "(MIT, Copyright ApexCharts)", "ApexCharts-Lizenz", "v2.0.6/LICENSE", "v3.14.9/README.md", "configPanel", "x-model=\"selectedName\"", "reloadService()", "show-runtime-status", "showRuntimeStatus", "role=\"switch\"", "settings-toggle-track", "id=\"config-panel\"", "id=\"energy-panel\"", "data-panel-script=\"/static/js/revisions.js?v=4,/static/js/schema-form.js?v=2,/static/js/config-status.js?v=4,/static/js/config.page.js?v=11\"", "data-panel-script=\"/static/js-deps/cytoscape.min.js,/static/js/revisions.js?v=4,/static/js/devicemap-model.js?v=16,/static/js/devicemap-subdevices.js?v=1,/static/js/energy-chains.js?v=2,/static/js/energy-chain-suggest.js?v=2,/static/js/devicemap-graph.js?v=12,/static/js/devicemap-wiring.js?v=3,/static/js/devicemap-dataflow.js?v=5,/static/js/devicemap-node-svg.js?v=7,/static/js/devicemap-labels.js?v=6,/static/js/energy-plant.js?v=7,/static/js/device-picker.js?v=2,/static/js/devicemap-switch.js?v=2,/static/js/energy.page.js?v=19\"", "data-panel-css=\"/static/css/manager.css?v=54\"", "schema-form", "revision-preview", "config-presets-error", diff --git a/dashboard/test/dashboard.i18n.test.mjs b/dashboard/test/dashboard.i18n.test.mjs index 7bbf38acd..48732ec88 100644 --- a/dashboard/test/dashboard.i18n.test.mjs +++ b/dashboard/test/dashboard.i18n.test.mjs @@ -1,4 +1,4 @@ -// The runtime status bar labels come from the catalog via I18n.t, so a +// The title-row status chip labels come from the catalog via I18n.t, so a // language switch changes them without a reload of dashboard.js. import { test } from 'node:test'; import assert from 'node:assert/strict'; @@ -29,29 +29,30 @@ function createStatusPanel(I18n) { } const english = { + tn(key, n) { return this.t(`${key}${n === 1 ? '.one' : '.other'}`, { n }); }, t: (key, params = {}) => ({ 'status.loading': 'Loading status ...', 'status.unavailable': 'Status unavailable', 'status.ok': 'Operational', - 'status.degraded': 'Degraded', + 'status.count.bad.one': '1 problem', + 'status.count.bad.other': `${params.n} problems`, + 'status.ready_short': 'Ready', 'status.uptime.days_hours': `${params.days} d ${params.hours} h`, 'status.uptime.hours_minutes': `${params.hours} h ${params.minutes} min`, 'status.uptime.minutes': `${params.minutes} min`, }[key] || key), }; -test('statusLabel reads the catalog', () => { +test('chipLabel reads the catalog for loading, unavailable and ok', () => { const panel = createStatusPanel(english); - panel.loading = true; - assert.equal(panel.statusLabel, 'Loading status ...'); - panel.loading = false; + assert.equal(panel.chipLabel, 'Loading status ...'); panel.error = 'x'; - assert.equal(panel.statusLabel, 'Status unavailable'); + assert.equal(panel.chipLabel, 'Status unavailable'); panel.error = ''; - panel.status = { status: 'ok' }; - assert.equal(panel.statusLabel, 'Operational'); - panel.status = { status: 'degraded' }; - assert.equal(panel.statusLabel, 'Degraded'); + panel.status = { level: 'ok', issues: [] }; + assert.equal(panel.chipLabel, 'Operational'); + panel.status = { level: 'bad', issues: [{ key: 'cache_error', level: 'bad' }, { key: 'undervoltage', level: 'warn' }] }; + assert.equal(panel.chipLabel, '2 problems'); }); test('formatUptime uses the catalog units', () => { @@ -64,6 +65,6 @@ test('formatUptime uses the catalog units', () => { test('without the i18n runtime the keys stay visible instead of throwing', () => { const panel = createStatusPanel(undefined); - panel.status = { status: 'ok' }; - assert.equal(panel.statusLabel, 'status.ok'); + panel.status = { level: 'ok', issues: [] }; + assert.equal(panel.chipLabel, 'status.ok'); }); diff --git a/dashboard/test/dashboard.overview.test.mjs b/dashboard/test/dashboard.overview.test.mjs index 6dd6989ab..d09996eb5 100644 --- a/dashboard/test/dashboard.overview.test.mjs +++ b/dashboard/test/dashboard.overview.test.mjs @@ -93,6 +93,23 @@ test('ein zweiter init() auf runtimeStatusPanel legt kein zweites Intervall an', assert.equal(started, 1); }); +test('runtimeStatusPanel hoert nicht mehr auf die entfernte Statusfeld-Auswahl', () => { + const { factories, window } = load({ html: '
' }); + const panel = factories.runtimeStatusPanel(); + panel.$root = window.document.getElementById('runtime-status'); + attachStores(panel); + const listened = []; + const addEventListener = window.document.addEventListener.bind(window.document); + window.document.addEventListener = (type, handler, options) => { + listened.push(type); + return addEventListener(type, handler, options); + }; + window.setInterval = () => 1; + panel.init(); + assert.equal(listened.includes('status-bar-items-changed'), false); + assert.equal(listened.includes('runtime-status-setting-changed'), true); +}); + test('ein zweiter init() auf devicesPanel registriert keinen zweiten Zuhoerer', () => { const { factories, window } = load({ html: '
' }); const panel = factories.devicesPanel(); diff --git a/dashboard/test/dashboard.status-chip.test.mjs b/dashboard/test/dashboard.status-chip.test.mjs new file mode 100644 index 000000000..250036f0d --- /dev/null +++ b/dashboard/test/dashboard.status-chip.test.mjs @@ -0,0 +1,131 @@ +// The title-row status chip: runtimeStatusPanel turns the /api/v1/health +// issue list into the chip label, the chip level and the detail rows. The +// texts come from the catalog, so the stub returns the key (plus params) and +// the assertions check which key was asked for. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +import { JSDOM } from 'jsdom'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const source = fs.readFileSync( + path.join(here, '..', 'internal', 'webui', 'static', 'js', 'dashboard.js'), + 'utf8', +); + +const stubI18n = { + t: (key, params) => (params ? `${key}|${JSON.stringify(params)}` : key), + tn: (key, n) => `${key}#${n}`, +}; + +function createPanel() { + const dom = new JSDOM('', { + runScripts: 'outside-only', + url: 'http://localhost/', + }); + const factories = {}; + dom.window.Alpine = { data: (name, fn) => { factories[name] = fn; }, directive() {} }; + dom.window.setInterval = () => 0; + dom.window.I18n = stubI18n; + vm.runInContext(source, dom.getInternalVMContext()); + dom.window.document.dispatchEvent(new dom.window.Event('alpine:init')); + return factories.runtimeStatusPanel(); +} + +test('chip is calm when the level is ok', () => { + const panel = createPanel(); + panel.status = { level: 'ok', issues: [], mqtt: { connected: true }, version: 'v1' }; + assert.equal(panel.level, 'ok'); + assert.equal(panel.chipLabel, 'status.ok'); + assert.equal(panel.chipShort, 'status.ready_short'); + assert.equal(panel.rows[0].key, 'mqtt'); + assert.equal(panel.rows[0].value, 'status.mqtt.connected'); +}); + +test('chip names a single issue and its row is left out', () => { + const panel = createPanel(); + panel.status = { + level: 'warn', + issues: [{ key: 'undervoltage', level: 'warn' }], + node: { telemetry: { undervoltage_now: true } }, + version: 'v1', + }; + assert.equal(panel.level, 'warn'); + assert.equal(panel.chipLabel, 'status.issue.undervoltage.chip'); + assert.equal(panel.chipShort, 'status.issue.undervoltage.chip'); + assert.equal(panel.issues[0].label, 'status.issue.undervoltage.label'); + assert.equal(panel.issues[0].value, 'status.issue.undervoltage.value'); + assert.equal(panel.rows.some(row => row.key === 'undervoltage'), false); +}); + +test('chip counts several issues, bad ones first', () => { + const panel = createPanel(); + panel.status = { + level: 'bad', + issues: [ + { key: 'service_down', level: 'warn', params: { service: 'tuya' } }, + { key: 'mqtt_disconnected', level: 'bad' }, + ], + mqtt: { connected: false }, + }; + assert.equal(panel.level, 'bad'); + assert.equal(panel.chipLabel, 'status.count.bad#2'); + assert.deepEqual(panel.issues.map(issue => issue.key), ['mqtt_disconnected', 'service_down']); + assert.equal(panel.issues[1].chip, 'status.issue.service_down.chip|{"service":"tuya"}'); + assert.equal(panel.rows.some(row => row.key === 'mqtt'), false); +}); + +test('chip counts only warnings when no issue is bad', () => { + const panel = createPanel(); + panel.status = { + level: 'warn', + issues: [ + { key: 'cpu_hot', level: 'warn', params: { value: 81.2 } }, + { key: 'ram_full', level: 'warn', params: { value: 93 } }, + ], + node: { telemetry: { cpu_temp_c: 81.2, ram_used_pct: 93 } }, + }; + assert.equal(panel.chipLabel, 'status.count.warn#2'); +}); + +test('chip shows unavailable when health fails', () => { + const panel = createPanel(); + panel.error = 'HTTP 502'; + panel.status = null; + assert.equal(panel.level, 'bad'); + assert.equal(panel.chipLabel, 'status.unavailable'); + assert.equal(panel.rows.length, 0); +}); + +test('chip is loading before the first answer', () => { + const panel = createPanel(); + assert.equal(panel.level, 'loading'); + assert.equal(panel.chipLabel, 'status.loading'); +}); + +test('rows show a dash for null telemetry and leave out undefined telemetry', () => { + const panel = createPanel(); + panel.status = { level: 'ok', issues: [], node: { telemetry: { cpu_temp_c: null } } }; + const cpu = panel.rows.find(row => row.key === 'cpu_temp'); + assert.equal(cpu.value, '-'); + assert.equal(panel.rows.some(row => row.key === 'cpu_load'), false); + assert.equal(panel.rows.some(row => row.key === 'ram'), false); +}); + +test('no node means no undervoltage row', () => { + const panel = createPanel(); + panel.status = { level: 'ok', issues: [], version: 'v1' }; + assert.equal(panel.rows.some(row => row.key === 'undervoltage'), false); + assert.equal(panel.rows.some(row => row.key === 'cpu_temp'), false); +}); + +test('rows show the undervoltage state with the voltage keys', () => { + const panel = createPanel(); + panel.status = { level: 'ok', issues: [], node: { telemetry: { undervoltage_now: false } } }; + const row = panel.rows.find(entry => entry.key === 'undervoltage'); + assert.equal(row.label, 'status.label.voltage'); + assert.equal(row.value, 'status.voltage.ok'); +}); From ce581a532b38e457082fd55c1c2a60a47c7c8d1e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:53:52 +0100 Subject: [PATCH 07/20] fix(dashboard): format the status chip values for the locale Co-Authored-By: Claude Sonnet 5.5 --- .../internal/webui/static/js/dashboard.js | 28 ++++++++++++++----- dashboard/test/dashboard.status-chip.test.mjs | 14 ++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/dashboard/internal/webui/static/js/dashboard.js b/dashboard/internal/webui/static/js/dashboard.js index 2b6359679..d2db1257c 100644 --- a/dashboard/internal/webui/static/js/dashboard.js +++ b/dashboard/internal/webui/static/js/dashboard.js @@ -770,6 +770,17 @@ const STATUS_ROWS = ['mqtt', 'cache', 'storage', 'uptime', 'version', 'cpu_temp', 'cpu_load', 'ram', 'undervoltage']; const STATUS_ISSUE_ROW = {mqtt_disconnected: 'mqtt', cache_error: 'cache', storage_error: 'storage', undervoltage: 'undervoltage', cpu_hot: 'cpu_temp', ram_full: 'ram'}; + // Dezimalstellen der numerischen Werte in einer Stoerung. Der Server liefert + // die Zahl roh, der Text soll das Locale-Dezimalzeichen zeigen. + const STATUS_ISSUE_DECIMALS = {cpu_hot: 1, ram_full: 0}; + const localizedParams = issue => { + const params = issue.params; + const decimals = STATUS_ISSUE_DECIMALS[issue.key]; + if (!params || typeof params.value !== 'number' || decimals === undefined) return params; + if (!window.I18n || typeof window.I18n.formatNumber !== 'function') return params; + return {...params, value: window.I18n.formatNumber(params.value, decimals)}; + }; + const runtimeStatusPanel = () => ({ open: false, enabled: true, @@ -793,13 +804,16 @@ // (bad vor warn, sonst Reihenfolge) haelt den Chip auch bei anderer // Quelle richtig. return (this.status?.issues || []) - .map(issue => ({ - key: issue.key, - level: issue.level, - chip: t(`status.issue.${issue.key}.chip`, issue.params), - label: t(`status.issue.${issue.key}.label`, issue.params), - value: t(`status.issue.${issue.key}.value`, issue.params), - })) + .map(issue => { + const params = localizedParams(issue); + return { + key: issue.key, + level: issue.level, + chip: t(`status.issue.${issue.key}.chip`, params), + label: t(`status.issue.${issue.key}.label`, params), + value: t(`status.issue.${issue.key}.value`, params), + }; + }) .sort((a, b) => (a.level === 'bad' ? 0 : 1) - (b.level === 'bad' ? 0 : 1)); }, diff --git a/dashboard/test/dashboard.status-chip.test.mjs b/dashboard/test/dashboard.status-chip.test.mjs index 250036f0d..af4f77984 100644 --- a/dashboard/test/dashboard.status-chip.test.mjs +++ b/dashboard/test/dashboard.status-chip.test.mjs @@ -19,6 +19,7 @@ const source = fs.readFileSync( const stubI18n = { t: (key, params) => (params ? `${key}|${JSON.stringify(params)}` : key), tn: (key, n) => `${key}#${n}`, + formatNumber: (value, digits) => value.toFixed(digits).replace('.', ','), }; function createPanel() { @@ -129,3 +130,16 @@ test('rows show the undervoltage state with the voltage keys', () => { assert.equal(row.label, 'status.label.voltage'); assert.equal(row.value, 'status.voltage.ok'); }); + +test('cpu_hot and ram_full values reach the catalog in the locale number format', () => { + const panel = createPanel(); + panel.status = { + level: 'warn', + issues: [ + { key: 'cpu_hot', level: 'warn', params: { value: 81.2 } }, + { key: 'ram_full', level: 'warn', params: { value: 93 } }, + ], + }; + assert.equal(panel.issues[0].value, 'status.issue.cpu_hot.value|{"value":"81,2"}'); + assert.equal(panel.issues[1].value, 'status.issue.ram_full.value|{"value":"93"}'); +}); From d28e19e32e7e9e7e6e360be189f8354ba7bd4d6e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:56:13 +0100 Subject: [PATCH 08/20] style(dashboard): style the title row and the status chip Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/static/css/base.css | 143 +++++++++++++++++-- 1 file changed, 128 insertions(+), 15 deletions(-) diff --git a/dashboard/internal/webui/static/css/base.css b/dashboard/internal/webui/static/css/base.css index 7f9f9a982..cf98df94b 100644 --- a/dashboard/internal/webui/static/css/base.css +++ b/dashboard/internal/webui/static/css/base.css @@ -248,40 +248,153 @@ body { font-family: system-ui, sans-serif; padding: 2rem 1.5rem; background: var Breite und linksbuendig. Typo nach apple-design Abschnitt 15: grosser Display-Text bekommt negatives Tracking und enges Leading, Praesenz kommt ueber das Gewicht statt ueber noch mehr Groesse. */ -.masthead { margin-bottom: 1.5rem; } -.masthead-title { display: flex; align-items: baseline; flex-wrap: wrap; gap: .55rem; } +/* Titelzeile: Titel, Untertitel, Status und Sprache in einer Reihe. Der + Titel bekommt die Breite des laengsten Wortes plus den Rest, der Untertitel + kuerzt sich zuerst. Passt nichts mehr neben den Titel, rutschen Status und + Sprache in eine zweite Zeile. */ +.masthead { + position: relative; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: .5rem .6rem; + margin-bottom: 0; + min-height: 2rem; +} +.masthead-title { display: contents; } .masthead h1 { - margin: 0 0 .15rem; - font-size: clamp(1.6rem, 1.2rem + 1.8vw, 2.15rem); - line-height: 1.05; - letter-spacing: -0.021em; - font-weight: 640; + order: 0; + flex: 1000 1 min-content; + max-width: max-content; + min-width: 0; + margin: 0; + font-size: clamp(1.25rem, 1.05rem + .7vw, 1.5rem); + line-height: 1.15; + letter-spacing: -.018em; + font-weight: 650; font-optical-sizing: auto; + overflow-wrap: break-word; color: var(--text-strong); text-wrap: balance; } .masthead small { + order: 1; + flex: 1 1 0; + min-width: 0; display: block; - font-size: .85rem; + padding-top: .2em; + font-size: .82rem; color: var(--text-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } /* Titel, Untertitel und Sprachwaehler lassen sich einzeln ausblenden (Einstellungen > Darstellung > Kopfzeile). Sind alle drei aus, faellt die - Kopfzeile samt Abstand weg. */ + Kopfzeile samt Abstand weg. Der Statuschip zaehlt nur, solange er sichtbar + ist (x-show setzt display: none). */ .masthead [hidden] { display: none; } -.masthead:not(:has(h1:not([hidden]), small:not([hidden]), .lang-pill:not([hidden]))) { display: none; } +.masthead:not(:has(h1:not([hidden]), small:not([hidden]), .lang-pill:not([hidden]), .status-chip-wrap:not([style*="display: none"]))) { display: none; } +/* Rechts in der Titelzeile: Statuschip und Sprachwaehler. */ +.masthead-tools { order: 2; display: flex; align-items: center; gap: .6rem; flex: none; margin-left: auto; } +.status-chip-wrap { display: inline-flex; position: relative; flex: none; } + +/* Status-Chip: zeigt den Gesamtzustand, der Klick oeffnet das Popover. */ +.status-chip { + display: inline-flex; + align-items: center; + gap: .45rem; + height: 1.85rem; + padding: 0 .75rem; + border: 1px solid var(--border-soft); + border-radius: 999px; + background: var(--panel); + color: var(--text-muted); + font: inherit; + font-size: .8rem; + font-weight: 600; + white-space: nowrap; + cursor: pointer; + -webkit-tap-highlight-color: transparent; + transition: color .2s ease, background-color .2s ease, border-color .2s ease, transform .12s var(--ease-out); +} +.status-chip:active { transform: scale(.97); } +.status-chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +@media (hover: hover) and (pointer: fine) { + .status-chip:hover { border-color: var(--border); color: var(--text-subtle); } +} +.status-chip-dot { width: .45rem; height: .45rem; flex: none; border-radius: 50%; background: var(--ok); transition: background-color .2s ease, box-shadow .25s ease; } +.status-chip-short { display: none; } +.status-chip.is-loading .status-chip-dot { background: var(--text-faint); } +.status-chip.is-warn { color: var(--warn); background: var(--warn-bg); border-color: color-mix(in srgb, var(--warn-line) 60%, transparent); } +.status-chip.is-warn .status-chip-dot { background: var(--warn); box-shadow: 0 0 0 3px color-mix(in srgb, var(--warn) 22%, transparent); } +.status-chip.is-bad { color: var(--bad); background: var(--bad-bg); border-color: var(--bad-line); } +.status-chip.is-bad .status-chip-dot { background: var(--bad); box-shadow: 0 0 0 3px color-mix(in srgb, var(--bad) 22%, transparent); } + +/* Popover am Chip: waechst aus der Chip-Ecke, durchscheinendes Material. */ +.status-pop { + position: absolute; + top: calc(100% + .5rem); + right: 0; + z-index: 40; + width: min(18rem, calc(100vw - 2rem)); + padding: .35rem; + border: 1px solid var(--border-soft); + border-radius: 14px; + background: color-mix(in srgb, var(--panel-alt) 86%, transparent); + -webkit-backdrop-filter: blur(18px) saturate(160%); + backdrop-filter: blur(18px) saturate(160%); + box-shadow: 0 12px 32px rgb(0 0 0 / .45); + transform-origin: top right; + font-size: .8rem; + color: var(--text-subtle); +} +.status-row { display: flex; justify-content: space-between; gap: .75rem; padding: .32rem .55rem; border-radius: 8px; } +.status-row strong { color: var(--text); font-weight: 600; text-align: right; } +.status-row.is-warn { background: var(--warn-bg); } +.status-row.is-warn span, .status-row.is-warn strong { color: var(--warn); } +.status-row.is-bad { background: var(--bad-bg); } +.status-row.is-bad span, .status-row.is-bad strong { color: var(--bad); } +.status-sep { height: 1px; margin: .3rem .55rem; background: var(--border-soft); } +.status-link { display: block; width: 100%; padding: .32rem .55rem; border: 0; border-radius: 8px; background: none; color: var(--accent); font: inherit; font-weight: 600; text-align: left; cursor: pointer; } +@media (hover: hover) and (pointer: fine) { + .status-link:hover { background: color-mix(in srgb, var(--accent) 10%, transparent); } +} +.status-pop-enter { transition: opacity .16s var(--ease-out), transform .2s var(--ease-out); } +.status-pop-leave { transition: opacity .12s var(--ease-out), transform .12s var(--ease-out); } +.status-pop-from { opacity: 0; transform: scale(.96) translateY(-4px); } +.status-pop-to { opacity: 1; transform: none; } + +/* Schmal: das Popover haengt an der Kopfzeile statt am Chip, damit es nicht + links aus dem Bild ragt. Der Untertitel entfaellt, der Chip zeigt die + Kurzform. */ +@media (max-width: 640px) { + .status-chip-wrap { position: static; } + .status-pop { width: min(20rem, 100%); } + .masthead small { display: none; } + .status-chip-long { display: none; } + .status-chip-short { display: inline; } +} +/* Weniger Bewegung, weniger Transparenz. */ +@media (prefers-reduced-motion: reduce) { + .status-pop-from { transform: none; } + .status-pop-enter, .status-pop-leave { transition: opacity .15s ease; } +} +@media (prefers-reduced-transparency: reduce) { + .status-pop { background: var(--panel-alt); -webkit-backdrop-filter: none; backdrop-filter: none; } +} /* Sprachwaehler (lang-pill.html): die DE | EN-Pille aus dem Installer als - echte Radiogruppe. Sitzt am Ende der Titelzeile (margin-left: auto) und - bricht auf schmalen Schirmen mit ihr um, statt absolut ueber dem Titel zu - liegen. Der Daumen gleitet mit derselben Kurve wie .segmented, Prozent- - Schritte beziehen sich auf die Daumenbreite = eine Option. */ + echte Radiogruppe. Sitzt in .masthead-tools neben dem Statuschip und + bricht auf schmalen Schirmen mit der Titelzeile um, statt absolut ueber dem + Titel zu liegen. Der Daumen gleitet mit derselben Kurve wie .segmented, + Prozent-Schritte beziehen sich auf die Daumenbreite = eine Option. */ .lang-pill { --lang-count: 2; position: relative; display: inline-grid; grid-template-columns: repeat(var(--lang-count), 1fr); align-self: center; - margin-left: auto; + margin-left: 0; padding: .2rem; border: 1px solid var(--border-soft); border-radius: 999px; From 28ca2c55262fc706da2b58160c7e717a9bd8cccc Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:58:27 +0100 Subject: [PATCH 09/20] test(dashboard): check that the title row never truncates Co-Authored-By: Claude Sonnet 5.5 --- dashboard/test/browser/README.md | 1 + dashboard/test/browser/title-row.mjs | 92 ++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 dashboard/test/browser/title-row.mjs diff --git a/dashboard/test/browser/README.md b/dashboard/test/browser/README.md index 9a13872d3..20032bb02 100644 --- a/dashboard/test/browser/README.md +++ b/dashboard/test/browser/README.md @@ -18,6 +18,7 @@ Konsole des Starts. | `docs-screenshots.mjs` | Die Bilder fuer `docs/images/` neu aufnehmen | `demo/demo.sh --docs --no-simulate`, dann `node dashboard/test/browser/docs-screenshots.mjs`. Mit `--history` zusaetzlich den Verlauf (ca. 12 min). Die Karten fuer `docs/dashboard/overview-cards.md`: `demo/demo.sh --docs`, dann `node dashboard/test/browser/docs-screenshots.mjs --cards` | | `history-view-tile.mjs` | Prueft, dass Verlaufskacheln den Live-Tausch ueberleben (Gruppe Verlauf und Statistik) | `node dashboard/test/browser/history-view-tile.mjs` | | `mobile-overflow.mjs` | Prueft Tabs und Breiten auf horizontales Ueberlaufen | `node dashboard/test/browser/mobile-overflow.mjs --widths 400,1280 overview settings energy devicemap stats` | +| `title-row.mjs` | Prueft, dass die Titelzeile nie abschneidet und der Werkzeugblock in einer Zeile bleibt (390 und 1280 px) | `node dashboard/test/browser/title-row.mjs` | | `onboarding-steps.mjs` | Prueft je Einrichtungsschritt, ob das Spotlight auf dem Ziel liegt (Desktop und Handy) | `node dashboard/test/browser/onboarding-steps.mjs --widths 1280,390` | | `measure-client-cost.mjs` | Misst die Kosten eines offenen Uebersichts-Tabs im Leerlauf | `node dashboard/test/browser/measure-client-cost.mjs --seconds 30` | diff --git a/dashboard/test/browser/title-row.mjs b/dashboard/test/browser/title-row.mjs new file mode 100644 index 000000000..1703355da --- /dev/null +++ b/dashboard/test/browser/title-row.mjs @@ -0,0 +1,92 @@ +#!/usr/bin/env node +// Prüft an der laufenden Demo (demo/demo.sh), dass die Titelzeile nie abschneidet +// und der Werkzeugblock nie umbricht. Je Breite wird der Titel gesetzt und gemessen: +// kein text-overflow: ellipsis, kein Überlauf des

, alle Kinder von +// .masthead-tools in einer Zeile. Ausgabe je Prüfung eine Zeile, Exit 1 bei Fehler. +// +// node dashboard/test/browser/title-row.mjs +// node dashboard/test/browser/title-row.mjs --url https://localhost:18200 --password smoketest1234 +import { chromium } from 'playwright'; + +function parseArgs(argv) { + const args = { url: 'https://localhost:18200', password: 'smoketest1234' }; + for (let i = 0; i < argv.length; i++) { + const [flag, inlineValue] = argv[i].split(/=(.*)/s); + const value = inlineValue ?? argv[++i]; + if (flag === '--url') args.url = value.replace(/\/$/, ''); + else if (flag === '--password') args.password = value; + else throw new Error(`unbekannte Option: ${flag}`); + } + return args; +} + +const SHORT_TITLE = 'Werkstatt Energiezentrale Nord'; +const LONG_TITLE = 'Energiezentrale Nord mit einem langen Titel fuer den Breitentest, Haus Ost'.slice(0, 64); + +const checks = [ + { width: 390, label: 'Handy', title: SHORT_TITLE }, + { width: 1280, label: 'Desktop, 64 Zeichen', title: LONG_TITLE }, +]; + +const measure = page => page.evaluate(() => { + const h1 = document.querySelector('h1[data-masthead-title]'); + const tools = document.querySelector('.masthead-tools'); + const style = getComputedStyle(h1); + const boxes = tools ? [...tools.children].filter(el => el.offsetParent !== null).map(el => el.getBoundingClientRect()) : []; + // Umbruch: zwei Kinder überlappen sich in der Senkrechten nicht. + const wrapped = boxes.some((a, i) => boxes.some((b, j) => j > i && (a.bottom <= b.top || b.bottom <= a.top))); + return { + textOverflow: style.textOverflow, + scrollWidth: h1.scrollWidth, + clientWidth: h1.clientWidth, + wrapped, + toolsCount: boxes.length, + }; +}); + +const args = parseArgs(process.argv.slice(2)); +const browser = await chromium.launch({ args: ['--no-sandbox'] }); +let failed = false; +try { + for (const { width, label, title } of checks) { + const ctx = await browser.newContext({ + ignoreHTTPSErrors: true, + extraHTTPHeaders: { 'X-Forwarded-Proto': 'https' }, + viewport: { width, height: 860 }, + }); + await ctx.request.post(`${args.url}/api/v1/auth/login`, { data: { username: 'admin', password: args.password } }); + const page = await ctx.newPage(); + await page.goto(`${args.url}/`, { waitUntil: 'networkidle' }); + await page.waitForSelector('#login-form', { state: 'detached', timeout: 15000 }).catch(() => {}); + await page.waitForTimeout(1000); + await page.evaluate(text => { + document.querySelector('h1[data-masthead-title]').textContent = text; + }, title); + await page.waitForTimeout(300); + const m = await measure(page); + const tag = `${width}px ${label} (${title.length} Zeichen)`; + + if (m.textOverflow === 'ellipsis') { + failed = true; + console.log(`FEHL ${tag}: text-overflow ist ellipsis`); + } else { + console.log(`OK ${tag}: text-overflow ${m.textOverflow}`); + } + if (m.scrollWidth > m.clientWidth + 1) { + failed = true; + console.log(`FEHL ${tag}: h1 scrollWidth ${m.scrollWidth} > clientWidth ${m.clientWidth}`); + } else { + console.log(`OK ${tag}: h1 ohne Überlauf (${m.scrollWidth}/${m.clientWidth} px)`); + } + if (m.wrapped) { + failed = true; + console.log(`FEHL ${tag}: .masthead-tools bricht um (Kinder überlappen sich nicht in der Senkrechten, ${m.toolsCount} Kinder)`); + } else { + console.log(`OK ${tag}: .masthead-tools in einer Zeile (${m.toolsCount} Kinder)`); + } + await ctx.close(); + } +} finally { + await browser.close(); +} +process.exit(failed ? 1 : 0); From 10a1384b39e3b4a477c6935f8fc454375d7b421f Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:01:14 +0100 Subject: [PATCH 10/20] style(dashboard): give update, guest and example notes one slim row form Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/static/css/base.css | 87 +++++++++++++++---- .../internal/webui/static/css/onboarding.css | 85 +++--------------- 2 files changed, 79 insertions(+), 93 deletions(-) diff --git a/dashboard/internal/webui/static/css/base.css b/dashboard/internal/webui/static/css/base.css index cf98df94b..e5c9ed002 100644 --- a/dashboard/internal/webui/static/css/base.css +++ b/dashboard/internal/webui/static/css/base.css @@ -480,6 +480,7 @@ body { font-family: system-ui, sans-serif; padding: 2rem 1.5rem; background: var @media (prefers-reduced-motion: no-preference) { .update-badge-enter { transition: opacity .2s var(--ease-out), transform .2s var(--ease-out); } .update-badge-enter-start { opacity: 0; transform: scale(.95) translateY(-2px); } + .update-bar.update-badge-enter-start { transform: translateY(-4px); } .update-badge-enter-end { opacity: 1; transform: scale(1) translateY(0); } } @media (prefers-reduced-motion: reduce) { @@ -1274,20 +1275,69 @@ table.energy-board-table tr.is-stale td { color: var(--text-faint); } .history-view-plot { position: relative; overflow: hidden; } .license-footer { margin-top: 2.5rem; padding-top: .75rem; border-top: 1px solid var(--border-soft); color: var(--text-muted); font-size: .8rem; } .license-footer p { margin: 0; } -/* Update-Leiste unter dem Masthead (update-bar.js). Gleiche Kartenform wie - .runtime-status, Rahmen und Grund tragen den Zustand. */ -.update-bar { display: flex; align-items: center; gap: .8rem; flex-wrap: wrap; margin-top: 1rem; padding: .65rem .9rem; border: 1px solid var(--accent-line); border-radius: 12px; background: color-mix(in srgb, var(--accent) 5%, var(--panel)); box-shadow: 0 1px 3px rgba(0, 0, 0, .25); } -.update-bar-icon { width: 1.1rem; height: 1.1rem; flex: none; fill: none; stroke: var(--accent); stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; } -.update-bar-main { flex: 1 1 16rem; min-width: 0; } -.update-bar-title { color: var(--text-strong); font-weight: 600; } -.update-bar-detail { color: var(--text-muted); font-size: .82rem; margin-top: .1rem; overflow-wrap: anywhere; } -.update-bar-track { height: 4px; margin-top: .45rem; border-radius: 2px; background: var(--panel-alt); overflow: hidden; } -.update-bar-fill { height: 100%; border-radius: 2px; background: var(--accent); transition: width .4s var(--ease-out); } -.update-bar-actions { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; } -.update-bar-button { display: inline-flex; align-items: center; gap: .35rem; padding: .35rem .75rem; border: 1px solid var(--border); border-radius: 8px; background: transparent; color: var(--text); font: inherit; font-size: .82rem; font-weight: 600; text-decoration: none; white-space: nowrap; cursor: pointer; } -.update-bar-button.is-primary { border-color: var(--accent-line); background: var(--accent-bg); color: var(--accent); } -.update-bar-button.is-ok { border-color: color-mix(in srgb, var(--ok) 50%, transparent); background: color-mix(in srgb, var(--ok) 14%, transparent); color: var(--ok); } -.update-bar-link { color: var(--accent); font-size: .82rem; text-decoration: none; white-space: nowrap; } +/* Hinweiszeilen: Update-Leiste, Gast- und Beispielhinweis teilen eine Zeilenform + (Rahmen, Radius, Hoehe, Innenabstand, Schrift). Icon, Titel mit "· Detail" und + Aktionen stehen in einer Reihe, der Fortschritt fuellt die Zeile selbst. + Die Toene fuer Gast und Beispiel stehen in onboarding.css. */ +.update-bar, +.ob-guest-note, +.example-note { + position: relative; + isolation: isolate; + overflow: hidden; + display: flex; + align-items: center; + flex-wrap: nowrap; + gap: .6rem; + box-sizing: border-box; + min-height: 2.6rem; + margin-top: .75rem; + padding: .3rem .35rem .3rem .8rem; + border-radius: 12px; + box-shadow: none; + font-size: .86rem; + line-height: 1.35; +} +.update-bar { border: 1px solid color-mix(in srgb, var(--accent-line) 55%, transparent); background: color-mix(in srgb, var(--accent) 6%, var(--panel)); } +.update-bar-icon, +.ob-guest-note-icon, +.example-note-icon { width: 1rem; height: 1rem; margin: 0; align-self: center; flex: none; } +.update-bar-icon { fill: none; stroke: var(--accent); stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; } +.update-bar-main, +.example-note-main { flex: 1 1 auto; min-width: 0; display: flex; align-items: baseline; gap: .4rem; white-space: nowrap; overflow: hidden; } +.update-bar-title, +.example-note-title { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; color: var(--text-strong); font-weight: 600; } +.update-bar-detail, +.example-note-detail { flex: 0 1000 auto; min-width: 0; margin: 0; overflow: hidden; text-overflow: ellipsis; color: var(--text-muted); font-size: inherit; overflow-wrap: normal; } +.update-bar-detail:not(:empty)::before, +.example-note-detail::before { content: '· '; } +.update-bar-track { position: absolute; inset: 0; z-index: -1; height: auto; margin: 0; border-radius: 0; background: transparent; overflow: hidden; } +.update-bar-fill { height: 100%; border-radius: 0; background: color-mix(in srgb, var(--accent) 14%, transparent); transition: width .5s var(--ease-out); } +.update-bar-actions, +.example-note-actions { display: flex; align-items: center; flex: none; flex-wrap: nowrap; gap: .25rem; } +.update-bar-button, +.update-bar-link, +.example-note-btn { display: inline-flex; align-items: center; gap: .3rem; height: 1.9rem; padding: 0 .75rem; border: 0; border-radius: 999px; background: transparent; color: var(--accent); font: inherit; font-size: .82rem; font-weight: 600; white-space: nowrap; text-decoration: none; cursor: pointer; transition: background-color .18s ease, transform .12s var(--ease-out); } +.update-bar-button:active, +.example-note-btn:active:not(:disabled) { transform: scale(.97); } +@media (hover: hover) and (pointer: fine) { + .update-bar-button:hover, + .update-bar-link:hover, + .example-note-btn:hover:not(:disabled) { background: color-mix(in srgb, var(--accent) 10%, transparent); } + .update-bar-button.is-primary:hover { background: color-mix(in srgb, var(--accent) 86%, white); } +} +.update-bar-button.is-primary { background: var(--accent); color: var(--accent-ink); } +.update-bar-button.is-ok { color: var(--ok); } +.ob-guest-note p { margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +/* Schmal: nur die Hauptaktion bleibt, die Nebenwege entfallen. */ +@media (max-width: 640px) { + .update-bar-detail, + .example-note-detail { display: none; } + .update-bar:has(.is-primary:not([style*="none"])) .update-bar-button:not(.is-primary), + .update-bar:has(.is-primary:not([style*="none"])) .update-bar-link { display: none !important; } + .example-note-btn:not(.is-primary) { display: none; } + .ob-guest-note p { white-space: normal; } +} /* Neuerungen: Versionsmarken und Eintraege, auch von der Versionsseite genutzt. */ .version-tag { color: var(--text-strong); font-variant-numeric: tabular-nums; font-weight: 600; font-size: .9rem; } .version-chip { @@ -1353,13 +1403,14 @@ table.energy-board-table tr.is-stale td { color: var(--text-faint); } .whatsnew-summary:active { transform: none; } .whatsnew-shot::after { animation: none; } } -.update-bar-dismiss { padding: 0 .2rem; border: 0; background: none; color: var(--text-muted); font-size: 1.1rem; cursor: pointer; } -.update-bar-restarting { border-color: color-mix(in srgb, var(--warn) 50%, transparent); } +.update-bar-dismiss { width: 1.9rem; height: 1.9rem; padding: 0 .2rem; border: 0; border-radius: 999px; background: none; color: var(--text-muted); font-size: 1.1rem; cursor: pointer; } +.update-bar-restarting { border-color: color-mix(in srgb, var(--warn) 45%, transparent); } .update-bar-restarting .update-bar-icon { stroke: var(--warn); } -.update-bar-ok { border-color: color-mix(in srgb, var(--ok) 55%, transparent); background: color-mix(in srgb, var(--ok) 7%, var(--panel)); } +.update-bar-ok { border-color: color-mix(in srgb, var(--ok) 45%, transparent); background: color-mix(in srgb, var(--ok) 6%, var(--panel)); } .update-bar-ok .update-bar-icon { stroke: var(--ok); stroke-width: 2.4; } -.update-bar-fail { border-color: color-mix(in srgb, var(--bad) 55%, transparent); background: color-mix(in srgb, var(--bad) 7%, var(--panel)); } +.update-bar-fail { border-color: color-mix(in srgb, var(--bad) 50%, transparent); background: color-mix(in srgb, var(--bad) 6%, var(--panel)); } .update-bar-fail .update-bar-icon { stroke: var(--bad); stroke-width: 2.4; } +@media (prefers-reduced-motion: reduce) { .update-bar-fill { transition: none; } } @media (prefers-reduced-motion: no-preference) { .update-bar-spin { transform-origin: 12px 12px; animation: update-bar-spin 1.1s linear infinite; } } diff --git a/dashboard/internal/webui/static/css/onboarding.css b/dashboard/internal/webui/static/css/onboarding.css index 7f638cb49..6e33d603f 100644 --- a/dashboard/internal/webui/static/css/onboarding.css +++ b/dashboard/internal/webui/static/css/onboarding.css @@ -380,90 +380,25 @@ button.ob-crosslink { font: inherit; cursor: pointer; } .ob-bar.is-collapsed .ob-bar-state { visibility: hidden; transition: visibility 0s .3s; } } -/* --- Gast-Hinweis --------------------------------------------------------- */ -.ob-guest-note { - display: flex; - align-items: flex-start; - gap: .7rem; - margin-top: 1rem; - padding: .75rem 1rem; - border: 1px solid color-mix(in srgb, var(--info-line) 70%, transparent); - border-radius: 12px; - background: var(--info-bg); - color: var(--text); - font-size: .92rem; - line-height: 1.45; -} -.ob-guest-note p { margin: 0; text-wrap: pretty; } +/* --- Gast-Hinweis und Hinweis zum Beispiel -------------------------------- + Zeilenform und Layout stehen in base.css (Hinweiszeilen). Hier nur der + Infoton, die Rueckmeldung und das Einblenden. */ +.ob-guest-note, +.example-note { border: 1px solid color-mix(in srgb, var(--info) 30%, transparent); background: color-mix(in srgb, var(--info) 6%, var(--panel)); color: var(--text-subtle); } +.ob-guest-note { padding-right: .8rem; } .ob-guest-note strong { color: var(--text-strong); } -.ob-guest-note-icon { flex: none; width: 1.15rem; height: 1.15rem; margin-top: .1rem; fill: none; stroke: var(--info); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } -@media (prefers-reduced-motion: no-preference) { - .ob-guest-note { animation: masthead-rise .42s var(--ease-out) both; } -} - -/* --- Hinweis zum Beispiel ------------------------------------------------ - Gleiche Bauweise wie die Update-Leiste: Icon, Text (Titel plus Zeile - darunter), Aktionen rechts in derselben Reihe. Schmal stehen die Aktionen - unter dem Text. Die Hauptaktion traegt den Ton, die zweite bleibt leise. */ -.example-note { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: .6rem .9rem; - margin-top: 1rem; - padding: .65rem .9rem; - border: 1px solid color-mix(in srgb, var(--info-line) 55%, transparent); - border-radius: 12px; - background: var(--info-bg); - color: var(--text); - font-size: .92rem; - line-height: 1.4; -} -.example-note-icon { flex: none; width: 1.15rem; height: 1.15rem; fill: none; stroke: var(--info); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } -.example-note-main { flex: 1 1 18rem; min-width: 0; } -.example-note-title { color: var(--text-strong); font-weight: 600; } -.example-note-detail { margin-top: .1rem; color: var(--text-muted); font-size: .82rem; text-wrap: pretty; } +.ob-guest-note-icon, +.example-note-icon { fill: none; stroke: var(--info); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } .example-note-msg { margin: .4rem 0 0; color: var(--text); font-size: .82rem; text-wrap: pretty; } .example-note-msg[hidden] { display: none; } -.example-note-actions { display: flex; align-items: center; flex-wrap: wrap; gap: .5rem; } -.example-note-btn { - display: inline-flex; - align-items: center; - justify-content: center; - padding: .35rem .75rem; - border: 1px solid transparent; - border-radius: 8px; - background: transparent; - color: var(--text-muted); - font: inherit; - font-size: .82rem; - font-weight: 600; - white-space: nowrap; - cursor: pointer; - -webkit-tap-highlight-color: transparent; - transition: background-color .15s ease, border-color .15s ease, color .15s ease, transform .1s var(--ease-out), opacity .15s ease; -} -.example-note-btn.is-primary { border-color: color-mix(in srgb, var(--info-line) 60%, transparent); background: color-mix(in srgb, var(--info) 14%, transparent); color: var(--info); } -.example-note-btn:active:not(:disabled) { transform: scale(.97); } +.example-note-btn.is-primary { color: var(--accent); } .example-note-btn:disabled { opacity: .5; cursor: progress; } .example-note-btn:focus-visible { outline: 2px solid var(--info); outline-offset: 2px; } -@media (hover: hover) and (pointer: fine) { - .example-note-btn:hover:not(:disabled) { color: var(--text-strong); background: color-mix(in srgb, var(--info) 10%, transparent); } - .example-note-btn.is-primary:hover:not(:disabled) { color: var(--text-strong); background: color-mix(in srgb, var(--info) 24%, transparent); } -} -/* Schmal: Text oben, die Aktionen darunter ueber die ganze Breite, mit - Tippflaechen von 2.5rem Hoehe. */ -@media (max-width: 640px) { - .example-note-icon { align-self: flex-start; margin-top: .15rem; } - .example-note-main { flex-basis: calc(100% - 2.4rem); } - .example-note-actions { flex: 1 1 100%; flex-direction: column; align-items: stretch; } - .example-note-btn { min-height: 2.5rem; } - .example-note-btn:not(.is-primary) { border-color: var(--border); color: var(--text); } -} /* Die Rueckmeldung blendet kurz ein, statt ploetzlich aufzutauchen. */ .example-note-msg { transition: opacity .2s var(--ease-out), transform .2s var(--ease-out); } @starting-style { .example-note-msg { opacity: 0; transform: translateY(-4px); } } @media (prefers-reduced-motion: no-preference) { + .ob-guest-note, .example-note { animation: masthead-rise .42s var(--ease-out) both; } } @media (prefers-reduced-motion: reduce) { From d2cc2132a050a3e8c04d06c0e7904c5a392d460a Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:04:32 +0100 Subject: [PATCH 11/20] feat(dashboard): slide one tab indicator to the active tab Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/static/css/base.css | 21 ++++++++ .../internal/webui/static/js/dashboard.js | 51 +++++++++++++++++++ dashboard/test/dashboard.nav.test.mjs | 35 +++++++++++++ 3 files changed, 107 insertions(+) diff --git a/dashboard/internal/webui/static/css/base.css b/dashboard/internal/webui/static/css/base.css index e5c9ed002..ed2d66877 100644 --- a/dashboard/internal/webui/static/css/base.css +++ b/dashboard/internal/webui/static/css/base.css @@ -539,6 +539,26 @@ nav .nav-more-list button.active { background: var(--accent-bg); color: var(--ac .nav-shell[data-nav-mode="more"] nav#dashboard-tabs .tab.is-overflow { display: none !important; } .nav-shell[data-nav-mode="more"] nav#dashboard-tabs .tab-divider { display: none; } .nav-shell[data-nav-mode="menu"] nav#dashboard-tabs .nav-more { display: none; } +/* Gleitende Markierung (dashboard.js, trackNavIndicator): im Modus "Weitere" + wandert eine Linie unter dem aktiven Reiter, die Unterstriche der Reiter + bleiben dafuer eingeklappt. */ +nav#dashboard-tabs { margin-top: 1rem; } +.nav-shell[data-nav-mode="more"] nav#dashboard-tabs > button.tab::after, +.nav-shell[data-nav-mode="more"] nav#dashboard-tabs .nav-more-toggle::after { transform: scaleX(0) !important; } +.nav-indicator { display: none; } +.nav-shell[data-nav-mode="more"] .nav-indicator { + display: block; + position: absolute; + left: 0; + bottom: -1px; + height: 2px; + width: 0; + border-radius: 2px; + background: var(--accent); + pointer-events: none; + opacity: 0; +} +.nav-indicator.is-ready { transition: transform .2s var(--ease-out), width .2s var(--ease-out), opacity .15s ease; } .nav-menu-chevron { width: 0; height: 0; border-left: .35rem solid transparent; border-right: .35rem solid transparent; border-top: .4rem solid currentColor; transition: transform .24s var(--ease-out); } .nav-menu-toggle[aria-expanded="true"] .nav-menu-chevron { transform: rotate(180deg); } section.panel { display: none; } @@ -562,6 +582,7 @@ section.panel.active { display: block; } nav button::after { transition: none; } nav button:active { transform: none; } .nav-menu-chevron { transition: none; } + .nav-indicator.is-ready { transition: opacity .15s ease; } } @keyframes panel-fade { from { opacity: 0; } to { opacity: 1; } } .toolbar { display: flex; gap: .6rem; align-items: center; flex-wrap: wrap; margin: 1rem 0; } diff --git a/dashboard/internal/webui/static/js/dashboard.js b/dashboard/internal/webui/static/js/dashboard.js index d2db1257c..9c252c564 100644 --- a/dashboard/internal/webui/static/js/dashboard.js +++ b/dashboard/internal/webui/static/js/dashboard.js @@ -97,6 +97,14 @@ return count; }; + // Lage und Breite der gleitenden Markierung unter dem aktiven Reiter, in px + // relativ zur Leiste. Die Markierung ist 8 px kuerzer als der Reiter. + const navIndicatorGeometry = (navLeft, targetLeft, targetWidth, scrollLeft, inset = 8) => ({ + x: targetLeft - navLeft + scrollLeft + inset, + width: Math.max(targetWidth - 2 * inset, 8), + }); + window.dashboardNav = { navIndicatorGeometry }; + // Text eines Reiters ohne versteckte Zusaetze (Punkt, "Neu", "Offene // Vorschlaege"): die stehen fuer Screenreader im Reiter, gehoeren aber // nicht in das Menue "Weitere" oder die Titelzeile. @@ -146,6 +154,9 @@ initNav() { const nav = document.getElementById('dashboard-tabs'); if (!nav) return; + // Zweiter Aufruf: Markierung und Beobachter gibt es schon, nicht doppelt anlegen. + if (nav.querySelector('.nav-indicator')) return; + this.trackNavIndicator(nav); const refit = () => this.$nextTick(() => this.fitNav()); window.addEventListener('nav-mode-changed', (event) => { this.navMode = event.detail && event.detail.mode === 'menu' ? 'menu' : 'more'; @@ -168,6 +179,46 @@ refit(); }, + // Eine Markierung, die unter dem aktiven Reiter gleitet (Modus "Weitere"). + // Beobachtet werden nur Klassen und der Modus, keine Kinder: Die Markierung + // selbst und die Liste "Weitere" loesen so kein Neumessen aus. Alle Ausloeser + // laufen in einem Frame, und style wird nur bei geaenderter Lage geschrieben. + trackNavIndicator(nav) { + const shell = nav.closest('.nav-shell'); + const ind = document.createElement('span'); + ind.className = 'nav-indicator'; + ind.setAttribute('aria-hidden', 'true'); + nav.appendChild(ind); + let frame = 0; + let placed = ''; + const place = () => { + frame = 0; + const target = nav.querySelector('button.tab.active:not(.is-overflow)') || nav.querySelector('.nav-more-toggle.active'); + if (!shell || shell.dataset.navMode !== 'more' || !target || !target.offsetWidth) { + if (ind.style.opacity !== '0') ind.style.opacity = '0'; + return; + } + const n = nav.getBoundingClientRect(); + const r = target.getBoundingClientRect(); + const geo = window.dashboardNav.navIndicatorGeometry(n.left, r.left, r.width, nav.scrollLeft); + const key = `${geo.x}|${geo.width}`; + if (key !== placed) { + placed = key; + ind.style.width = `${geo.width}px`; + ind.style.transform = `translateX(${geo.x}px)`; + } + if (ind.style.opacity !== '1') ind.style.opacity = '1'; + }; + const schedule = () => { if (!frame) frame = requestAnimationFrame(place); }; + new MutationObserver(schedule).observe(nav, { attributes: true, attributeFilter: ['class'], subtree: true }); + if (shell) new MutationObserver(schedule).observe(shell, { attributes: true, attributeFilter: ['data-nav-mode'] }); + if (typeof ResizeObserver === 'function') new ResizeObserver(schedule).observe(nav); + document.fonts?.ready?.then(schedule); + place(); + // Erst nach dem ersten Setzen weich, sonst gleitet sie beim Laden von links herein. + requestAnimationFrame(() => requestAnimationFrame(() => ind.classList.add('is-ready'))); + }, + // Misst bei allen Tabs in der Zeile und blendet aus, was nicht passt. Laeuft in // einem Frame, die Zwischenstufe wird nie gemalt. Ein verborgenes Panel hat // keine Breite, dann kommt der ResizeObserver spaeter nochmal. diff --git a/dashboard/test/dashboard.nav.test.mjs b/dashboard/test/dashboard.nav.test.mjs index 28473d2be..868b4c930 100644 --- a/dashboard/test/dashboard.nav.test.mjs +++ b/dashboard/test/dashboard.nav.test.mjs @@ -233,6 +233,8 @@ function createRow({ navWidth, mode = 'more' }) { nav.querySelectorAll('button.tab').forEach((tab) => Object.defineProperty(tab, 'offsetWidth', { value: 100 })); Object.defineProperty(nav.querySelector('.nav-more'), 'offsetWidth', { value: 80 }); component.navMode = mode; + // jsdom ohne Layout-Takt: Frames laufen als Timer, initNav braucht sie. + window.requestAnimationFrame = (fn) => setTimeout(fn, 0); return { component, nav }; } const overflowIds = (nav) => [...nav.querySelectorAll('button.tab.is-overflow')].map((tab) => tab.id); @@ -534,3 +536,36 @@ test('das Aufklappmenue bleibt einspaltig und erreicht jeden Eintrag', () => { assert.match(open, /max-height: 60rem;/); assert.match(open, /overflow-y: auto;/); }); + +// Gleitende Markierung im Modus "Weitere" (dashboard.js, trackNavIndicator). +const plain = (value) => JSON.parse(JSON.stringify(value)); + +test('navIndicatorGeometry legt die Markierung um den Reiter, 8 px kuerzer', () => { + const { window } = createShell(); + const { navIndicatorGeometry } = window.dashboardNav; + assert.deepEqual(plain(navIndicatorGeometry(100, 180, 90, 0)), { x: 88, width: 74 }); + assert.deepEqual(plain(navIndicatorGeometry(0, 0, 10, 0)), { x: 8, width: 8 }); + assert.equal(navIndicatorGeometry(100, 180, 90, 20).x, 108); +}); + +test('initNav zweimal aufgerufen legt nur eine Markierung an', () => { + const { component, nav } = createRow({ navWidth: 250 }); + const window = nav.ownerDocument.defaultView; + component.$nextTick = (fn) => fn(); + component.$watch = () => {}; + component.initNav(); + component.initNav(); + assert.equal(nav.querySelectorAll('.nav-indicator').length, 1); +}); + +test('ein Wechsel des aktiven Reiters misst die Leiste nicht neu', async () => { + const { component, nav } = createRow({ navWidth: 250 }); + const window = nav.ownerDocument.defaultView; + const fits = watchFits(component); + component.initNav(); + await flushObservers(); + const before = fits(); + nav.querySelector('#tab-devices').classList.add('active'); + await flushObservers(); + assert.equal(fits(), before); +}); From 97f7d9200de2ad014562715384e4955f7527e787 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:04:59 +0100 Subject: [PATCH 12/20] docs(dashboard): describe the status chip and bump the changed assets Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/cache-bust-history.csv | 5 +++++ dashboard/internal/webui/templates/base.html | 12 ++++++------ dashboard/internal/webui/webui_test.go | 12 ++++++------ docs/dashboard/index.md | 10 +++++++--- docs/dashboard/settings-appearance.md | 3 +-- 5 files changed, 25 insertions(+), 17 deletions(-) diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index d5e5287bc..01d4b6b93 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,4 +1,9 @@ version,date,asset,v,note +v0.12.1,2026-12-03,css/base.css,56, +v0.12.1,2026-12-03,css/onboarding.css,9, +v0.12.1,2026-12-03,css/settings-controls.css,23, +v0.12.1,2026-12-03,js/dashboard.js,57, +v0.12.1,2026-12-03,js/settings.page.js,46, v0.12.0,2026-12-02,css/storage.css,2,"settings panel, system drive usage broken down into its parts (#252)" v0.12.0,2026-12-02,js/storage.page.js,2,"settings panel, system drive usage broken down into its parts (#252)" v0.11.23-pre.46,2026-12-02,css/settings-controls.css,22, diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 8c193ff7e..c0d53ab96 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -72,8 +72,8 @@ - - + + @@ -240,14 +240,14 @@

{{t "no_access.title"}}

{{if and .Manager (index .Can "view_efficiency")}}

{{t "panel.efficiency_loading"}}

{{end}} {{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} {{if .Manager}} -{{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} +{{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} {{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} {{if index .Can "view_energy"}}

{{t "panel.energy_loading"}}

{{end}} {{if index .Can "view_device_map"}}

{{t "panel.devicemap_loading"}}

{{end}} -

{{t "panel.settings_loading"}}

+

{{t "panel.settings_loading"}}

{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} {{else}} -{{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} +{{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} {{end}}