From f85130f76eef47bca3faa1714a353dd5da7e7760 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:16:23 +0100 Subject: [PATCH 01/34] feat(automations): mark rules that came from a learned suggestion Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/rules.go | 31 ++++++++++---- dashboard/internal/autolearn/rules_test.go | 33 +++++++++++++++ .../internal/config/automation_schema_test.go | 40 +++++++++++++++++++ .../automation/automation_rules.schema.json | 20 ++++++++++ .../automation/tests/test_automation_mqtt.py | 27 +++++++++++++ 5 files changed, 143 insertions(+), 8 deletions(-) diff --git a/dashboard/internal/autolearn/rules.go b/dashboard/internal/autolearn/rules.go index 7f97721f..f3878fad 100644 --- a/dashboard/internal/autolearn/rules.go +++ b/dashboard/internal/autolearn/rules.go @@ -27,6 +27,17 @@ type Rule struct { Actions []Action CooldownSeconds float64 RepeatSeconds float64 + // LearnedFrom is nil when the rule was not made from a learned suggestion. + LearnedFrom *LearnedFrom +} + +// LearnedFrom marks a rule or a scenario that came from a learned suggestion. +// Suggestion is the text of the suggestion, Kind its kind and At the time in +// Unix seconds when it was accepted. +type LearnedFrom struct { + Suggestion string `json:"suggestion"` + Kind string `json:"kind"` + At int64 `json:"at"` } // Condition is one condition of a rule. Threshold is read from threshold of a @@ -113,6 +124,8 @@ type Scenario struct { // Regulator is nil when the scenario has no regulator block. Regulator *RegulatorSpec ActionTopics []string + // LearnedFrom is nil when the scenario was not made from a learned suggestion. + LearnedFrom *LearnedFrom } // RegulatorSpec is the part of a scenario regulator that the learning steps @@ -164,6 +177,7 @@ type wireRule struct { RepeatSeconds float64 `json:"repeat_seconds"` Conditions []json.RawMessage `json:"conditions"` Actions []wireAction `json:"actions"` + LearnedFrom *LearnedFrom `json:"learned_from"` } // wireCondition keeps the fields that may hold a learned reference as raw @@ -209,12 +223,13 @@ type wireAction struct { } type wireScenario struct { - ID string `json:"id"` - Name string `json:"name"` - Enabled bool `json:"enabled"` - OnStart wirePhase `json:"on_start"` - While wireWhile `json:"while"` - OnEnd wirePhase `json:"on_end"` + ID string `json:"id"` + Name string `json:"name"` + Enabled bool `json:"enabled"` + LearnedFrom *LearnedFrom `json:"learned_from"` + OnStart wirePhase `json:"on_start"` + While wireWhile `json:"while"` + OnEnd wirePhase `json:"on_end"` } type wirePhase struct { @@ -250,7 +265,7 @@ func ParseDoc(raw []byte) (Doc, error) { doc := Doc{Location: wire.Settings.location()} for _, wr := range wire.Rules { rule := Rule{ID: wr.ID, Name: wr.Name, Enabled: wr.Enabled, - CooldownSeconds: wr.CooldownSeconds, RepeatSeconds: wr.RepeatSeconds} + CooldownSeconds: wr.CooldownSeconds, RepeatSeconds: wr.RepeatSeconds, LearnedFrom: wr.LearnedFrom} for _, rawCond := range wr.Conditions { condition, err := parseCondition(rawCond) if err != nil { @@ -264,7 +279,7 @@ func ParseDoc(raw []byte) (Doc, error) { doc.Rules = append(doc.Rules, rule) } for _, ws := range wire.Scenarios { - scenario := Scenario{ID: ws.ID, Name: ws.Name, Enabled: ws.Enabled} + scenario := Scenario{ID: ws.ID, Name: ws.Name, Enabled: ws.Enabled, LearnedFrom: ws.LearnedFrom} if wr := ws.While.Regulator; wr != nil { scenario.RegulatorTopic = wr.Output.Topic scenario.Regulator = wr.spec() diff --git a/dashboard/internal/autolearn/rules_test.go b/dashboard/internal/autolearn/rules_test.go index a68e472a..c4068dd0 100644 --- a/dashboard/internal/autolearn/rules_test.go +++ b/dashboard/internal/autolearn/rules_test.go @@ -497,3 +497,36 @@ func TestLearnedReadersFindsRulesOnce(t *testing.T) { t.Fatalf("empty doc: %#v", got) } } + +// TestParseDocReadsLearnedFrom reads learned_from of a rule and of a scenario. +// A rule without the field has no LearnedFrom. +func TestParseDocReadsLearnedFrom(t *testing.T) { + raw := `{ + "version": 1, + "settings": {}, + "rules": [ + {"id": "pump", "name": "Pump", "enabled": true, "conditions": [], "actions": [], + "learned_from": {"suggestion": "Pumpe bei Export", "kind": "threshold", "at": 1700000000}}, + {"id": "plain", "name": "Plain", "enabled": true, "conditions": [], "actions": []} + ], + "scenarios": [ + {"id": "nulleinspeisung", "name": "N", "enabled": true, + "learned_from": {"suggestion": "Nulleinspeisung", "kind": "scenario", "at": 1700000001}} + ] +}` + doc, err := ParseDoc([]byte(raw)) + if err != nil { + t.Fatal(err) + } + want := &LearnedFrom{Suggestion: "Pumpe bei Export", Kind: "threshold", At: 1700000000} + if !reflect.DeepEqual(doc.Rules[0].LearnedFrom, want) { + t.Errorf("rule learned_from = %+v, want %+v", doc.Rules[0].LearnedFrom, want) + } + if doc.Rules[1].LearnedFrom != nil { + t.Errorf("rule without learned_from has %+v", doc.Rules[1].LearnedFrom) + } + wantScenario := &LearnedFrom{Suggestion: "Nulleinspeisung", Kind: "scenario", At: 1700000001} + if !reflect.DeepEqual(doc.Scenarios[0].LearnedFrom, wantScenario) { + t.Errorf("scenario learned_from = %+v, want %+v", doc.Scenarios[0].LearnedFrom, wantScenario) + } +} diff --git a/dashboard/internal/config/automation_schema_test.go b/dashboard/internal/config/automation_schema_test.go index 8e31706f..b6c9f73d 100644 --- a/dashboard/internal/config/automation_schema_test.go +++ b/dashboard/internal/config/automation_schema_test.go @@ -300,3 +300,43 @@ func TestAutomationSchemaAcceptsLearnedValues(t *testing.T) { } } } + +// learned_from marks a rule or a scenario that came from a learned suggestion. +// All three keys are required and no other key is allowed. +func TestAutomationSchemaCasesLearnedFrom(t *testing.T) { + ruleWith := func(learned string) string { + return `{"version":1,"settings":` + defaultAutomationSettings + `,"rules":[{"id":"r1","name":"R","enabled":true,` + + `"conditions":[{"type":"balance_threshold","field":"grid_export","comparison":"above","threshold":800,"hysteresis":0,"hold_seconds":0}],` + + `"actions":[{"type":"notification","severity":"info","title":"t","message":"m"}],` + + `"learned_from":` + learned + `}],"scenarios":[]}` + } + scenarioWith := func(learned string) string { + return automationDoc(defaultAutomationSettings, + `[`+strings.Replace(minimalScenario("x"), `"enabled":true,`, `"enabled":true,"learned_from":`+learned+`,`, 1)+`]`) + } + valid := `{"suggestion":"Pumpe bei Export","kind":"threshold_low","at":1700000000}` + cases := []struct { + name string + doc string + ok bool + }{ + {"rule with learned_from", ruleWith(valid), true}, + {"scenario with learned_from", scenarioWith(valid), true}, + {"rule without at", ruleWith(`{"suggestion":"x","kind":"threshold"}`), false}, + {"scenario without at", scenarioWith(`{"suggestion":"x","kind":"threshold"}`), false}, + {"negative at", ruleWith(`{"suggestion":"x","kind":"threshold","at":-1}`), false}, + {"empty suggestion", ruleWith(`{"suggestion":"","kind":"threshold","at":0}`), false}, + {"suggestion over 200 characters", ruleWith(`{"suggestion":"` + strings.Repeat("a", 201) + `","kind":"threshold","at":0}`), false}, + {"kind with upper case", ruleWith(`{"suggestion":"x","kind":"Threshold","at":0}`), false}, + {"unknown key in learned_from", ruleWith(`{"suggestion":"x","kind":"threshold","at":0,"extra":1}`), false}, + } + for _, tc := range cases { + err := ValidateDocument([]byte(tc.doc), automationSchema(t)) + if tc.ok && err != nil { + t.Errorf("%s: expected acceptance, got %v", tc.name, err) + } + if !tc.ok && err == nil { + t.Errorf("%s: expected rejection", tc.name) + } + } +} diff --git a/services/automation/automation_rules.schema.json b/services/automation/automation_rules.schema.json index 83ea2726..160be785 100644 --- a/services/automation/automation_rules.schema.json +++ b/services/automation/automation_rules.schema.json @@ -55,6 +55,16 @@ "type": "boolean", "default": false }, + "learned_from": { + "type": "object", + "additionalProperties": false, + "required": ["suggestion", "kind", "at"], + "properties": { + "suggestion": { "type": "string", "minLength": 1, "maxLength": 200 }, + "kind": { "type": "string", "pattern": "^[a-z_]{1,40}$" }, + "at": { "type": "integer", "minimum": 0 } + } + }, "max_duration_s": { "type": "number", "minimum": 10, @@ -685,6 +695,16 @@ "name": { "type": "string", "minLength": 1 }, "enabled": { "type": "boolean" }, "history_enabled": { "type": "boolean", "default": false }, + "learned_from": { + "type": "object", + "additionalProperties": false, + "required": ["suggestion", "kind", "at"], + "properties": { + "suggestion": { "type": "string", "minLength": 1, "maxLength": 200 }, + "kind": { "type": "string", "pattern": "^[a-z_]{1,40}$" }, + "at": { "type": "integer", "minimum": 0 } + } + }, "cooldown_seconds": { "type": "number", "minimum": 0, "maximum": 86400, "default": 0 }, "repeat_seconds": { "type": "number", "minimum": 0, "maximum": 86400, "default": 0 }, "conditions": { diff --git a/services/automation/tests/test_automation_mqtt.py b/services/automation/tests/test_automation_mqtt.py index 64b21d22..f502d542 100644 --- a/services/automation/tests/test_automation_mqtt.py +++ b/services/automation/tests/test_automation_mqtt.py @@ -2290,3 +2290,30 @@ def test_malformed_hold_seconds_on_a_publish_rule_is_reported_not_raised(hold): automation._validate_rule(rule, 0, errors, set(), 30) assert "condition[0]: hold_seconds must be a number or a learned value" in errors[0] assert len(errors) == 1 + + +LEARNED_FROM = {"suggestion": "Pumpe bei Export", "kind": "threshold", "at": 1700000000} + + +def test_learned_from_passes_validation_for_rule_and_scenario(tmp_path): + scenario = {"id": "s1", "name": "S", "enabled": True, "learned_from": LEARNED_FROM, + "when": {"conditions": [{"type": "sun_window", "from": "sunrise", "to": "sunset"}]}} + doc = document(rules=[rule(learned_from=LEARNED_FROM)]) + doc["scenarios"] = [scenario] + result = automation.load_and_validate(write_doc(tmp_path, doc)) + assert result.rules[0]["learned_from"] == LEARNED_FROM + assert result.scenarios[0]["learned_from"] == LEARNED_FROM + + +def test_learned_from_stays_out_of_state_and_history(): + rule_def = rule_with_hold(hold_seconds=0, cooldown_seconds=0) + rule_def["learned_from"] = LEARNED_FROM + history_events = [] + doc, engine, published, events = engine_with( + [rule_def], history_sink=lambda rule_id, event: history_events.append((rule_id, event))) + results = engine.tick(doc, balance={"grid_export": 900}, balance_age=0, topic_values={}, now_ts=1000.0) + assert results["r1"]["result"] == "fired" + state_doc = automation.build_state_document(results, events, at=1000.0, online=True) + assert "learned_from" not in json.dumps(state_doc) + assert len(history_events) == 1 + assert "learned_from" not in json.dumps(history_events[0][1]) From ae2baedb52496cc9dcff1f94b29d506db0aea95a Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:24:02 +0100 Subject: [PATCH 02/34] feat(webui): record which suggestion a saved rule came from Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/automation-suggestions.js | 2 + .../webui/static/js/automations.page.js | 43 ++++++++++-- .../test/automation-suggestions.test.mjs | 7 ++ dashboard/test/automations.page.test.mjs | 68 +++++++++++++++++++ 4 files changed, 116 insertions(+), 4 deletions(-) diff --git a/dashboard/internal/webui/static/js/automation-suggestions.js b/dashboard/internal/webui/static/js/automation-suggestions.js index c49f4228..3ab14f73 100644 --- a/dashboard/internal/webui/static/js/automation-suggestions.js +++ b/dashboard/internal/webui/static/js/automation-suggestions.js @@ -278,6 +278,8 @@ fixOf(s) { return (s.apply || []).find((f) => f && f.template) || null; }, // Ein Befehl mit Ops schreibt seine Pfade direkt in den Regelentwurf (applyFix der Seite). opFixOf(s) { return (s.apply || []).find((f) => f && !f.template && Array.isArray(f.ops) && f.ops.length > 0) || null; }, + // Herkunft fuer den Assistenten: Id und Art des Vorschlags, learned_from der angelegten Regel. + originOf(s) { return { suggestion: s.id, kind: s.kind }; }, applyLabelOf(s, t) { const fix = this.opFixOf(s); return fix ? t(CAT + 'fix.' + fix.code, {}) : ''; diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index 55763a09..b82b7674 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -159,7 +159,7 @@ // Zustand des Vorlagen-Assistenten im Ruhezustand (Dialog zu). const assistantIdle = () => ({ open: false, templateId: '', answers: {}, index: 0, name: '', query: '', category: 'all', context: null, effects: {}, - band: { tolOn: false, errors: null }, surplus: null, + band: { tolOn: false, errors: null }, surplus: null, origin: null, }); // Zielband im Assistenten: Griff und Zustand leben ausserhalb der reaktiven Daten. let bandHandle = null; @@ -1621,8 +1621,11 @@ // falsch geformte Vorbelegung oeffnet die Galerie ohne Vorbelegung. Vorbelegte // Geraete, die es nicht gibt oder die gesperrt sind, werden leer. Danach springt // der Assistent zum ersten unvollstaendigen Schritt, sonst zur Zusammenfassung. - async openAssistantWith(templateId, prefill) { + // origin (optional) ist { suggestion, kind, replaceId? } des Vorschlags. assistantCreate + // setzt daraus learned_from an den angelegten Eintrag. + async openAssistantWith(templateId, prefill, origin = null) { await this.openAssistant(); + this.assistant.origin = origin && origin.suggestion ? origin : null; const mapped = prefillToAnswers(templateId, prefill); if (!mapped || !assistantTemplateList().some((item) => item.id === templateId) || !this.assistant.context) return; this.startTemplate(templateId); @@ -2003,12 +2006,34 @@ // Legt die Vorlage an: ungespeichert, aktiv, mit Rueckgaengig. Bei voller Liste // passiert nichts, der Dialog bleibt offen. Alle Eintraege sind schon gebaut, bevor // der erste eingefuegt wird, daher bleibt bei einem Fehler nichts halb angelegt. + // Kommt die Vorlage aus einem vorschlag (origin), traegt jeder Eintrag learned_from. + // Mit replaceId ersetzt der erste Eintrag die Regel mit dieser ID, die ID bleibt. assistantCreate() { const built = this.assistantBuild(); if (!built) return; const { kind, entries } = this.assistantEntries(built); - if (this.assistantFull(kind, entries.length)) return; - this.insertEntries(kind, entries); + const origin = this.assistant.origin; + const list = kind === 'scenario' ? this.document.scenarios : this.document.rules; + const replaceIndex = origin && origin.replaceId ? list.findIndex((entry) => entry.id === origin.replaceId) : -1; + if (replaceIndex < 0 && this.assistantFull(kind, entries.length)) return; + if (origin) { + const at = Math.floor(Date.now() / 1000); + entries.forEach((entry) => { + entry.learned_from = { suggestion: origin.suggestion, kind: origin.kind, at }; + }); + } + if (replaceIndex < 0) { + this.insertEntries(kind, entries); + } else { + const [first, ...rest] = entries; + first.id = list[replaceIndex].id; + list.splice(replaceIndex, 1, first); + this.newIds[first.id] = true; + this.expanded[first.id] = true; + this.editing[first.id] = true; + this.view = kind === 'scenario' ? 'scenarios' : 'rules'; + if (rest.length) this.insertEntries(kind, rest); + } this.closeAssistant(); }, @@ -2316,6 +2341,8 @@ // seit dem Befund geaendert), wird nichts geschrieben, die Regel oeffnet sich trotzdem. // Ein Befund mit fix.rules aendert mehrere Regeln: alle oder keine. // finding (optional) ist der Befund des Popovers, er bleibt bis zum Speichern verborgen. + // Mit finding setzt jede Regel oder jedes Szenario, auf die alle Ops geschrieben wurden, + // learned_from mit der Befund-Id als suggestion. applyFix(fix, finding = null) { const groups = Array.isArray(fix.rules) && fix.rules.length ? fix.rules.map((entry) => ({ code: fix.code, rule_id: entry.rule_id, ops: entry.ops || [] })) @@ -2353,6 +2380,14 @@ if (write.target.append) write.target.parent.push(write.value); else write.target.parent[write.target.key] = write.value; })); + if (finding && finding.id) { + const at = Math.floor(Date.now() / 1000); + plans.forEach((plan) => { + if (plan.entry && plan.writes.length > 0) { + plan.entry.learned_from = { suggestion: finding.id, kind: finding.kind, at }; + } + }); + } if (finding && finding.id && !this.appliedFindingIds.includes(finding.id)) { this.appliedFindingIds = [...this.appliedFindingIds, finding.id]; } diff --git a/dashboard/test/automation-suggestions.test.mjs b/dashboard/test/automation-suggestions.test.mjs index 3c104c5a..2f206dca 100644 --- a/dashboard/test/automation-suggestions.test.mjs +++ b/dashboard/test/automation-suggestions.test.mjs @@ -408,6 +408,13 @@ test('the assistant button needs a template fix and the editing permission', asy close(); }); +test('originOf gives the id and the kind of the suggestion for the assistant', async () => { + const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [withTemplate(finding('t:1', { kind: 'temp_limit' }))], learning: { since: 1, devices: 1, days: 1 } })); + await band.load(); + assert.deepEqual(plain(band.originOf(band.items[0])), { suggestion: 't:1', kind: 'temp_limit' }); + close(); +}); + function withOpsFix(s) { const fix = { code: 'add_condition', rule_id: 'r1', ops: [{ path: ['conditions', 0], value: { type: 'entity_value' } }] }; return { ...s, apply: [fix] }; diff --git a/dashboard/test/automations.page.test.mjs b/dashboard/test/automations.page.test.mjs index 0a756618..4ad3b5d3 100644 --- a/dashboard/test/automations.page.test.mjs +++ b/dashboard/test/automations.page.test.mjs @@ -3516,6 +3516,32 @@ test('applying a temperature limit suggestion adds the condition to the draft an assert.deepEqual(posted, []); }); +test('applyFix with a finding marks the rule it wrote to with learned_from', () => { + const { component } = createAutomationsPanel(); + component.document = { version: 1, settings: {}, rules: [ + { id: 'r1', name: 'Pumpe', conditions: [{ type: 'balance_threshold', threshold: 100, hysteresis: 0 }], actions: [] }, + ] }; + component.startEditing = () => {}; + component.applyFix({ code: 'shift_thresholds', rule_id: 'r1', ops: [{ path: ['conditions', 0, 'threshold'], value: 120 }] }, { id: 'f-hyst', kind: 'hysteresis' }); + assert.equal(component.document.rules[0].conditions[0].threshold, 120); + assert.equal(component.document.rules[0].learned_from.suggestion, 'f-hyst'); + assert.equal(component.document.rules[0].learned_from.kind, 'hysteresis'); +}); + +test('applyFix without a finding and applyFix with an unresolvable path write no learned_from', () => { + const { component } = createAutomationsPanel(); + component.document = { version: 1, settings: {}, rules: [ + { id: 'r1', name: 'Pumpe', conditions: [{ type: 'balance_threshold', threshold: 100, hysteresis: 0 }], actions: [] }, + ] }; + component.startEditing = () => {}; + component.applyFix({ code: 'shift_thresholds', rule_id: 'r1', ops: [{ path: ['conditions', 0, 'threshold'], value: 120 }] }); + assert.equal(component.document.rules[0].conditions[0].threshold, 120); + assert.equal('learned_from' in component.document.rules[0], false); + component.applyFix({ code: 'shift_thresholds', rule_id: 'r1', ops: [{ path: ['conditions', 4, 'threshold'], value: 90 }] }, { id: 'f-hyst', kind: 'hysteresis' }); + assert.equal(component.document.rules[0].conditions[0].threshold, 120); + assert.equal('learned_from' in component.document.rules[0], false); +}); + test('applyFix with rules changes every listed rule in the draft', () => { const { component } = createAutomationsPanel(); component.document = { version: 1, settings: {}, rules: [ @@ -3953,6 +3979,48 @@ test('openAssistantWith on a shift suggestion creates the scenario of the templa assert.equal(component.assistant.open, false); }); +test('an assistant from a learned suggestion marks the created scenario with learned_from', async () => { + const { component } = await prefillPanel(); + const before = component.document.scenarios.length; + await component.openAssistantWith('shift_start', { device: 'lampe', on_w: 1500, latest: '20:00' }, { suggestion: 'load_shift:lampe', kind: 'load_shift' }); + component.assistantGoTo('summary'); + component.assistantCreate(); + const created = component.document.scenarios[before]; + assert.equal(created.learned_from.suggestion, 'load_shift:lampe'); + assert.equal(created.learned_from.kind, 'load_shift'); + assert.ok(Number.isInteger(created.learned_from.at) && created.learned_from.at > 0); +}); + +test('an assistant without a suggestion writes no learned_from', async () => { + const { component } = await prefillPanel(); + const before = component.document.scenarios.length; + await component.openAssistantWith('shift_start', { device: 'lampe', on_w: 1500, latest: '20:00' }); + component.assistantGoTo('summary'); + component.assistantCreate(); + assert.equal(component.document.scenarios.length, before + 1); + assert.equal('learned_from' in component.document.scenarios[before], false); +}); + +test('replaceId keeps the count and the id of the replaced entry and takes the new conditions and a new stamp', async () => { + const { component } = await prefillPanel(); + await component.openAssistantWith('shift_start', { device: 'lampe', on_w: 1500, latest: '20:00' }, { suggestion: 'load_shift:lampe', kind: 'load_shift' }); + component.assistantGoTo('summary'); + component.assistantCreate(); + const before = component.document.scenarios.length; + const old = component.document.scenarios[before - 1]; + old.learned_from.at = 1; + await component.openAssistantWith('shift_start', { device: 'lampe', on_w: 1500, latest: '21:00' }, { suggestion: 'season_shift:lampe', kind: 'season_shift', replaceId: old.id }); + component.assistantGoTo('summary'); + component.assistantCreate(); + assert.equal(component.document.scenarios.length, before); + const replaced = component.document.scenarios[before - 1]; + assert.equal(replaced.id, old.id); + assert.equal(replaced.learned_from.suggestion, 'season_shift:lampe'); + assert.notEqual(replaced.learned_from.at, 1); + assert.match(JSON.stringify(replaced), /21:00/); + assert.doesNotMatch(JSON.stringify(replaced), /20:00/); +}); + // Die Demo-Spuelmaschine wie sie der Erkenner nennt: Geraete-Id spuelmaschine, Schalter spuelmaschine_steckdose. const dishwasherDevices = [ ...assistantDevices, From 6e20041bba7aa54f8790fca8a5477804073b56af Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:25:09 +0100 Subject: [PATCH 03/34] fix(webui): mark rules adopted from the suggestions band Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/static/js/automations.page.js | 4 ++-- dashboard/internal/webui/templates/automations-finding.html | 2 +- dashboard/internal/webui/templates/automations.html | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index b82b7674..d8b5b20e 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -2343,7 +2343,7 @@ // finding (optional) ist der Befund des Popovers, er bleibt bis zum Speichern verborgen. // Mit finding setzt jede Regel oder jedes Szenario, auf die alle Ops geschrieben wurden, // learned_from mit der Befund-Id als suggestion. - applyFix(fix, finding = null) { + applyFix(fix, finding = null, asSuggestion = true) { const groups = Array.isArray(fix.rules) && fix.rules.length ? fix.rules.map((entry) => ({ code: fix.code, rule_id: entry.rule_id, ops: entry.ops || [] })) : [{ code: fix.code, rule_id: fix.rule_id, ops: fix.ops || [] }]; @@ -2380,7 +2380,7 @@ if (write.target.append) write.target.parent.push(write.value); else write.target.parent[write.target.key] = write.value; })); - if (finding && finding.id) { + if (asSuggestion && finding && finding.id) { const at = Math.floor(Date.now() / 1000); plans.forEach((plan) => { if (plan.entry && plan.writes.length > 0) { diff --git a/dashboard/internal/webui/templates/automations-finding.html b/dashboard/internal/webui/templates/automations-finding.html index b488cbe8..928f1c82 100644 --- a/dashboard/internal/webui/templates/automations-finding.html +++ b/dashboard/internal/webui/templates/automations-finding.html @@ -26,7 +26,7 @@

diff --git a/dashboard/internal/webui/templates/automations.html b/dashboard/internal/webui/templates/automations.html index f1057f1a..f4b12890 100644 --- a/dashboard/internal/webui/templates/automations.html +++ b/dashboard/internal/webui/templates/automations.html @@ -136,9 +136,9 @@

+ x-on:click="openAssistantWith(fixOf(current).template, fixOf(current).prefill, originOf(current))">{{t "automations.learn.button.open_assistant"}} + x-on:click="applyFix(opFixOf(current), current)" x-text="applyLabelOf(current, $t)">
From a1e9dc649e6a0f63cfea066940cdb98ee1226c9c Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:28:47 +0100 Subject: [PATCH 04/34] feat(autolearn): measure the effect of an adopted suggestion against the season Co-Authored-By: Claude Sonnet 5.5 --- .../internal/autolearn/detect_overridden.go | 73 ++++- dashboard/internal/autolearn/effect.go | 270 ++++++++++++++++++ dashboard/internal/autolearn/effect_test.go | 260 +++++++++++++++++ 3 files changed, 590 insertions(+), 13 deletions(-) create mode 100644 dashboard/internal/autolearn/effect.go create mode 100644 dashboard/internal/autolearn/effect_test.go diff --git a/dashboard/internal/autolearn/detect_overridden.go b/dashboard/internal/autolearn/detect_overridden.go index 9cbc1016..0992bf15 100644 --- a/dashboard/internal/autolearn/detect_overridden.go +++ b/dashboard/internal/autolearn/detect_overridden.go @@ -213,6 +213,64 @@ func overrideFirst(manual []overrideManual, from int64, on bool, sec float64) (i return 0, false } +// overrideRuleIdx returns the positions in sw of the switches of the rule. +func overrideRuleIdx(sw []overrideSwitch, ruleID string) []int { + var idx []int + for i, s := range sw { + if s.rule == ruleID { + idx = append(idx, i) + } + } + return idx +} + +// overrideRuleLimit is the time limit of a rule whose switches sit at the +// positions idx of sw: the valley of the logarithmic distances to the reversal. +func overrideRuleLimit(sw []overrideSwitch, manual []overrideManual, idx []int) float64 { + dist := overrideDistances(sw, manual) + var logs []float64 + for _, i := range idx { + if dist[i] >= 0 { + logs = append(logs, math.Log(math.Max(float64(dist[i]), 1))) + } + } + return overriddenDeadline(logs) +} + +// OverrideCount counts the switches of the rule at or after since (fired) and +// how many of them the user reversed by hand or from outside within the time +// limit the detector learns for the rule (overridden). The limit and the counts +// are per device, the rule's switches of all devices are summed. +func OverrideCount(days []DayFile, ruleID string, since time.Time) (overridden, fired int) { + if ruleID == "" { + return 0, 0 + } + devices := map[string]bool{} + for i := range days { + for _, e := range days[i].Events { + if Origin(e.Origin) == OriginRule && e.Rule == ruleID { + devices[e.Device] = true + } + } + } + from := since.Unix() + for device := range devices { + sw, manual := overrideSwitches(days, device) + idx := overrideRuleIdx(sw, ruleID) + limit := overrideRuleLimit(sw, manual, idx) + for _, i := range idx { + if sw[i].at < from { + continue + } + fired++ + if _, ok := overrideFirst(manual, sw[i].at, !sw[i].on, limit); ok { + overridden++ + } + } + } + return overridden, fired +} + // overriddenDeadline learns the time limit from the valley of the logarithmic // distances. Without a valley it is overriddenFallbackSec. func overriddenDeadline(dists []float64) float64 { @@ -226,23 +284,12 @@ func overriddenDeadline(dists []float64) float64 { // overriddenCandidate builds the candidate of one rule, or reports false when // the rule fails the gates. func overriddenCandidate(device string, in *Input, rule Rule, sw []overrideSwitch, manual []overrideManual, loc *time.Location) (Candidate, bool) { - dist := overrideDistances(sw, manual) - var idx []int - var logs []float64 - for i, s := range sw { - if s.rule != rule.ID { - continue - } - idx = append(idx, i) - if dist[i] >= 0 { - logs = append(logs, math.Log(math.Max(float64(dist[i]), 1))) - } - } + idx := overrideRuleIdx(sw, rule.ID) n := len(idx) if n < overriddenMinCases { return Candidate{}, false } - limit := overriddenDeadline(logs) + limit := overrideRuleLimit(sw, manual, idx) cases := make([]overrideCase, n) hits := 0 diff --git a/dashboard/internal/autolearn/effect.go b/dashboard/internal/autolearn/effect.go new file mode 100644 index 00000000..6e279060 --- /dev/null +++ b/dashboard/internal/autolearn/effect.go @@ -0,0 +1,270 @@ +package autolearn + +import ( + "math" + "sort" + "time" +) + +// Units of Benefit.Unit that have a measured effect (spec 15.7). The group +// energy selects the grid share of the device energy. +const ( + effectUnitActions = "actions_week" + effectUnitKWh = "kwh_week" + effectGroupEnergy = "energy" +) + +// Status values of an EffectResult. +const ( + // EffectStatusOK means the effect is computed from a baseline and at least one full week since. + EffectStatusOK = "ok" + // EffectStatusWaiting means no full ISO week lies after the adoption yet. + EffectStatusWaiting = "waiting" + // EffectStatusNoBaseline means the baseline is missing, so there is no proof. + EffectStatusNoBaseline = "no_baseline" +) + +const ( + // effectMinBaseline is the number of baseline weeks the comparison needs. + effectMinBaseline = 2 + // effectBaselineWeeks is the number of full weeks before the adoption. + effectBaselineWeeks = 4 + // effectSinceWeeks is the largest number of full weeks since the adoption that is shown. + effectSinceWeeks = 8 +) + +// EffectResult is the measured effect of an adopted suggestion. Before is the +// median of the baseline weeks. Since and Expected hold per full week since the +// adoption the measure and the expected measure without the change. Low and High +// span the effect Since minus Expected over those weeks. Measurable is set when +// the span does not contain zero. Estimate is set when the expectation is not +// corrected by the prior year. Overridden and Fired are filled by the caller +// with OverrideCount. +type EffectResult struct { + Unit string + Before float64 + Since []float64 + Expected []float64 + Low, High float64 + Measurable bool + Estimate bool + Overridden int + Fired int + Weeks int + Status string +} + +// effectWeek is one full ISO week (seven day files) with its measure. pv is the +// PV of the week in kWh, kept for the season ratio. +type effectWeek struct { + mon time.Time + value float64 + pv float64 +} + +// EffectMetric returns the measure of the device per full ISO week (seven day +// files), oldest first. The measure follows the unit: actions_week counts the +// hand and external switches, kwh_week the device energy, or in the group +// energy its grid share. ok is false for a unit without a measure. +func EffectMetric(unit, group string, device string, days []DayFile) (perWeek []float64, ok bool) { + if !effectUnitKnown(unit) { + return nil, false + } + for _, w := range effectWeeks(days, unit, group, device) { + perWeek = append(perWeek, w.value) + } + return perWeek, true +} + +// ComputeEffect measures the effect of a change made at at. before holds the +// measures of the baseline weeks, the full weeks before at. The expectation of +// each week since at is the baseline times the season ratio r_i (spec 15.7), +// and the effect of the week is its measure minus that expectation. +func ComputeEffect(at time.Time, unit, group, device string, before []float64, days []DayFile, season *SeasonStore, loc *time.Location) EffectResult { + if loc == nil { + loc = time.Local + } + res := EffectResult{Unit: unit, Status: EffectStatusNoBaseline} + if !effectUnitKnown(unit) || len(before) < effectMinBaseline { + return res + } + res.Before = Median(before) + + atMon, _ := isoWeekMonday(isoWeekKey(at.In(loc))) + var since, base []effectWeek + for _, w := range effectWeeks(days, unit, group, device) { + switch { + case w.mon.After(atMon): + since = append(since, w) + case w.mon.Before(atMon): + base = append(base, w) + } + } + if len(base) > effectBaselineWeeks { + base = base[len(base)-effectBaselineWeeks:] + } + res.Status = EffectStatusWaiting + if len(since) == 0 { + return res + } + if len(since) > effectSinceWeeks { + since = since[len(since)-effectSinceWeeks:] + } + + // The prior-year figure of the baseline weeks is the denominator of every + // season ratio. Without it, the ratio falls back to this year's PV. + var baseSeason []float64 + var basePV []float64 + for _, w := range base { + basePV = append(basePV, w.pv) + if f, ok := effectPriorFigure(season, w.mon, unit, group); ok { + baseSeason = append(baseSeason, f) + } + } + denom := Median(baseSeason) + ratio := func(w effectWeek) (r float64, exact bool) { + if len(baseSeason) > 0 { + if f, ok := effectPriorFigure(season, w.mon, unit, group); ok { + return f / denom, true + } + } + if unit == effectUnitKWh && group == effectGroupEnergy && w.pv > 0 && len(basePV) > 0 { + if pv := Median(basePV); pv > 0 { + return pv / w.pv, false + } + } + return 1, false + } + + estimate := false + for i, w := range since { + r, exact := ratio(w) + if !exact { + estimate = true + } + exp := res.Before * r + res.Since = append(res.Since, w.value) + res.Expected = append(res.Expected, exp) + eff := w.value - exp + if i == 0 || eff < res.Low { + res.Low = eff + } + if i == 0 || eff > res.High { + res.High = eff + } + } + res.Measurable = res.Low > 0 || res.High < 0 + res.Estimate = estimate + res.Weeks = len(since) + res.Status = EffectStatusOK + return res +} + +// effectUnitKnown reports whether the unit has a measure. +func effectUnitKnown(unit string) bool { + return unit == effectUnitActions || unit == effectUnitKWh +} + +// effectWeeks sums the full ISO weeks of the day files, oldest first. A day +// counts once even when it appears twice. +func effectWeeks(days []DayFile, unit, group, device string) []effectWeek { + type acc struct { + mon time.Time + days int + value float64 + pv float64 + } + byKey := map[string]*acc{} + seen := map[string]bool{} + for i := range days { + d := &days[i] + t, err := time.Parse(dayLayout, d.Day) + if err != nil || seen[d.Day] { + continue + } + seen[d.Day] = true + key := isoWeekKey(t) + a := byKey[key] + if a == nil { + a = &acc{mon: t.AddDate(0, 0, -((int(t.Weekday()) + 6) % 7))} + byKey[key] = a + } + a.days++ + a.value += effectDayValue(d, unit, group, device) + for q := 0; q < dayQuarters; q++ { + a.pv += float64(d.Site.PV[q]) * baseWattQuarterKWh + } + } + var out []effectWeek + for _, a := range byKey { + if a.days == 7 { + out = append(out, effectWeek{mon: a.mon, value: a.value, pv: a.pv}) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].mon.Before(out[j].mon) }) + return out +} + +// effectDayValue is the measure of the device on one day for the unit. +func effectDayValue(d *DayFile, unit, group, device string) float64 { + dd := d.Devices[device] + if dd == nil { + return 0 + } + var sum float64 + switch { + case unit == effectUnitActions: + for q := 0; q < dayQuarters; q++ { + sum += float64(dd.Hand[q]) + float64(dd.Ext[q]) + } + case unit == effectUnitKWh && group == effectGroupEnergy: + // Per quarter hour the grid share is the smaller of the device energy and + // the grid import of the quarter (W over 0.25 h, in Wh). + for q := 0; q < dayQuarters; q++ { + sum += math.Min(float64(dd.Wh[q]), float64(d.Site.GridImport[q])*0.25) + } + sum /= 1000 + case unit == effectUnitKWh: + for q := 0; q < dayQuarters; q++ { + sum += float64(dd.Wh[q]) + } + sum /= 1000 + } + return sum +} + +// effectPriorFigure is the median season figure of the weeks of the same +// calendar week in the years before mon. ok is false without such a figure. +func effectPriorFigure(season *SeasonStore, mon time.Time, unit, group string) (float64, bool) { + if season == nil { + return 0, false + } + _, wk := mon.ISOWeek() + var vals []float64 + for _, w := range season.Same(mon, wk, seasonYears) { + if v := effectSeasonFigure(w, unit, group); v > 0 { + vals = append(vals, v) + } + } + if len(vals) == 0 { + return 0, false + } + return Median(vals), true +} + +// effectSeasonFigure is the season figure of a stored week for the unit: the +// house load for device energy, the inverse PV for the grid share. Actions +// have none, so the figure is zero. +func effectSeasonFigure(w Week, unit, group string) float64 { + switch { + case unit == effectUnitActions: + return 0 + case group == effectGroupEnergy: + if w.PVKWh > 0 { + return 1 / w.PVKWh + } + return 0 + default: + return w.LoadKWh + } +} diff --git a/dashboard/internal/autolearn/effect_test.go b/dashboard/internal/autolearn/effect_test.go new file mode 100644 index 00000000..ee96b311 --- /dev/null +++ b/dashboard/internal/autolearn/effect_test.go @@ -0,0 +1,260 @@ +package autolearn + +import ( + "math" + "path/filepath" + "testing" + "time" +) + +const effDev = "plug.heater" + +// effDays builds the day files of the given ISO weeks of year in loc, Monday to +// Sunday. fill sets the values of one day of week w (d is 0 for Monday). +func effDays(t *testing.T, loc *time.Location, year int, weeks []int, fill func(w, d int, dd *DeviceDay, f *DayFile)) []DayFile { + t.Helper() + var out []DayFile + for _, w := range weeks { + mon := isoWeekMondayOf(year, w) + for d := 0; d < 7; d++ { + day := time.Date(mon.Year(), mon.Month(), mon.Day()+d, 0, 0, 0, 0, loc) + f := relDay(day) + for q := 0; q < dayQuarters; q++ { + f.Site.PV[q] = 1000 + f.Site.LoadTotal[q] = 300 + } + dd := &DeviceDay{} + f.Devices[effDev] = dd + if fill != nil { + fill(w, d, dd, &f) + } + out = append(out, f) + } + } + return out +} + +// effAt is noon of the Monday of week w of year in loc. +func effAt(year, w int, loc *time.Location) time.Time { + mon := isoWeekMondayOf(year, w) + return time.Date(mon.Year(), mon.Month(), mon.Day(), 12, 0, 0, 0, loc) +} + +func effClose(a, b float64) bool { + return math.Abs(a-b) < 1e-6 +} + +// effStore is an empty season store in a temporary file. +func effStore(t *testing.T) *SeasonStore { + t.Helper() + return LoadSeasonStore(filepath.Join(t.TempDir(), "season.json"), nil) +} + +// effHandWeeks gives each week its hand switches on the Monday. +func effHandWeeks(hand map[int]uint8) func(w, d int, dd *DeviceDay, f *DayFile) { + return func(w, d int, dd *DeviceDay, f *DayFile) { + if d == 0 { + dd.Hand[0] = hand[w] + } + } +} + +func TestEffectHandSwitchesDropBelowBaseline(t *testing.T) { + loc := berlinLoc(t) + hand := map[int]uint8{1: 10, 2: 10, 3: 10, 4: 10, 5: 0, 6: 2, 7: 2} + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(hand)) + + perWeek, ok := EffectMetric(effectUnitActions, "", effDev, days) + if !ok { + t.Fatal("actions_week has no metric") + } + want := []float64{10, 10, 10, 10, 0, 2, 2} + if len(perWeek) != len(want) { + t.Fatalf("perWeek = %v, want %v", perWeek, want) + } + for i := range want { + if perWeek[i] != want[i] { + t.Fatalf("perWeek = %v, want %v", perWeek, want) + } + } + if _, ok := EffectMetric("minutes", "", effDev, days); ok { + t.Error("unknown unit has a metric") + } + + res := ComputeEffect(effAt(2026, 5, loc), effectUnitActions, "", effDev, + []float64{10, 10, 10, 10}, days, effStore(t), loc) + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if res.Before != 10 || res.Weeks != 2 { + t.Errorf("Before = %v, Weeks = %d, want 10 and 2", res.Before, res.Weeks) + } + if len(res.Since) != 2 || res.Since[0] != 2 || res.Since[1] != 2 { + t.Errorf("Since = %v, want [2 2]", res.Since) + } + if !effClose(res.Low, -8) || !effClose(res.High, -8) { + t.Errorf("span = [%v, %v], want [-8, -8]", res.Low, res.High) + } + if !res.Measurable { + t.Error("a span below zero is not measurable") + } +} + +func TestEffectNoiseSpanContainsZero(t *testing.T) { + loc := berlinLoc(t) + hand := map[int]uint8{1: 5, 2: 5, 3: 5, 4: 5, 5: 0, 6: 3, 7: 7} + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(hand)) + + res := ComputeEffect(effAt(2026, 5, loc), effectUnitActions, "", effDev, + []float64{5, 5, 5, 5}, days, effStore(t), loc) + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if !effClose(res.Low, -2) || !effClose(res.High, 2) { + t.Errorf("span = [%v, %v], want [-2, 2]", res.Low, res.High) + } + if res.Measurable { + t.Error("a span around zero is measurable") + } +} + +// effGridFill gives the device 20 Wh per quarter and the grid import per week, +// so the grid share is 10 Wh per quarter in weeks before 9 and 11 Wh after. +func effGridFill(grid map[int]float32) func(w, d int, dd *DeviceDay, f *DayFile) { + return func(w, d int, dd *DeviceDay, f *DayFile) { + for q := 0; q < dayQuarters; q++ { + dd.Wh[q] = 20 + f.Site.GridImport[q] = grid[w] + } + } +} + +// effGridDays are weeks 5 to 11 of 2026: four baseline weeks, the adoption +// week 9 and the weeks 10 and 11 since. +func effGridDays(t *testing.T, loc *time.Location) []DayFile { + grid := map[int]float32{5: 40, 6: 40, 7: 40, 8: 40, 9: 40, 10: 44, 11: 44} + return effDays(t, loc, 2026, []int{5, 6, 7, 8, 9, 10, 11}, effGridFill(grid)) +} + +// effPriorPV puts the prior-year PV of the weeks 4 to 12 of 2025 in the store: +// 100 kWh up to week 8, 70 kWh from week 9 on. +func effPriorPV(t *testing.T) *SeasonStore { + t.Helper() + s := effStore(t) + for w := 4; w <= 12; w++ { + pv := 100.0 + if w >= 9 { + pv = 70 + } + s.Put(Week{Key: isoWeekKey(isoWeekMondayOf(2025, w)), PVKWh: pv}) + } + return s +} + +func TestEffectGridShareWithPriorYearIsSeasonAdjusted(t *testing.T) { + loc := berlinLoc(t) + days := effGridDays(t, loc) + before := []float64{6.72, 6.72, 6.72, 6.72} + + res := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + before, days, effPriorPV(t), loc) + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if res.Estimate { + t.Error("Estimate set although the prior year is there") + } + if len(res.Since) != 2 || len(res.Expected) != 2 { + t.Fatalf("Since = %v, Expected = %v, want two weeks", res.Since, res.Expected) + } + for i := range res.Since { + if !(res.Expected[i] > res.Since[i]) { + t.Errorf("week %d: Expected %v not above Since %v", i, res.Expected[i], res.Since[i]) + } + } + if !(res.High < 0) { + t.Errorf("effect span [%v, %v], want below zero (good)", res.Low, res.High) + } + if !res.Measurable { + t.Error("the grid share effect is not measurable") + } +} + +func TestEffectWithoutPriorYearIsEstimate(t *testing.T) { + loc := berlinLoc(t) + days := effGridDays(t, loc) + before := []float64{6.72, 6.72, 6.72, 6.72} + + res := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + before, days, effStore(t), loc) + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if !res.Estimate { + t.Error("Estimate not set without a prior year") + } +} + +func TestEffectAdoptionFiveDaysAgoIsWaiting(t *testing.T) { + loc := berlinLoc(t) + grid := map[int]float32{5: 40, 6: 40, 7: 40, 8: 40, 9: 40} + days := effDays(t, loc, 2026, []int{5, 6, 7, 8, 9}, effGridFill(grid)) + at := effAt(2026, 9, loc).AddDate(0, 0, 5) + + res := ComputeEffect(at, effectUnitKWh, "energy", effDev, + []float64{6.72, 6.72, 6.72, 6.72}, days, effStore(t), loc) + if res.Status != EffectStatusWaiting { + t.Errorf("Status = %q, want waiting", res.Status) + } +} + +func TestEffectOneBaselineWeekIsNoBaseline(t *testing.T) { + loc := berlinLoc(t) + days := effGridDays(t, loc) + + res := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + []float64{6.72}, days, effStore(t), loc) + if res.Status != EffectStatusNoBaseline { + t.Errorf("Status = %q, want no_baseline", res.Status) + } +} + +func TestEffectWithoutUnitHasNoBaseline(t *testing.T) { + loc := berlinLoc(t) + days := effGridDays(t, loc) + + res := ComputeEffect(effAt(2026, 9, loc), "", "", effDev, + []float64{6.72, 6.72}, days, effStore(t), loc) + if res.Status != EffectStatusNoBaseline || len(res.Since) != 0 { + t.Errorf("Status = %q, Since = %v, want no_baseline without weeks", res.Status, res.Since) + } +} + +func TestOverrideCountReversedWithinLimit(t *testing.T) { + loc := berlinLoc(t) + start := isoWeekMondayOf(2026, 1) + var days []DayFile + for i := 0; i < 3; i++ { + day := time.Date(start.Year(), start.Month(), start.Day()+i, 0, 0, 0, 0, loc) + f := relDay(day) + at := relAt(day, 18, 0, 0) + f.Events = append(f.Events, EventRec{At: at, Device: effDev, Entity: "switch." + effDev, + On: true, Origin: string(OriginRule), Rule: "heat"}) + if i == 0 { + f.Events = append(f.Events, EventRec{At: at + 120, Device: effDev, Entity: "switch." + effDev, + On: false, Origin: string(OriginHand)}) + } + days = append(days, f) + } + + if ov, fired := OverrideCount(days, "heat", time.Time{}); ov != 1 || fired != 3 { + t.Errorf("OverrideCount = (%d, %d), want (1, 3)", ov, fired) + } + since := time.Date(start.Year(), start.Month(), start.Day()+2, 0, 0, 0, 0, loc) + if ov, fired := OverrideCount(days, "heat", since); ov != 0 || fired != 1 { + t.Errorf("OverrideCount since day 3 = (%d, %d), want (0, 1)", ov, fired) + } + if ov, fired := OverrideCount(days, "", time.Time{}); ov != 0 || fired != 0 { + t.Errorf("OverrideCount without rule = (%d, %d), want (0, 0)", ov, fired) + } +} From fbbda8cb0f802ff54dc393e332ca15f74f95cfd4 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:29:59 +0100 Subject: [PATCH 05/34] fix(autolearn): accept baseline weeks with five days of data Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/effect.go | 27 ++++++++++++-------- dashboard/internal/autolearn/effect_test.go | 28 +++++++++++++++++++++ 2 files changed, 45 insertions(+), 10 deletions(-) diff --git a/dashboard/internal/autolearn/effect.go b/dashboard/internal/autolearn/effect.go index 6e279060..6d328ac2 100644 --- a/dashboard/internal/autolearn/effect.go +++ b/dashboard/internal/autolearn/effect.go @@ -25,6 +25,8 @@ const ( ) const ( + // effectBaseDays is the number of day files a baseline week needs. + effectBaseDays = 5 // effectMinBaseline is the number of baseline weeks the comparison needs. effectMinBaseline = 2 // effectBaselineWeeks is the number of full weeks before the adoption. @@ -58,19 +60,21 @@ type EffectResult struct { // PV of the week in kWh, kept for the season ratio. type effectWeek struct { mon time.Time + days int value float64 pv float64 } -// EffectMetric returns the measure of the device per full ISO week (seven day -// files), oldest first. The measure follows the unit: actions_week counts the +// EffectMetric returns the measure of the device per ISO week with at least +// effectBaseDays day files, oldest first. A week with fewer than seven day files +// is scaled to a week by the mean per day. The measure follows the unit: actions_week counts the // hand and external switches, kwh_week the device energy, or in the group // energy its grid share. ok is false for a unit without a measure. func EffectMetric(unit, group string, device string, days []DayFile) (perWeek []float64, ok bool) { if !effectUnitKnown(unit) { return nil, false } - for _, w := range effectWeeks(days, unit, group, device) { + for _, w := range effectWeeks(days, unit, group, device, effectBaseDays) { perWeek = append(perWeek, w.value) } return perWeek, true @@ -92,9 +96,9 @@ func ComputeEffect(at time.Time, unit, group, device string, before []float64, d atMon, _ := isoWeekMonday(isoWeekKey(at.In(loc))) var since, base []effectWeek - for _, w := range effectWeeks(days, unit, group, device) { + for _, w := range effectWeeks(days, unit, group, device, effectBaseDays) { switch { - case w.mon.After(atMon): + case w.mon.After(atMon) && w.days == 7: since = append(since, w) case w.mon.Before(atMon): base = append(base, w) @@ -165,9 +169,10 @@ func effectUnitKnown(unit string) bool { return unit == effectUnitActions || unit == effectUnitKWh } -// effectWeeks sums the full ISO weeks of the day files, oldest first. A day -// counts once even when it appears twice. -func effectWeeks(days []DayFile, unit, group, device string) []effectWeek { +// effectWeeks sums the ISO weeks of the day files that hold at least minDays +// day files, oldest first. The sums are scaled to seven days by the mean per day, +// so a full week is unchanged. A day counts once even when it appears twice. +func effectWeeks(days []DayFile, unit, group, device string, minDays int) []effectWeek { type acc struct { mon time.Time days int @@ -197,9 +202,11 @@ func effectWeeks(days []DayFile, unit, group, device string) []effectWeek { } var out []effectWeek for _, a := range byKey { - if a.days == 7 { - out = append(out, effectWeek{mon: a.mon, value: a.value, pv: a.pv}) + if a.days < minDays { + continue } + scale := 7 / float64(a.days) + out = append(out, effectWeek{mon: a.mon, days: a.days, value: a.value * scale, pv: a.pv * scale}) } sort.Slice(out, func(i, j int) bool { return out[i].mon.Before(out[j].mon) }) return out diff --git a/dashboard/internal/autolearn/effect_test.go b/dashboard/internal/autolearn/effect_test.go index ee96b311..d298405d 100644 --- a/dashboard/internal/autolearn/effect_test.go +++ b/dashboard/internal/autolearn/effect_test.go @@ -258,3 +258,31 @@ func TestOverrideCountReversedWithinLimit(t *testing.T) { t.Errorf("OverrideCount without rule = (%d, %d), want (0, 0)", ov, fired) } } + +// TestEffectBaselineWeeksWithFiveDaysAreOK: the baseline weeks 5 to 8 hold only +// their Monday to Friday, which is enough for a baseline week. The prior-year +// ratio then applies, so the result is exact and not an estimate. +func TestEffectBaselineWeeksWithFiveDaysAreOK(t *testing.T) { + loc := berlinLoc(t) + var days []DayFile + for _, f := range effGridDays(t, loc) { + d, err := time.Parse(dayLayout, f.Day) + if err != nil { + t.Fatal(err) + } + if _, wk := d.ISOWeek(); wk < 9 && (d.Weekday() == time.Saturday || d.Weekday() == time.Sunday) { + continue + } + days = append(days, f) + } + before := []float64{6.72, 6.72, 6.72, 6.72} + + res := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + before, days, effPriorPV(t), loc) + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if res.Estimate { + t.Error("Estimate set although the baseline weeks have five days and the prior year is there") + } +} From f0d3d9e60e27d2de368d3e6803cf4b2e8113539d Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:59:10 +0100 Subject: [PATCH 06/34] feat(autolearn): keep the effect of adopted rules in a store The season denominator of the effect now comes from the adoption date, so it holds once the baseline day files are pruned. The new EffectStore keeps one measured effect per rule or scenario that came from a learned suggestion, with its baseline and the numbers shown with it. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/effect.go | 8 +- dashboard/internal/autolearn/effect_store.go | 363 ++++++++++++++++++ .../internal/autolearn/effect_store_test.go | 220 +++++++++++ dashboard/internal/autolearn/effect_test.go | 31 ++ dashboard/internal/autolearn/finding.go | 2 + 5 files changed, 621 insertions(+), 3 deletions(-) create mode 100644 dashboard/internal/autolearn/effect_store.go create mode 100644 dashboard/internal/autolearn/effect_store_test.go diff --git a/dashboard/internal/autolearn/effect.go b/dashboard/internal/autolearn/effect.go index 6d328ac2..0bad967c 100644 --- a/dashboard/internal/autolearn/effect.go +++ b/dashboard/internal/autolearn/effect.go @@ -118,12 +118,14 @@ func ComputeEffect(at time.Time, unit, group, device string, before []float64, d // The prior-year figure of the baseline weeks is the denominator of every // season ratio. Without it, the ratio falls back to this year's PV. var baseSeason []float64 + for k := 1; k <= effectBaselineWeeks; k++ { + if f, ok := effectPriorFigure(season, atMon.AddDate(0, 0, -7*k), unit, group); ok { + baseSeason = append(baseSeason, f) + } + } var basePV []float64 for _, w := range base { basePV = append(basePV, w.pv) - if f, ok := effectPriorFigure(season, w.mon, unit, group); ok { - baseSeason = append(baseSeason, f) - } } denom := Median(baseSeason) ratio := func(w effectWeek) (r float64, exact bool) { diff --git a/dashboard/internal/autolearn/effect_store.go b/dashboard/internal/autolearn/effect_store.go new file mode 100644 index 00000000..0d42b8ca --- /dev/null +++ b/dashboard/internal/autolearn/effect_store.go @@ -0,0 +1,363 @@ +package autolearn + +import ( + "encoding/json" + "log" + "math" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/energystats" +) + +// effectBandSpan is how long the effect of an adopted suggestion stays on the band. +const effectBandSpan = 8 * 7 * 24 * time.Hour + +// effectEntry is the measured effect of one rule or scenario that came from a +// learned suggestion. Before holds the baseline measures, Values the numbers +// shown with the suggestion, Result the last computed effect. +type effectEntry struct { + Rule string `json:"rule"` + Suggestion string `json:"suggestion"` + Kind string `json:"kind"` + At int64 `json:"at"` + Unit string `json:"unit,omitempty"` + Group string `json:"group,omitempty"` + Device string `json:"device,omitempty"` + Before []float64 `json:"before,omitempty"` + Values map[string]float64 `json:"values,omitempty"` + Result EffectResult `json:"result"` +} + +// effectFile is the content of the effect store file. +type effectFile struct { + Entries []effectEntry `json:"entries"` +} + +// EffectStore keeps one entry per rule or scenario with LearnedFrom, keyed by +// its ID. It is safe for concurrent use. +type EffectStore struct { + mu sync.Mutex + path string + logf func(string, ...any) + entries map[string]effectEntry +} + +// LoadEffectStore reads the store from path. A missing file means an empty +// store. A damaged file is logged and starts empty. +func LoadEffectStore(path string, logf func(string, ...any)) *EffectStore { + if logf == nil { + logf = log.Printf + } + s := &EffectStore{path: path, logf: logf, entries: map[string]effectEntry{}} + data, err := os.ReadFile(path) + if err != nil { + if !os.IsNotExist(err) { + logf("effect store: read %s: %v", path, err) + } + return s + } + var f effectFile + if err := json.Unmarshal(data, &f); err != nil { + logf("effect store: %s is damaged, starting empty: %v", path, err) + return s + } + for _, e := range f.Entries { + s.entries[e.Rule] = e + } + return s +} + +// Save writes the store atomically. Without a path nothing is written. +func (s *EffectStore) Save() error { + s.mu.Lock() + defer s.mu.Unlock() + return s.saveLocked() +} + +// saveLocked writes the store. The caller holds s.mu. +func (s *EffectStore) saveLocked() error { + if s.path == "" { + return nil + } + data, err := json.Marshal(effectFile{Entries: s.sortedLocked()}) + if err != nil { + return err + } + return energystats.WriteFileAtomic(filepath.Dir(s.path), s.path, data) +} + +// Reset drops all entries and removes the file. A missing file is no error. +func (s *EffectStore) Reset() error { + s.mu.Lock() + defer s.mu.Unlock() + s.entries = map[string]effectEntry{} + if s.path == "" { + return nil + } + if err := os.Remove(s.path); err != nil && !os.IsNotExist(err) { + return err + } + return nil +} + +// Len is the number of entries. +func (s *EffectStore) Len() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.entries) +} + +// NeedsDays tells whether Sync would take a new entry for the doc, so the day +// files of the baseline are needed. +func (s *EffectStore) NeedsDays(doc Doc) bool { + s.mu.Lock() + defer s.mu.Unlock() + for id, lf := range learnedMarks(doc) { + e, ok := s.entries[id] + if !ok || e.At != lf.At || e.Suggestion != lf.Suggestion { + return true + } + } + return false +} + +// Sync brings the entries in line with the doc. Entries of rules or scenarios +// without LearnedFrom are removed. A new entry takes its baseline from the day +// files before the adoption week. An unchanged entry is kept as it was first +// seen. The store is saved when the set changed. added tells whether an entry +// was taken. +func (s *EffectStore) Sync(doc Doc, now time.Time, days []DayFile, shown map[string]Shown, findingsByID map[string]Finding) (added bool) { + marks := learnedMarks(doc) + s.mu.Lock() + defer s.mu.Unlock() + changed := false + for id := range s.entries { + if _, ok := marks[id]; !ok { + delete(s.entries, id) + changed = true + } + } + for id, lf := range marks { + e, ok := s.entries[id] + if ok && e.At == lf.At && e.Suggestion == lf.Suggestion { + continue + } + s.entries[id] = newEffectEntry(id, lf, now, days, shown, findingsByID) + added = true + changed = true + } + if changed { + if err := s.saveLocked(); err != nil { + s.logf("effect store: save: %v", err) + } + } + return added +} + +// Nightly computes the effect of every entry from the day files and the season +// store, then saves the store. cands is unused for now. The season drift reads it. +func (s *EffectStore) Nightly(now time.Time, days []DayFile, season *SeasonStore, cands []Candidate) { + s.mu.Lock() + defer s.mu.Unlock() + loc := now.Location() + for id, e := range s.entries { + at := time.Unix(e.At, 0) + res := ComputeEffect(at, e.Unit, e.Group, e.Device, e.Before, days, season, loc) + res.Overridden, res.Fired = OverrideCount(days, id, at) + e.Result = res + s.entries[id] = e + } + if err := s.saveLocked(); err != nil { + s.logf("effect store: save: %v", err) + } +} + +// Findings returns one check finding per entry with a computed effect, sorted +// by rule ID. +func (s *EffectStore) Findings(now time.Time) []Finding { + s.mu.Lock() + defer s.mu.Unlock() + out := []Finding{} + for _, e := range s.sortedLocked() { + if e.Result.Status == "" { + continue + } + out = append(out, effectFinding(e, FindingID("effect", e.Rule), "check", now.Location())) + } + return out +} + +// BandEntries returns the feedback findings of the entries with a measured +// effect that is still shown on the band, sorted by rule ID. +func (s *EffectStore) BandEntries(now time.Time) []Finding { + s.mu.Lock() + defer s.mu.Unlock() + out := []Finding{} + for _, e := range s.sortedLocked() { + if e.Result.Status != EffectStatusOK { + continue + } + if !now.Before(time.Unix(e.At, 0).Add(effectBandSpan)) { + continue + } + out = append(out, effectFinding(e, "effect:"+e.Rule, "feedback", now.Location())) + } + return out +} + +// sortedLocked returns the entries sorted by rule ID. The caller holds s.mu. +func (s *EffectStore) sortedLocked() []effectEntry { + ids := make([]string, 0, len(s.entries)) + for id := range s.entries { + ids = append(ids, id) + } + sort.Strings(ids) + out := make([]effectEntry, 0, len(ids)) + for _, id := range ids { + out = append(out, s.entries[id]) + } + return out +} + +// learnedMarks lists the rules and scenarios of the doc that came from a +// learned suggestion, by ID. +func learnedMarks(doc Doc) map[string]*LearnedFrom { + out := map[string]*LearnedFrom{} + for _, r := range doc.Rules { + if r.LearnedFrom != nil { + out[r.ID] = r.LearnedFrom + } + } + for _, sc := range doc.Scenarios { + if sc.LearnedFrom != nil { + out[sc.ID] = sc.LearnedFrom + } + } + return out +} + +// newEffectEntry takes the measure, the numbers and the baseline of a new entry. +func newEffectEntry(id string, lf *LearnedFrom, now time.Time, days []DayFile, shown map[string]Shown, findingsByID map[string]Finding) effectEntry { + e := effectEntry{Rule: id, Suggestion: lf.Suggestion, Kind: lf.Kind, At: lf.At} + if f, ok := findingsByID[lf.Suggestion]; ok { + if f.Benefit != nil { + e.Unit = f.Benefit.Unit + } + e.Group = f.Group + e.Device = f.Device + } else { + e.Unit, e.Group, e.Device = effectSpecFromKind(lf.Kind, lf.Suggestion) + } + if e.Device == "" { + e.Unit = "" + } + if sh, ok := shown[lf.Suggestion]; ok { + e.Values = copyValues(sh.Values) + } + e.Before = effectBefore(e.Unit, e.Group, e.Device, lf.At, now, days) + return e +} + +// effectSpecFromKind gives the unit, group and device of a suggestion without +// its finding, from its kind and its ID parts split at ":". +func effectSpecFromKind(kind, sugg string) (unit, group, device string) { + parts := strings.Split(sugg, ":") + part := func(i int) string { + if i < len(parts) { + return parts[i] + } + return "" + } + switch kind { + case "switch_time": + return effectUnitActions, "habit", part(1) + case "coupling": + return effectUnitActions, "habit", part(3) + case "away_standby", "runtime": + return effectUnitKWh, "habit", part(1) + case "surplus_window", "load_shift": + return effectUnitKWh, effectGroupEnergy, part(1) + case "temp_limit", "threshold", "battery": + return effectUnitKWh, effectGroupEnergy, "" + } + return "", "", "" +} + +// effectBefore is the measure of the four full weeks before the adoption week +// at, oldest first. Only the day files of those weeks count. +func effectBefore(unit, group, device string, at int64, now time.Time, days []DayFile) []float64 { + mon, ok := isoWeekMonday(isoWeekKey(time.Unix(at, 0).In(now.Location()))) + if !ok { + return nil + } + from := mon.AddDate(0, 0, -28).Format(dayLayout) + to := mon.Format(dayLayout) + var sel []DayFile + for i := range days { + if days[i].Day >= from && days[i].Day < to { + sel = append(sel, days[i]) + } + } + perWeek, _ := EffectMetric(unit, group, device, sel) + return perWeek +} + +// effectFinding builds the finding of an entry with the given ID and group. +func effectFinding(e effectEntry, id, group string, loc *time.Location) Finding { + r := e.Result + f := Finding{ + ID: id, + Kind: "effect", + Group: group, + RuleIDs: []string{e.Rule}, + Severity: "info", + Confidence: "high", + Device: e.Device, + Facts: []Fact{}, + Apply: []Fix{}, + } + if r.Estimate { + f.Confidence = "estimate" + } + params := map[string]any{"overridden": r.Overridden, "fired": r.Fired} + switch r.Status { + case EffectStatusOK: + if !r.Measurable { + f.Summary = Text{Code: "effect.not_measurable", Params: params} + break + } + var mean float64 + for _, v := range r.Since { + mean += v + } + if len(r.Since) > 0 { + mean /= float64(len(r.Since)) + } + before, since := effectRound(r.Before), effectRound(mean) + params["before"] = before + params["since"] = since + params["low"] = effectRound(r.Low) + params["high"] = effectRound(r.High) + params["unit"] = r.Unit + f.Summary = Text{Code: "effect.ok", Params: params} + f.Evidence = Evidence{Shape: "scale", Unit: r.Unit, IstValue: &before, SollValue: &since, + Labels: []string{"before", "since"}} + case EffectStatusWaiting: + mon, _ := isoWeekMonday(isoWeekKey(time.Unix(e.At, 0).In(loc))) + params["date"] = mon.AddDate(0, 0, 14).Format(dayLayout) + f.Summary = Text{Code: "effect.waiting", Params: params} + default: + f.Summary = Text{Code: "effect.no_baseline", Params: params} + } + return f +} + +// effectRound rounds to one decimal. +func effectRound(x float64) float64 { + return math.Round(x*10) / 10 +} diff --git a/dashboard/internal/autolearn/effect_store_test.go b/dashboard/internal/autolearn/effect_store_test.go new file mode 100644 index 00000000..211b7950 --- /dev/null +++ b/dashboard/internal/autolearn/effect_store_test.go @@ -0,0 +1,220 @@ +package autolearn + +import ( + "os" + "path/filepath" + "reflect" + "testing" + "time" +) + +const effSugg = "switch_time:plug.heater:on:0:0700" + +// effDoc is a doc with one rule learned from suggestion sugg at the time at. +func effDoc(rule, sugg, kind string, at time.Time) Doc { + return Doc{Rules: []Rule{{ID: rule, LearnedFrom: &LearnedFrom{Suggestion: sugg, Kind: kind, At: at.Unix()}}}} +} + +// effMark is the finding of the suggestion: actions per week on the heater. +func effMark() map[string]Finding { + return map[string]Finding{effSugg: {ID: effSugg, Group: "habit", Device: effDev, + Benefit: &Benefit{Unit: effectUnitActions}}} +} + +// effHandHeater: ten switches a week in weeks 1 to 4, then two a week. +var effHandHeater = map[int]uint8{1: 10, 2: 10, 3: 10, 4: 10, 5: 0, 6: 2, 7: 2} + +func effStoreAt(t *testing.T) *EffectStore { + t.Helper() + return LoadEffectStore(filepath.Join(t.TempDir(), "effect.json"), nil) +} + +func TestEffectStoreSyncNewMark(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(effHandHeater)) + s := effStoreAt(t) + doc := effDoc("r1", effSugg, "switch_time", at) + shown := map[string]Shown{effSugg: {Values: map[string]float64{"n": 3}}} + + if !s.Sync(doc, at, days, shown, effMark()) { + t.Fatal("Sync added nothing for a new mark") + } + e := s.entries["r1"] + if want := []float64{10, 10, 10, 10}; !reflect.DeepEqual(e.Before, want) { + t.Errorf("Before = %v, want %v", e.Before, want) + } + if e.Values["n"] != 3 { + t.Errorf("Values = %v, want n=3", e.Values) + } + if s.Sync(doc, at, days, shown, effMark()) { + t.Error("second Sync reported an added entry") + } + if s.NeedsDays(doc) { + t.Error("NeedsDays after a complete Sync") + } +} + +func TestEffectStoreFindingsAndBand(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(effHandHeater)) + s := effStoreAt(t) + s.Sync(effDoc("r1", effSugg, "switch_time", at), at, days, nil, effMark()) + now := effAt(2026, 7, loc).AddDate(0, 0, 7) + s.Nightly(now, days, effStore(t), nil) + + fs := s.Findings(now) + if len(fs) != 1 { + t.Fatalf("Findings = %d, want 1", len(fs)) + } + f := fs[0] + if f.ID != "effect:r1" || f.Kind != "effect" || f.Group != "check" || f.Severity != "info" { + t.Errorf("finding = %+v", f) + } + if f.Summary.Code != "effect.ok" { + t.Fatalf("Summary.Code = %q, want effect.ok", f.Summary.Code) + } + p := f.Summary.Params + if p["before"] != 10.0 || p["since"] != 2.0 || p["low"] != -8.0 || p["high"] != -8.0 || p["unit"] != effectUnitActions { + t.Errorf("Params = %v", p) + } + if f.Evidence.IstValue == nil || *f.Evidence.IstValue != 10 || f.Evidence.SollValue == nil || *f.Evidence.SollValue != 2 { + t.Errorf("Evidence values = %v / %v, want 10 and 2", f.Evidence.IstValue, f.Evidence.SollValue) + } + if !reflect.DeepEqual(f.Evidence.Labels, []string{"before", "since"}) || f.Evidence.Shape != "scale" { + t.Errorf("Evidence = %+v", f.Evidence) + } + + band := s.BandEntries(now) + if len(band) != 1 || band[0].ID != "effect:r1" || band[0].Group != "feedback" { + t.Fatalf("BandEntries = %+v, want one feedback entry", band) + } + if late := s.BandEntries(at.Add(8*7*24*time.Hour + time.Hour)); len(late) != 0 { + t.Errorf("BandEntries eight weeks later = %d, want 0", len(late)) + } +} + +func TestEffectStoreRemovedRuleIsDropped(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(effHandHeater)) + now := effAt(2026, 7, loc).AddDate(0, 0, 7) + docs := map[string]Doc{ + "rule deleted": {}, + "learned_from unset": {Rules: []Rule{{ID: "r1"}}}, + } + for name, doc := range docs { + s := effStoreAt(t) + s.Sync(effDoc("r1", effSugg, "switch_time", at), at, days, nil, effMark()) + s.Nightly(now, days, effStore(t), nil) + if added := s.Sync(doc, at, days, nil, effMark()); added { + t.Errorf("%s: Sync reported an added entry", name) + } + if s.Len() != 0 || len(s.Findings(now)) != 0 || len(s.BandEntries(now)) != 0 { + t.Errorf("%s: entry kept, Len = %d", name, s.Len()) + } + } +} + +func TestEffectStoreChangedAtRestarts(t *testing.T) { + loc := berlinLoc(t) + hand := map[int]uint8{1: 10, 2: 10, 3: 10, 4: 10, 5: 4, 6: 4, 7: 4} + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(hand)) + s := effStoreAt(t) + at := effAt(2026, 5, loc) + s.Sync(effDoc("r1", effSugg, "switch_time", at), at, days, nil, effMark()) + + at2 := effAt(2026, 7, loc) + doc := effDoc("r1", effSugg, "switch_time", at2) + if !s.NeedsDays(doc) { + t.Fatal("NeedsDays false after learned_from.at changed") + } + if !s.Sync(doc, at2, days, nil, effMark()) { + t.Fatal("Sync did not restart the entry") + } + if want := []float64{10, 10, 4, 4}; !reflect.DeepEqual(s.entries["r1"].Before, want) { + t.Errorf("Before = %v, want %v", s.entries["r1"].Before, want) + } +} + +func TestEffectStoreResetWithoutDays(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + now := effAt(2026, 7, loc).AddDate(0, 0, 7) + s := effStoreAt(t) + doc := effDoc("r1", effSugg, "switch_time", at) + s.Sync(doc, at, nil, nil, effMark()) + s.Save() + if err := s.Reset(); err != nil { + t.Fatalf("Reset: %v", err) + } + if s.Len() != 0 { + t.Fatalf("Len after Reset = %d", s.Len()) + } + if _, err := os.Stat(s.path); !os.IsNotExist(err) { + t.Errorf("file after Reset: %v", err) + } + if err := s.Reset(); err != nil { + t.Errorf("Reset of a missing file: %v", err) + } + + if !s.Sync(doc, at, nil, nil, effMark()) { + t.Fatal("Sync after Reset added nothing") + } + s.Nightly(now, nil, effStore(t), nil) + fs := s.Findings(now) + if len(fs) != 1 || fs[0].Summary.Code != "effect.no_baseline" { + t.Fatalf("Findings = %+v, want one effect.no_baseline", fs) + } + if len(s.BandEntries(now)) != 0 { + t.Error("BandEntries not empty without a baseline") + } +} + +func TestEffectStoreDerivesFromKind(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + s := effStoreAt(t) + sugg := "switch_time:plug.heater:on:0:0700" + s.Sync(effDoc("r1", sugg, "switch_time", at), at, nil, nil, nil) + e := s.entries["r1"] + if e.Unit != effectUnitActions || e.Group != "habit" || e.Device != "plug.heater" { + t.Errorf("derived unit, group, device = %q, %q, %q", e.Unit, e.Group, e.Device) + } + + s2 := effStoreAt(t) + sugg2 := "temp_limit:plug.heater:x" + s2.Sync(effDoc("r2", sugg2, "temp_limit", at), at, nil, nil, nil) + if e := s2.entries["r2"]; e.Unit != "" || e.Device != "" { + t.Errorf("temp_limit without device: unit %q, device %q, want empty", e.Unit, e.Device) + } +} + +func TestEffectStoreSaveLoadAndDamaged(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(effHandHeater)) + path := filepath.Join(t.TempDir(), "effect.json") + s := LoadEffectStore(path, nil) + shown := map[string]Shown{effSugg: {Values: map[string]float64{"n": 3}}} + s.Sync(effDoc("r1", effSugg, "switch_time", at), at, days, shown, effMark()) + + back := LoadEffectStore(path, nil) + if back.Len() != 1 { + t.Fatalf("reloaded Len = %d, want 1", back.Len()) + } + e := back.entries["r1"] + if !reflect.DeepEqual(e.Before, []float64{10, 10, 10, 10}) || e.Values["n"] != 3 || e.Device != effDev { + t.Errorf("reloaded entry = %+v", e) + } + + if err := os.WriteFile(path, []byte("{not json"), 0o644); err != nil { + t.Fatal(err) + } + logged := 0 + damaged := LoadEffectStore(path, func(string, ...any) { logged++ }) + if damaged.Len() != 0 || logged == 0 { + t.Errorf("damaged file: Len = %d, logged = %d, want empty and logged", damaged.Len(), logged) + } +} diff --git a/dashboard/internal/autolearn/effect_test.go b/dashboard/internal/autolearn/effect_test.go index d298405d..3c00afd9 100644 --- a/dashboard/internal/autolearn/effect_test.go +++ b/dashboard/internal/autolearn/effect_test.go @@ -286,3 +286,34 @@ func TestEffectBaselineWeeksWithFiveDaysAreOK(t *testing.T) { t.Error("Estimate set although the baseline weeks have five days and the prior year is there") } } + +// TestEffectSeasonDenominatorWithoutBaselineDays: the prior-year denominator +// comes from the adoption date, so it holds once the baseline day files are +// pruned. The expectation equals the one with the baseline day files. +func TestEffectSeasonDenominatorWithoutBaselineDays(t *testing.T) { + loc := berlinLoc(t) + before := []float64{6.72, 6.72, 6.72, 6.72} + full := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + before, effGridDays(t, loc), effPriorPV(t), loc) + + grid := map[int]float32{9: 40, 10: 44, 11: 44} + pruned := effDays(t, loc, 2026, []int{9, 10, 11}, effGridFill(grid)) + res := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + before, pruned, effPriorPV(t), loc) + + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if res.Estimate { + t.Error("Estimate set although the prior year is there") + } + if len(res.Expected) != len(full.Expected) || len(res.Since) != len(full.Since) { + t.Fatalf("Expected = %v, want %v", res.Expected, full.Expected) + } + for i := range full.Expected { + if !effClose(res.Expected[i], full.Expected[i]) || !effClose(res.Since[i], full.Since[i]) { + t.Errorf("week %d: Expected %v, Since %v, want %v and %v", + i, res.Expected[i], res.Since[i], full.Expected[i], full.Since[i]) + } + } +} diff --git a/dashboard/internal/autolearn/finding.go b/dashboard/internal/autolearn/finding.go index 6f3581c6..4b6ea239 100644 --- a/dashboard/internal/autolearn/finding.go +++ b/dashboard/internal/autolearn/finding.go @@ -90,6 +90,8 @@ type Evidence struct { SollQ []float32 `json:"soll_q,omitempty"` BestQ []float32 `json:"best_q,omitempty"` Unit string `json:"unit,omitempty"` + // Labels names the Ist and Soll side of a scale, such as "before" and "since". + Labels []string `json:"labels,omitempty"` Max float64 `json:"max,omitempty"` Seen [2]float64 `json:"seen,omitempty"` IstValue *float64 `json:"ist_value,omitempty"` From d024c0df26e7be318fc35170bd5814bd0556f79c Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:02:03 +0100 Subject: [PATCH 07/34] feat(autolearn): show the effect of adopted suggestions on the rule and in the band Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_effect_test.go | 74 +++++++++++++++++++ dashboard/cmd/dashboard/learn_engine.go | 64 ++++++++++++++++ dashboard/cmd/dashboard/learn_suggestions.go | 48 ++++++++++-- .../cmd/dashboard/learn_suggestions_test.go | 54 ++++++++++++++ dashboard/cmd/dashboard/main.go | 45 ++++++++++- dashboard/internal/autolearn/checker.go | 32 +++++++- dashboard/internal/autolearn/checker_test.go | 52 +++++++++++++ 7 files changed, 360 insertions(+), 9 deletions(-) create mode 100644 dashboard/cmd/dashboard/learn_effect_test.go diff --git a/dashboard/cmd/dashboard/learn_effect_test.go b/dashboard/cmd/dashboard/learn_effect_test.go new file mode 100644 index 00000000..bb7cbee1 --- /dev/null +++ b/dashboard/cmd/dashboard/learn_effect_test.go @@ -0,0 +1,74 @@ +package main + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" +) + +// effectTestRunner builds an effect runner over a fixed rule document and +// counts the day file loads. +func effectTestRunner(t *testing.T, doc []byte, loads *int) *effectRunner { + t.Helper() + dir := t.TempDir() + return &effectRunner{ + store: autolearn.LoadEffectStore(filepath.Join(dir, "effects.json"), nil), + readDoc: func() ([]byte, error) { return doc, nil }, + days: func(from, to time.Time) ([]autolearn.DayFile, error) { + *loads++ + return nil, nil + }, + candidates: func() []autolearn.Candidate { return nil }, + shown: func() map[string]autolearn.Shown { return nil }, + season: autolearn.LoadSeasonStore(filepath.Join(dir, "season.json"), nil), + enabled: func() bool { return true }, + } +} + +func TestEffectRunnerLoadsDaysOnlyForNewRuleOrDailyRun(t *testing.T) { + loads := 0 + r := effectTestRunner(t, []byte(effectRuleDoc), &loads) + now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.Local) + + r.Run(now) + r.Run(now.Add(time.Minute)) + r.Run(now.Add(2 * time.Minute)) + if loads != 1 { + t.Fatalf("day file loads over three rounds of one day = %d, want 1 (the new rule)", loads) + } + if r.store.Len() != 1 { + t.Fatalf("entries = %d, want 1 for the learned rule", r.store.Len()) + } + + // The next morning the daily run loads the day files again, once. + r.Run(time.Date(2026, 11, 26, 4, 0, 0, 0, time.Local)) + if loads != 2 { + t.Fatalf("day file loads after the daily run = %d, want 2", loads) + } +} + +func TestEffectRunnerUnreadableDocumentKeepsEntries(t *testing.T) { + loads := 0 + r := effectTestRunner(t, []byte(effectRuleDoc), &loads) + now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.Local) + r.Run(now) + + r.readDoc = func() ([]byte, error) { return nil, os.ErrNotExist } + r.Run(now.AddDate(0, 0, 1).Add(5 * time.Hour)) + if r.store.Len() != 1 { + t.Fatalf("entries after an unreadable document = %d, want 1 kept", r.store.Len()) + } +} + +func TestEffectRunnerDisabledDoesNothing(t *testing.T) { + loads := 0 + r := effectTestRunner(t, []byte(effectRuleDoc), &loads) + r.enabled = func() bool { return false } + r.Run(time.Date(2026, 11, 25, 10, 0, 0, 0, time.Local)) + if loads != 0 || r.store.Len() != 0 { + t.Fatalf("disabled runner loads = %d, entries = %d, want none", loads, r.store.Len()) + } +} diff --git a/dashboard/cmd/dashboard/learn_engine.go b/dashboard/cmd/dashboard/learn_engine.go index d66f1525..92f8fbc9 100644 --- a/dashboard/cmd/dashboard/learn_engine.go +++ b/dashboard/cmd/dashboard/learn_engine.go @@ -534,3 +534,67 @@ func (c *cycleRunner) Reset() error { } return nil } + +// effectNightlyAt is the time of day from which the effect runner takes its +// daily run, once per calendar day. +const effectNightlyAt = 3*time.Hour + 30*time.Minute + +// effectRunner keeps the effect store current after every engine round. It runs +// in the engine round goroutine, so it needs no lock. done is the calendar day +// of the last daily run. +type effectRunner struct { + store *autolearn.EffectStore + readDoc func() ([]byte, error) + days func(from, to time.Time) ([]autolearn.DayFile, error) + candidates func() []autolearn.Candidate + shown func() map[string]autolearn.Shown + season *autolearn.SeasonStore + enabled func() bool + done string +} + +// Run takes the entries of new learned rules and, once a day, recomputes every +// effect. The day files are read only when a rule is new or on the daily run. +// An unreadable document or day file changes nothing, so the next round retries. +func (r *effectRunner) Run(now time.Time) { + if !r.enabled() { + return + } + raw, err := r.readDoc() + if err != nil { + return + } + doc, err := autolearn.ParseDoc(raw) + if err != nil { + return + } + day := now.Format("2006-01-02") + at := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Add(effectNightlyAt) + nightly := r.done == "" || (day != r.done && !now.Before(at)) + needs := r.store.NeedsDays(doc) + var days []autolearn.DayFile + if needs || (nightly && r.store.Len() > 0) { + days, err = r.days(now.AddDate(0, 0, -366), now) + if err != nil { + log.Printf("autolearn: effect day files unreadable, retrying next round: %v", err) + return + } + } + cands := r.candidates() + byID := make(map[string]autolearn.Finding, len(cands)) + for _, c := range cands { + f := c.Finding + if f.Benefit == nil { + b := c.Benefit + f.Benefit = &b + } + byID[f.ID] = f + } + added := r.store.Sync(doc, now, days, r.shown(), byID) + if added || nightly { + r.store.Nightly(now, days, r.season, cands) + } + if nightly { + r.done = day + } +} diff --git a/dashboard/cmd/dashboard/learn_suggestions.go b/dashboard/cmd/dashboard/learn_suggestions.go index 7e7fdfa8..1e25143b 100644 --- a/dashboard/cmd/dashboard/learn_suggestions.go +++ b/dashboard/cmd/dashboard/learn_suggestions.go @@ -25,12 +25,15 @@ type suggestionBook struct { recentC *float64 // readDoc returns the current rule document, nil keeps every suggestion. readDoc func() ([]byte, error) + // effects returns the effect findings of the adopted suggestions, nil for none. + effects func(now time.Time) []autolearn.Finding } // Visible returns the suggestions to show now, without dismissed or postponed // ones, without devices exists rejects and without the ones the current rule // document already holds. The rules are read on every call, so an applied -// suggestion vanishes before the next engine round. +// suggestion vanishes before the next engine round. The effects of adopted +// suggestions follow the suggestions, for rules that still came from one. func (b *suggestionBook) Visible(now time.Time, exists func(device string) bool) []autolearn.Finding { b.mu.Lock() all := append([]autolearn.Finding(nil), b.all...) @@ -38,13 +41,39 @@ func (b *suggestionBook) Visible(now time.Time, exists func(device string) bool) b.mu.Unlock() visible := b.state.Visible(all, now, exists, recentC) doc, ok := b.currentDoc() - if !ok { + if ok { + var out []autolearn.Finding + for _, f := range visible { + if !f.AppliedIn(doc) { + out = append(out, f) + } + } + visible = out + } + if b.effects == nil { return visible } - var out []autolearn.Finding - for _, f := range visible { - if !f.AppliedIn(doc) { - out = append(out, f) + learned := learnedRuleIDs(doc) + for _, f := range b.state.Visible(b.effects(now), now, exists, nil) { + if !ok || (len(f.RuleIDs) > 0 && learned[f.RuleIDs[0]]) { + visible = append(visible, f) + } + } + return visible +} + +// learnedRuleIDs holds the IDs of the rules and scenarios of doc that came from +// a learned suggestion. +func learnedRuleIDs(doc autolearn.Doc) map[string]bool { + out := map[string]bool{} + for _, r := range doc.Rules { + if r.LearnedFrom != nil { + out[r.ID] = true + } + } + for _, sc := range doc.Scenarios { + if sc.LearnedFrom != nil { + out[sc.ID] = true } } return out @@ -74,6 +103,13 @@ func (b *suggestionBook) Known(id string) bool { if b.state.Hidden(id) { return true } + if b.effects != nil { + for _, f := range b.effects(time.Now()) { + if f.ID == id { + return true + } + } + } b.mu.Lock() defer b.mu.Unlock() for _, f := range b.all { diff --git a/dashboard/cmd/dashboard/learn_suggestions_test.go b/dashboard/cmd/dashboard/learn_suggestions_test.go index 64c1eae6..fcb22d57 100644 --- a/dashboard/cmd/dashboard/learn_suggestions_test.go +++ b/dashboard/cmd/dashboard/learn_suggestions_test.go @@ -350,3 +350,57 @@ func TestVisibleKeepsSuggestionWhenRuleUnreadable(t *testing.T) { t.Fatalf("visible = %d, want 1 when the rules cannot be read", len(got)) } } + +// effectRuleDoc holds r1 from a learned suggestion and r2 made by hand. +const effectRuleDoc = `{"rules":[{"id":"r1","name":"Heizung","enabled":true,"conditions":[],"actions":[],"learned_from":{"suggestion":"switchtime:r1:dev-a","kind":"switch_time","at":1700000000}},{"id":"r2","name":"Licht","enabled":true,"conditions":[],"actions":[]}]}` + +func effectFinding(rule string) autolearn.Finding { + return autolearn.Finding{ID: "effect:" + rule, Kind: "effect", Group: "feedback", RuleIDs: []string{rule}, Device: "dev-a", Severity: "info", Confidence: "high"} +} + +func effectBook(t *testing.T, doc string, effects ...autolearn.Finding) *suggestionBook { + t.Helper() + state := autolearn.LoadSuggestionState(filepath.Join(t.TempDir(), "suggestions.json"), nil) + return &suggestionBook{ + state: state, + readDoc: func() ([]byte, error) { return []byte(doc), nil }, + effects: func(time.Time) []autolearn.Finding { return effects }, + } +} + +func TestVisibleShowsEffectOfLearnedRule(t *testing.T) { + book := effectBook(t, effectRuleDoc, effectFinding("r1")) + got := book.Visible(time.Now(), func(string) bool { return true }) + if len(got) != 1 || got[0].ID != "effect:r1" { + t.Fatalf("visible = %+v, want effect:r1", got) + } +} + +func TestVisibleHidesEffectOfRuleWithoutLearnedFrom(t *testing.T) { + book := effectBook(t, effectRuleDoc, effectFinding("r2")) + if got := book.Visible(time.Now(), func(string) bool { return true }); len(got) != 0 { + t.Fatalf("effect of a hand made rule visible: %+v", got) + } +} + +func TestDismissedEffectStaysKnown(t *testing.T) { + book := effectBook(t, effectRuleDoc, effectFinding("r1")) + exists := func(string) bool { return true } + if err := book.Dismiss("effect:r1", time.Now()); err != nil { + t.Fatal(err) + } + if got := book.Visible(time.Now(), exists); len(got) != 0 { + t.Fatalf("dismissed effect visible: %+v", got) + } + if !book.Known("effect:r1") { + t.Fatal("dismissed effect must stay known") + } +} + +func TestVisibleShowsEffectWhenRuleUnreadable(t *testing.T) { + book := effectBook(t, "", effectFinding("r1")) + book.readDoc = func() ([]byte, error) { return nil, os.ErrNotExist } + if got := book.Visible(time.Now(), func(string) bool { return true }); len(got) != 1 { + t.Fatalf("visible = %d, want the effect without a readable document", len(got)) + } +} diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index db219128..ffcc9060 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -673,6 +673,23 @@ func main() { // Datei liegt unter autolearn/ und wird mit dem Hub gespeichert. learnedStore := autolearn.LoadLearnedStore(filepath.Join(autolearnDir, "learned.json"), log.Printf) learnHub.AddSaver("learned", learnedStore) + // Wirkung der angenommenen Vorschlaege, nach jeder Runde durch den Effektlauf aktualisiert. + effectStore := autolearn.LoadEffectStore(filepath.Join(autolearnDir, "effects.json"), log.Printf) + learnHub.AddSaver("effects", effectStore) + learnHub.AddResetter("effects", effectStore) + // Die Wirkung zeigt die Regelpruefung und das Band, solange das Muster-Lernen an ist. + effectsOn := func() bool { + if value, err := settingsStore.LoadSettings(); err == nil && value.AutomationPatternsDisabled { + return false + } + return true + } + automationChecker.SetEffectSource(func(now time.Time) []autolearn.Finding { + if !effectsOn() { + return nil + } + return effectStore.Findings(now) + }) // Monitoring: Meldungen aus Energie, Ketten und Regelpruefung, je Minute // gesammelt, beim Abruf frisch und mit dem Hub gespeichert. // Vorschlaege fuer das Monitoring. Die Funktion wird unten gesetzt, sobald das @@ -727,6 +744,21 @@ func main() { seasonClose := &seasonCloser{store: seasonStore, days: dayStore.Days, learned: learnedClockMinutes(learnedStore), site: ruleSite(func() ([]byte, error) { return configManager.Read("automation_rules") }), loc: time.Local} suggestions := &suggestionBook{state: suggestionState, readDoc: func() ([]byte, error) { return configManager.Read("automation_rules") }} + suggestions.effects = func(now time.Time) []autolearn.Finding { + if !effectsOn() { + return nil + } + return effectStore.BandEntries(now) + } + effectLoop := &effectRunner{ + store: effectStore, + readDoc: func() ([]byte, error) { return configManager.Read("automation_rules") }, + days: dayStore.Days, + candidates: automationEngine.Candidates, + shown: suggestionState.Shown, + season: seasonStore, + enabled: effectsOn, + } suggestionExists := func(device string) bool { if deviceFilterStore.IsIgnored(device) { return false @@ -739,7 +771,14 @@ func main() { if value, err := settingsStore.LoadSettings(); err == nil && value.AutomationPatternsDisabled { return nil } - return suggestions.Visible(time.Now(), suggestionExists) + // The effects of adopted suggestions belong to the rule check, not to Monitoring. + var out []autolearn.Finding + for _, f := range suggestions.Visible(time.Now(), suggestionExists) { + if f.Group != "feedback" { + out = append(out, f) + } + } + return out } origin := newOriginLearner(originTracker, dayStore, reg, func() ([]byte, error) { return configManager.Read("automation_rules") }) @@ -938,9 +977,11 @@ func main() { learnedValues = func() []autolearn.Value { return autolearn.WithDemoHouseState(automationEngine.Values()) } } engineLoop.afterRound = func() { + // The effects come before the gate, which drops the adopted suggestion from the shown state. + seasonClose.Run(time.Now()) + effectLoop.Run(time.Now()) gateSuggestions(suggestions, automationEngine, func() ([]byte, error) { return configManager.Read("automation_rules") }, engineGroups(), suggestionExists, time.Now()) publishLearned(learnedStore, learnedValues, client, engineGroups()["habit"], learnedExists, time.Now()) - seasonClose.Run(time.Now()) } go engineLoop.Run(ctx) diff --git a/dashboard/internal/autolearn/checker.go b/dashboard/internal/autolearn/checker.go index d8f91f55..c8187eae 100644 --- a/dashboard/internal/autolearn/checker.go +++ b/dashboard/internal/autolearn/checker.go @@ -43,6 +43,8 @@ type Checker struct { pv PVSource // replay gives the input of the replay checks, nil until SetReplaySource is called. replay func() *Input + // effects gives the effect findings of the adopted suggestions, nil until SetEffectSource is called. + effects func(now time.Time) []Finding // replayIn is the input built at replayAt, kept for checkerReplayEvery. // replayBuilt is false until the first build. replayIn *Input @@ -110,6 +112,33 @@ func (c *Checker) SetEngineSource(candidates func() []Candidate, reliabilityOn f c.reliabilityOn = reliabilityOn } +// SetEffectSource connects the effect store. Its findings are listed only for +// rules and scenarios that still came from a learned suggestion. +func (c *Checker) SetEffectSource(effects func(now time.Time) []Finding) { + c.mu.Lock() + defer c.mu.Unlock() + c.effects = effects +} + +// effectsLocked returns the effect findings of rules that still came from a +// learned suggestion. Nothing is returned without a source or without a readable document. +func (c *Checker) effectsLocked(now time.Time) []Finding { + if c.effects == nil || !c.docOK { + return nil + } + marks := learnedMarks(c.doc) + var out []Finding + for _, f := range c.effects(now) { + if len(f.RuleIDs) == 0 { + continue + } + if _, ok := marks[f.RuleIDs[0]]; ok { + out = append(out, f) + } + } + return out +} + // SetReplaySource gives the checker the input the replay evidence and the // minute noise are read from, the same data the engine reads. Without it the // frequent check keeps its fallback hysteresis and no replay evidence. @@ -145,7 +174,7 @@ func hasEnabledRule(doc Doc) bool { return false } -// Findings returns the static, observed and reliability findings without the +// Findings returns the static, observed, reliability and effect findings without the // ignored ones, ordered by severity and ID, at most 20. Ignored IDs of rules that no longer // exist are removed from the ignored file here. func (c *Checker) Findings(now time.Time) []Finding { @@ -158,6 +187,7 @@ func (c *Checker) Findings(now time.Time) []Finding { all := StaticFindings(c.doc, c.entityExists) all = append(all, ObservedFindingsWithPV(c.doc, c.obs.Snapshot(), c.season, c.pv, c.replayInputLocked(now), now, c.thresholds)...) all = append(all, c.reliabilityLocked()...) + all = append(all, c.effectsLocked(now)...) sort.SliceStable(all, func(i, j int) bool { ri, rj := severityRank[all[i].Severity], severityRank[all[j].Severity] if ri != rj { diff --git a/dashboard/internal/autolearn/checker_test.go b/dashboard/internal/autolearn/checker_test.go index 2698b105..046bf9a0 100644 --- a/dashboard/internal/autolearn/checker_test.go +++ b/dashboard/internal/autolearn/checker_test.go @@ -470,3 +470,55 @@ func TestNotRuleSendsFindingsWithoutFixToMonitoring(t *testing.T) { } } } + +// effectDoc has two rules: r1 came from a learned suggestion, r2 was made by hand. +const effectDoc = `{"rules":[{"id":"r1","name":"Heizung","enabled":true,"conditions":[],"actions":[],"learned_from":{"suggestion":"switchtime:r1:dev-a","kind":"switch_time","at":1700000000}},{"id":"r2","name":"Licht","enabled":true,"conditions":[],"actions":[]}]}` + +func effectFindingFor(ruleID string) Finding { + return Finding{ID: FindingID("effect", ruleID), Kind: "effect", Group: "check", RuleIDs: []string{ruleID}, Severity: "info", Confidence: "high"} +} + +func checkerWithEffects(t *testing.T, path string) *Checker { + t.Helper() + c := NewChecker(NewObserver(time.UTC), nil, staticRead(effectDoc), nil, path, t.Logf) + c.SetEffectSource(func(time.Time) []Finding { + return []Finding{effectFindingFor("r1"), effectFindingFor("r2")} + }) + return c +} + +func effectIDs(fs []Finding) []string { + var ids []string + for _, f := range fs { + if strings.HasPrefix(f.ID, "effect:") { + ids = append(ids, f.ID) + } + } + return ids +} + +func TestCheckerListsEffectOnlyForLearnedRule(t *testing.T) { + c := checkerWithEffects(t, "") + got := effectIDs(c.Findings(testBase)) + if len(got) != 1 || got[0] != "effect:r1" { + t.Fatalf("effect findings = %v, want [effect:r1]", got) + } +} + +func TestCheckerEffectFindingCanBeIgnored(t *testing.T) { + c := checkerWithEffects(t, filepath.Join(t.TempDir(), "ignored.json")) + if err := c.Ignore("effect:r1"); err != nil { + t.Fatalf("Ignore: %v", err) + } + if got := effectIDs(c.Findings(testBase)); len(got) != 0 { + t.Fatalf("ignored effect still listed: %v", got) + } +} + +func TestCheckerEffectFindingsNeedReadableDocument(t *testing.T) { + c := NewChecker(NewObserver(time.UTC), nil, func() ([]byte, error) { return nil, os.ErrNotExist }, nil, "", t.Logf) + c.SetEffectSource(func(time.Time) []Finding { return []Finding{effectFindingFor("r1")} }) + if got := effectIDs(c.Findings(testBase)); len(got) != 0 { + t.Fatalf("effect findings without a document: %v", got) + } +} From 479c1257e9d647f579505b53f1e4be37ab38de52 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:04:55 +0100 Subject: [PATCH 08/34] feat(autolearn): report when an adopted suggestion drifts with the season Nightly, each learned entry keeps one standardised drift value per day, the difference between the adopted and the current suggested values in spreads. A CUSUM over the last 28 days raises a season_shift finding with replacing fixes once the drift is beyond the slack. A candidate that moved its switch time is matched by its ID prefix. Drift findings are reported with the rule check, never on the band. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/effect_store.go | 193 +++++++++++++++++- .../internal/autolearn/effect_store_test.go | 189 +++++++++++++++++ dashboard/internal/autolearn/finding.go | 2 + 3 files changed, 378 insertions(+), 6 deletions(-) diff --git a/dashboard/internal/autolearn/effect_store.go b/dashboard/internal/autolearn/effect_store.go index 0d42b8ca..fb3faa66 100644 --- a/dashboard/internal/autolearn/effect_store.go +++ b/dashboard/internal/autolearn/effect_store.go @@ -31,6 +31,12 @@ type effectEntry struct { Before []float64 `json:"before,omitempty"` Values map[string]float64 `json:"values,omitempty"` Result EffectResult `json:"result"` + // Series holds the nightly season drift in standard deviations, one value + // per day, the last at SeriesDay. Drift is the season shift finding, nil + // when the adopted suggestion does not drift. + Series []float64 `json:"series,omitempty"` + SeriesDay string `json:"series_day,omitempty"` + Drift *Finding `json:"drift,omitempty"` } // effectFile is the content of the effect store file. @@ -160,7 +166,8 @@ func (s *EffectStore) Sync(doc Doc, now time.Time, days []DayFile, shown map[str } // Nightly computes the effect of every entry from the day files and the season -// store, then saves the store. cands is unused for now. The season drift reads it. +// store, then advances the season drift with the current candidates, then saves +// the store. func (s *EffectStore) Nightly(now time.Time, days []DayFile, season *SeasonStore, cands []Candidate) { s.mu.Lock() defer s.mu.Unlock() @@ -170,6 +177,7 @@ func (s *EffectStore) Nightly(now time.Time, days []DayFile, season *SeasonStore res := ComputeEffect(at, e.Unit, e.Group, e.Device, e.Before, days, season, loc) res.Overridden, res.Fired = OverrideCount(days, id, at) e.Result = res + shiftStep(&e, now, cands) s.entries[id] = e } if err := s.saveLocked(); err != nil { @@ -177,17 +185,20 @@ func (s *EffectStore) Nightly(now time.Time, days []DayFile, season *SeasonStore } } -// Findings returns one check finding per entry with a computed effect, sorted -// by rule ID. +// Findings returns one check finding per entry with a computed effect, and the +// season shift finding of every entry that drifts. Sorted by rule ID, the +// effect finding first. func (s *EffectStore) Findings(now time.Time) []Finding { s.mu.Lock() defer s.mu.Unlock() out := []Finding{} for _, e := range s.sortedLocked() { - if e.Result.Status == "" { - continue + if e.Result.Status != "" { + out = append(out, effectFinding(e, FindingID("effect", e.Rule), "check", now.Location())) + } + if e.Drift != nil { + out = append(out, *e.Drift) } - out = append(out, effectFinding(e, FindingID("effect", e.Rule), "check", now.Location())) } return out } @@ -361,3 +372,173 @@ func effectFinding(e effectEntry, id, group string, loc *time.Location) Finding func effectRound(x float64) float64 { return math.Round(x*10) / 10 } + +// shiftSeriesMax is the number of nightly drift values kept per entry. +const shiftSeriesMax = 28 + +// shiftKey is one key of an adopted suggestion that the candidate still has: +// its value at adoption, now and the drift d in spreads. +type shiftKey struct { + name string + at float64 + now float64 + d float64 +} + +// shiftClockKey tells whether a key is a time of day. +func shiftClockKey(k string) bool { + return k == "time" || k == "latest" || k == "start" +} + +// shiftStep appends the drift of the night now to the series of e and sets +// e.Drift. With no matching candidate or no comparable key the series pauses. +func shiftStep(e *effectEntry, now time.Time, cands []Candidate) { + c := shiftMatch(*e, cands) + if c == nil { + e.Drift = nil + return + } + keys := shiftKeys(*e, c) + if len(keys) == 0 { + e.Drift = nil + return + } + best := keys[0] + for _, k := range keys[1:] { + if math.Abs(k.d) > math.Abs(best.d) { + best = k + } + } + today := now.Format(dayLayout) + if e.SeriesDay == today && len(e.Series) > 0 { + e.Series[len(e.Series)-1] = best.d + } else { + e.Series = append(e.Series, best.d) + e.SeriesDay = today + } + if n := len(e.Series); n > shiftSeriesMax { + e.Series = append([]float64(nil), e.Series[n-shiftSeriesMax:]...) + } + e.Drift = shiftFinding(*e, c, keys, best) +} + +// shiftMatch finds the candidate of the entry's suggestion. A switch time +// that moved within 180 minutes keeps its suggestion ID up to the last ":", so +// the candidate with that prefix and the closest time is taken instead. +func shiftMatch(e effectEntry, cands []Candidate) *Candidate { + for i := range cands { + if cands[i].Finding.ID == e.Suggestion { + return &cands[i] + } + } + if e.Kind != "switch_time" { + return nil + } + t0, ok := e.Values["time"] + cut := strings.LastIndex(e.Suggestion, ":") + if !ok || cut < 0 { + return nil + } + prefix := e.Suggestion[:cut+1] + var best *Candidate + bestD := 180.0 + for i := range cands { + id := cands[i].Finding.ID + j := strings.LastIndex(id, ":") + if j < 0 || id[:j+1] != prefix { + continue + } + tv, ok := cands[i].Values["time"] + if !ok { + continue + } + if d := math.Abs(circDelta(tv, t0)); d <= bestD { + best, bestD = &cands[i], d + } + } + return best +} + +// shiftKeys lists the keys present in the entry and in the candidate with a +// positive spread, sorted by name. +func shiftKeys(e effectEntry, c *Candidate) []shiftKey { + names := make([]string, 0, len(e.Values)) + for k := range e.Values { + names = append(names, k) + } + sort.Strings(names) + var out []shiftKey + for _, k := range names { + now, ok := c.Values[k] + if !ok || !(c.Spread[k] > 0) { + continue + } + at := e.Values[k] + diff := now - at + if shiftClockKey(k) { + diff = circDelta(now, at) + } + out = append(out, shiftKey{name: k, at: at, now: now, d: diff / c.Spread[k]}) + } + return out +} + +// shiftValue formats a key value for the text: HH:MM for times, else one decimal. +func shiftValue(key string, v float64) any { + if shiftClockKey(key) { + return switchTimeClock(wrapMinutes(v)) + } + return effectRound(v) +} + +// shiftFinding is the season shift finding of e when the series has drifted +// beyond the slack in the direction of its latest value, nil otherwise. +func shiftFinding(e effectEntry, c *Candidate, keys []shiftKey, best shiftKey) *Finding { + _, up, ok := CUSUM(e.Series, 0, 1) + if !ok { + return nil + } + last := e.Series[len(e.Series)-1] + if (up && last <= cusumK) || (!up && last >= -cusumK) { + return nil + } + bars := make([]ScaleBar, 0, len(keys)) + for _, k := range keys { + bar := ScaleBar{Name: k.name, Ist: k.at, Soll: k.now} + if shiftClockKey(k.name) { + bar.Unit = "clock" + } + bars = append(bars, bar) + } + fixes := make([]Fix, 0, len(c.Finding.Apply)) + var learned []Fix + for _, fx := range c.Finding.Apply { + fx.RuleID = e.Rule + fx.Replace = true + if strings.Contains(fx.Code, "learned") { + learned = append(learned, fx) + continue + } + fixes = append(fixes, fx) + } + fixes = append(fixes, learned...) + params := map[string]any{ + "key": best.name, + "old": shiftValue(best.name, best.at), + "new": shiftValue(best.name, best.now), + "device": e.Device, + } + return &Finding{ + ID: FindingID("season_shift", e.Rule), + Kind: "season_shift", + Group: "check", + RuleIDs: []string{e.Rule}, + Severity: "warn", + Confidence: "estimate", + Device: e.Device, + Summary: Text{Code: "season_shift." + e.Kind, Params: params}, + Evidence: Evidence{Shape: "scale", Scales: bars}, + Facts: []Fact{}, + Apply: fixes, + } +} diff --git a/dashboard/internal/autolearn/effect_store_test.go b/dashboard/internal/autolearn/effect_store_test.go index 211b7950..d524bd4d 100644 --- a/dashboard/internal/autolearn/effect_store_test.go +++ b/dashboard/internal/autolearn/effect_store_test.go @@ -218,3 +218,192 @@ func TestEffectStoreSaveLoadAndDamaged(t *testing.T) { t.Errorf("damaged file: Len = %d, logged = %d, want empty and logged", damaged.Len(), logged) } } + +const driftSugg = "switch_time:plug.heater:on:0:2230" + +// driftCand is a candidate of the switch time suggestion at minute tm with two +// fixes, the learned one listed first. +func driftCand(id string, tm float64) Candidate { + return Candidate{ + Finding: Finding{ID: id, Kind: "switch_time", Apply: []Fix{ + {Code: "time_point_learned", Ops: []Op{}}, + {Code: "time_point", Ops: []Op{}}, + }}, + Values: map[string]float64{"time": tm, "hit_rate": 0.9}, + Spread: map[string]float64{"time": 10}, + } +} + +// driftStore adopts driftSugg at week 5 with the time 1350 and returns the store and the adoption. +func driftStore(t *testing.T) (*EffectStore, Doc, time.Time) { + t.Helper() + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + s := effStoreAt(t) + doc := effDoc("r1", driftSugg, "switch_time", at) + shown := map[string]Shown{driftSugg: {Values: map[string]float64{"time": 1350, "hit_rate": 0.9}}} + s.Sync(doc, at, nil, shown, nil) + return s, doc, at +} + +// driftNight runs one nightly pass n days after the adoption with the candidates cands. +func driftNight(t *testing.T, s *EffectStore, at time.Time, n int, cands []Candidate) { + t.Helper() + s.Nightly(at.AddDate(0, 0, n), nil, effStore(t), cands) +} + +func seasonFindings(fs []Finding) []Finding { + var out []Finding + for _, f := range fs { + if f.Kind == "season_shift" { + out = append(out, f) + } + } + return out +} + +func TestSeasonDriftReported(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 20; n++ { + switch { + case n <= 8: + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, 1350)}) + default: + driftNight(t, s, at, n, []Candidate{driftCand("switch_time:plug.heater:on:0:2200", 1305)}) + } + } + now := at.AddDate(0, 0, 20) + fs := seasonFindings(s.Findings(now)) + if len(fs) != 1 { + t.Fatalf("season findings = %d, want 1", len(fs)) + } + f := fs[0] + if f.ID != "season_shift:r1" || f.Group != "check" || f.Severity != "warn" || f.Confidence != "estimate" { + t.Errorf("finding = %+v", f) + } + if f.Summary.Code != "season_shift.switch_time" { + t.Fatalf("Summary.Code = %q", f.Summary.Code) + } + if f.Summary.Params["old"] != "22:30" || f.Summary.Params["new"] != "21:45" || f.Summary.Params["key"] != "time" { + t.Errorf("Params = %v", f.Summary.Params) + } + if len(f.Apply) != 2 { + t.Fatalf("Apply = %d fixes, want 2", len(f.Apply)) + } + if f.Apply[0].Code != "time_point" || f.Apply[1].Code != "time_point_learned" { + t.Errorf("Apply order = %q, %q", f.Apply[0].Code, f.Apply[1].Code) + } + for _, fx := range f.Apply { + if fx.RuleID != "r1" || !fx.Replace { + t.Errorf("fix %+v, want RuleID r1 and Replace", fx) + } + } + if f.Evidence.Shape != "scale" || len(f.Evidence.Scales) != 1 || f.Evidence.Scales[0].Unit != "clock" { + t.Errorf("Evidence = %+v", f.Evidence) + } + if !reflect.DeepEqual(f.RuleIDs, []string{"r1"}) { + t.Errorf("RuleIDs = %v", f.RuleIDs) + } +} + +func TestSeasonDriftOneOutlierNoDrift(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 20; n++ { + tm := 1350.0 + if n == 10 { + tm = 1250 + } + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) + } + if fs := seasonFindings(s.Findings(at.AddDate(0, 0, 20))); len(fs) != 0 { + t.Errorf("season findings = %d after one outlier, want 0", len(fs)) + } +} + +func TestSeasonDriftPausesWithoutCandidate(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 12; n++ { + tm := 1350.0 + if n > 8 { + tm = 1305 + } + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) + } + before := len(s.entries["r1"].Series) + driftNight(t, s, at, 13, nil) + if got := len(s.entries["r1"].Series); got != before { + t.Errorf("series length = %d after a night without candidate, want %d", got, before) + } + if s.entries["r1"].Drift != nil { + t.Error("Drift kept without candidate") + } + if fs := seasonFindings(s.Findings(at.AddDate(0, 0, 13))); len(fs) != 0 { + t.Errorf("season findings = %d without candidate, want 0", len(fs)) + } +} + +func TestSeasonDriftGoneWhenBackAtAdoption(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 17; n++ { + tm := 1350.0 + if n >= 9 && n <= 12 { + tm = 1305 + } + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) + } + if s.entries["r1"].Drift != nil { + t.Error("Drift still set after several nights back at the adopted time") + } + if fs := seasonFindings(s.Findings(at.AddDate(0, 0, 17))); len(fs) != 0 { + t.Errorf("season findings = %d, want 0", len(fs)) + } +} + +func TestSeasonDriftResetsOnNewAt(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 12; n++ { + tm := 1350.0 + if n > 8 { + tm = 1305 + } + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) + } + if len(s.entries["r1"].Series) == 0 { + t.Fatal("series empty before the restart") + } + loc := berlinLoc(t) + at2 := effAt(2026, 7, loc) + s.Sync(effDoc("r1", driftSugg, "switch_time", at2), at2, nil, nil, nil) + if n := len(s.entries["r1"].Series); n != 0 { + t.Errorf("series length after a new At = %d, want 0", n) + } +} + +func TestSeasonDriftOneValuePerDay(t *testing.T) { + s, _, at := driftStore(t) + now := at.AddDate(0, 0, 1) + s.Nightly(now, nil, effStore(t), []Candidate{driftCand(driftSugg, 1305)}) + s.Nightly(now.Add(2*time.Hour), nil, effStore(t), []Candidate{driftCand(driftSugg, 1300)}) + if n := len(s.entries["r1"].Series); n != 1 { + t.Errorf("series length after two nights of one day = %d, want 1", n) + } +} + +func TestSeasonDriftNotInBand(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 12; n++ { + tm := 1350.0 + if n > 8 { + tm = 1305 + } + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) + } + if len(seasonFindings(s.Findings(at.AddDate(0, 0, 12)))) != 1 { + t.Fatal("no season finding to test the band against") + } + for _, f := range s.BandEntries(at.AddDate(0, 0, 12)) { + if f.Kind == "season_shift" { + t.Errorf("BandEntries contains %q", f.ID) + } + } +} diff --git a/dashboard/internal/autolearn/finding.go b/dashboard/internal/autolearn/finding.go index 4b6ea239..09e3ea7b 100644 --- a/dashboard/internal/autolearn/finding.go +++ b/dashboard/internal/autolearn/finding.go @@ -55,6 +55,8 @@ type Fix struct { Template string `json:"template,omitempty"` Prefill map[string]any `json:"prefill,omitempty"` Rules []RuleOps `json:"rules,omitempty"` + // Replace replaces the rule RuleID with the new one instead of adding a rule. + Replace bool `json:"replace,omitempty"` } // RuleOps is the ops of one rule. A fix that changes several rules at once From a95dcb5126aeaf35fa01ba5d983fe301d243e1cf Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:05:50 +0100 Subject: [PATCH 09/34] fix(autolearn): keep the comparison values when a drifted rule is replaced A replaced rule points at a candidate the gate does not show, so its values were missing. The effect runner now adds the values of every candidate that is not shown, the shown ones win. The season drift finding also names the matching candidate in its params. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_effect_test.go | 42 +++++++++++++++++++ dashboard/cmd/dashboard/learn_engine.go | 13 +++++- dashboard/internal/autolearn/effect_store.go | 9 ++-- .../internal/autolearn/effect_store_test.go | 3 ++ 4 files changed, 62 insertions(+), 5 deletions(-) diff --git a/dashboard/cmd/dashboard/learn_effect_test.go b/dashboard/cmd/dashboard/learn_effect_test.go index bb7cbee1..32957184 100644 --- a/dashboard/cmd/dashboard/learn_effect_test.go +++ b/dashboard/cmd/dashboard/learn_effect_test.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "os" "path/filepath" "testing" @@ -72,3 +73,44 @@ func TestEffectRunnerDisabledDoesNothing(t *testing.T) { t.Fatalf("disabled runner loads = %d, entries = %d, want none", loads, r.store.Len()) } } + +func TestEffectRunnerTakesCandidateValuesWhenNotShown(t *testing.T) { + dir := t.TempDir() + effects := filepath.Join(dir, "effects.json") + loads := 0 + r := effectTestRunner(t, []byte(effectRuleDoc), &loads) + r.store = autolearn.LoadEffectStore(effects, nil) + r.candidates = func() []autolearn.Candidate { + return []autolearn.Candidate{{ + Finding: autolearn.Finding{ID: "switchtime:r1:dev-a"}, + Values: map[string]float64{"time": 1305}, + Spread: map[string]float64{"time": 10}, + }} + } + now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.Local) + r.Run(now) + + raw, err := os.ReadFile(effects) + if err != nil { + t.Fatalf("effects file: %v", err) + } + var f struct { + Entries []struct { + Rule string `json:"rule"` + Values map[string]float64 `json:"values"` + Series []float64 `json:"series"` + } `json:"entries"` + } + if err := json.Unmarshal(raw, &f); err != nil { + t.Fatalf("effects file: %v", err) + } + if len(f.Entries) != 1 || f.Entries[0].Rule != "r1" { + t.Fatalf("entries = %+v, want one entry for r1", f.Entries) + } + if f.Entries[0].Values["time"] != 1305 { + t.Errorf("values = %v, want the candidate time 1305", f.Entries[0].Values) + } + if len(f.Entries[0].Series) != 1 { + t.Errorf("series = %v, want one nightly value after the new entry", f.Entries[0].Series) + } +} diff --git a/dashboard/cmd/dashboard/learn_engine.go b/dashboard/cmd/dashboard/learn_engine.go index 92f8fbc9..7e95c162 100644 --- a/dashboard/cmd/dashboard/learn_engine.go +++ b/dashboard/cmd/dashboard/learn_engine.go @@ -590,7 +590,18 @@ func (r *effectRunner) Run(now time.Time) { } byID[f.ID] = f } - added := r.store.Sync(doc, now, days, r.shown(), byID) + // A replaced rule points at a candidate the gate does not show. Its values + // come from the candidate, the shown ones win. + shown := map[string]autolearn.Shown{} + for id, sh := range r.shown() { + shown[id] = sh + } + for _, c := range cands { + if _, ok := shown[c.Finding.ID]; !ok { + shown[c.Finding.ID] = autolearn.Shown{Values: c.Values} + } + } + added := r.store.Sync(doc, now, days, shown, byID) if added || nightly { r.store.Nightly(now, days, r.season, cands) } diff --git a/dashboard/internal/autolearn/effect_store.go b/dashboard/internal/autolearn/effect_store.go index fb3faa66..faed6ef3 100644 --- a/dashboard/internal/autolearn/effect_store.go +++ b/dashboard/internal/autolearn/effect_store.go @@ -523,10 +523,11 @@ func shiftFinding(e effectEntry, c *Candidate, keys []shiftKey, best shiftKey) * } fixes = append(fixes, learned...) params := map[string]any{ - "key": best.name, - "old": shiftValue(best.name, best.at), - "new": shiftValue(best.name, best.now), - "device": e.Device, + "key": best.name, + "old": shiftValue(best.name, best.at), + "new": shiftValue(best.name, best.now), + "device": e.Device, + "suggestion": c.Finding.ID, } return &Finding{ ID: FindingID("season_shift", e.Rule), diff --git a/dashboard/internal/autolearn/effect_store_test.go b/dashboard/internal/autolearn/effect_store_test.go index d524bd4d..ea668fc8 100644 --- a/dashboard/internal/autolearn/effect_store_test.go +++ b/dashboard/internal/autolearn/effect_store_test.go @@ -287,6 +287,9 @@ func TestSeasonDriftReported(t *testing.T) { if f.Summary.Params["old"] != "22:30" || f.Summary.Params["new"] != "21:45" || f.Summary.Params["key"] != "time" { t.Errorf("Params = %v", f.Summary.Params) } + if f.Summary.Params["suggestion"] != "switch_time:plug.heater:on:0:2200" { + t.Errorf("suggestion param = %v, want the matching candidate ID", f.Summary.Params["suggestion"]) + } if len(f.Apply) != 2 { t.Fatalf("Apply = %d fixes, want 2", len(f.Apply)) } From 85a5fed50d4ccf52c999d6b9ef8b2bda1add10ee Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:11:05 +0100 Subject: [PATCH 10/34] feat(webui): show the effect of adopted suggestions in the band Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 42 +++++++ dashboard/internal/webui/catalogs/en.json | 42 +++++++ .../webui/learn_summary_catalog_test.go | 6 + .../internal/webui/static/css/automations.css | 1 + .../webui/static/js/automation-evidence.js | 34 ++++-- .../webui/static/js/automation-suggestions.js | 55 ++++++++- .../internal/webui/templates/automations.html | 7 +- dashboard/test/automation-evidence.test.mjs | 35 ++++++ .../test/automation-suggestions.test.mjs | 113 +++++++++++++++++- 9 files changed, 314 insertions(+), 21 deletions(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 3d68e529..7888ee9c 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -499,9 +499,11 @@ "automations.learn.battery.full_early.line": "Voll um {time}, danach rund {kwh_after} kWh Einspeisung", "automations.learn.battery.full_early.text": "An den meisten Tagen ist der Akku schon vor dem Sonnenhöchststand voll, im Median um {time}. Danach gehen rund {kwh_after} kWh ins Netz.", "automations.learn.battery.full_early.title": "Akku ist zu früh voll", + "automations.learn.button.hide": "Ausblenden", "automations.learn.button.later": "Später", "automations.learn.button.never": "Nicht mehr vorschlagen", "automations.learn.button.open_assistant": "Im Assistenten öffnen", + "automations.learn.button.open_rule": "Regel öffnen", "automations.learn.button.undo": "Rückgängig", "automations.learn.check.competition.text": "Mehrere Regeln schalten beim selben Überschuss ein. Lösen sie zusammen aus, zieht danach der Netzbezug. Gestaffelte Schwellen geben jeder Last ihren eigenen Platz.", "automations.learn.check.competition.title": "Regeln konkurrieren um denselben Überschuss", @@ -547,6 +549,18 @@ "automations.learn.coupling.follow.text": "{b} wurde {hits} von {cases} Mal innerhalb von {lag_s} Sekunden geschaltet, nachdem {a} geschaltet wurde. Eine Regel kann das übernehmen, dann musst du nur noch {a} schalten.", "automations.learn.coupling.follow.title": "{b} folgt {a}", "automations.learn.drop_failed": "Das Verwerfen hat nicht geklappt. Bitte versuche es erneut.", + "automations.learn.effect.no_baseline.line": "Keine Vergleichsdaten", + "automations.learn.effect.no_baseline.text": "Keine Vergleichsdaten aus der Zeit vor der Übernahme. Von Hand überstimmt {overridden} von {fired} Mal.", + "automations.learn.effect.no_baseline.title": "{rule}", + "automations.learn.effect.not_measurable.line": "Noch nicht messbar", + "automations.learn.effect.not_measurable.text": "Noch nicht messbar, die Woche schwankt mehr als die Wirkung. Von Hand überstimmt {overridden} von {fired} Mal.", + "automations.learn.effect.not_measurable.title": "{rule}", + "automations.learn.effect.ok.line": "Vorher {before} {unit}, seitdem {since} {unit}", + "automations.learn.effect.ok.text": "Vorher {before} {unit}, seitdem {since} {unit}. Von Hand überstimmt {overridden} von {fired} Mal.", + "automations.learn.effect.ok.title": "{rule}", + "automations.learn.effect.waiting.line": "Wirkung ab dem {date} sichtbar", + "automations.learn.effect.waiting.text": "Wirkung ab dem {date} sichtbar. Von Hand überstimmt {overridden} von {fired} Mal.", + "automations.learn.effect.waiting.title": "{rule}", "automations.learn.fact.cause": "Ursache", "automations.learn.fact.cause.clustered": "Die Befehle kamen gebündelt", "automations.learn.fact.cause.feedback": "Die Last selbst kippt die Bedingung", @@ -581,6 +595,7 @@ "automations.learn.fix.min_runtime": "Mindestlaufzeit setzen", "automations.learn.fix.move_before": "Vor den Ausfall verschieben", "automations.learn.fix.open_rule": "Regel öffnen", + "automations.learn.fix.quiet_off": "Regel neu anlegen", "automations.learn.fix.repeat": "Als Wiederholung zusammenfassen", "automations.learn.fix.set_cooldown": "Abkühlzeit {value} s", "automations.learn.fix.set_hysteresis": "Hysterese {value} W", @@ -588,22 +603,36 @@ "automations.learn.fix.set_threshold": "Schwelle auf {value}", "automations.learn.fix.shift_time": "Zeitfenster verschieben", "automations.learn.fix.stagger": "Schwellen staffeln", + "automations.learn.fix.surplus_switch": "Regel neu anlegen", + "automations.learn.fix.surplus_wallbox": "Regel neu anlegen", + "automations.learn.fix.time_point": "Neue Zeit übernehmen", + "automations.learn.fix.time_point_learned": "Auf den Lernwert umstellen", "automations.learn.group.check": "Regelprüfung", "automations.learn.group.energy": "Energie", + "automations.learn.group.feedback": "Wirkung", "automations.learn.group.habit": "Gewohnheit", "automations.learn.group.reliability": "Zuverlässigkeit", "automations.learn.hint.dismissed": "Vorschlag ausgeblendet", "automations.learn.ignore": "Ignorieren", + "automations.learn.lane.before": "Vorher", "automations.learn.lane.ist": "Ist", + "automations.learn.lane.since": "Seitdem", "automations.learn.lane.soll": "Soll", + "automations.learn.legend.before_since": "Vorher: der Wert vor der Übernahme. Seitdem: der Wert seit der Übernahme.", "automations.learn.legend.day": "Ist: wann es passiert ist. Soll: wann der Vorschlag schalten würde.", "automations.learn.legend.events": "Ist: jedes beobachtete Ereignis. Soll: was der Vorschlag ändern würde.", "automations.learn.legend.label": "Was bedeuten Ist und Soll?", + "automations.learn.legend.label_before_since": "Was bedeuten Vorher und Seitdem?", "automations.learn.legend.scale": "Ist: der beobachtete Wert. Soll: der vorgeschlagene Wert.", "automations.learn.mark_label": "Befund zu dieser Regel anzeigen", "automations.learn.param.deadband_w": "Totzone", "automations.learn.param.gain": "Verstärkung", + "automations.learn.param.kwh_day": "Verbrauch am Tag", "automations.learn.param.max_change_w": "Änderungsgrenze", + "automations.learn.param.on_w": "Einschaltschwelle", + "automations.learn.param.start": "Beginn", + "automations.learn.param.time": "Uhrzeit", + "automations.learn.param.window_quarters": "Länge in Viertelstunden", "automations.learn.regulator.quality.line": "Verstärkung {gain}, Soll nahe {gain_soll}", "automations.learn.regulator.quality.text": "Der Regler von „{scenario}“ passt nicht zur Strecke. Verstärkung {gain}, Soll nahe {gain_soll}. Die Vorschläge setzen die Werte, die zur gemessenen Totzeit und Steigung passen.", "automations.learn.regulator.quality.title": "Regler von „{scenario}“ ist nicht abgestimmt", @@ -613,6 +642,18 @@ "automations.learn.season": "Gilt von KW {from} bis KW {to}", "automations.learn.season.all": "Gilt das ganze Jahr", "automations.learn.season.heating": "Heizzeit unter {below} °C", + "automations.learn.season_shift.away_standby.line": "Bisher {old} kWh am Tag, jetzt {new} kWh", + "automations.learn.season_shift.away_standby.text": "Der Verbrauch von {device} bei Abwesenheit lag bei {old} kWh am Tag und liegt jetzt bei {new} kWh. Der Assistent ersetzt die Regel, gespeichert wird erst mit Speichern.", + "automations.learn.season_shift.away_standby.title": "{rule}: Verbrauch bei Abwesenheit hat sich geändert", + "automations.learn.season_shift.generic.line": "{param}: bisher {old}, jetzt {new}", + "automations.learn.season_shift.generic.text": "{param} lag bei {old} und liegt jetzt bei {new}. Der Assistent ersetzt die Regel, gespeichert wird erst mit Speichern.", + "automations.learn.season_shift.generic.title": "{rule}: Werte haben sich verschoben", + "automations.learn.season_shift.surplus_window.line": "{param}: bisher {old}, jetzt {new}", + "automations.learn.season_shift.surplus_window.text": "Das typische Überschussfenster für {device} hat sich geändert. {param} lag bei {old} und liegt jetzt bei {new}. Der Assistent ersetzt die Regel, gespeichert wird erst mit Speichern.", + "automations.learn.season_shift.surplus_window.title": "{rule}: Überschussfenster hat sich verschoben", + "automations.learn.season_shift.switch_time.line": "Bisher {old} Uhr, jetzt passt {new} Uhr", + "automations.learn.season_shift.switch_time.text": "Als die Regel entstand, passte {old} Uhr. Inzwischen passt {new} Uhr besser. Der Assistent ersetzt die Regel, gespeichert wird erst mit Speichern.", + "automations.learn.season_shift.switch_time.title": "{rule}: Schaltzeit hat sich verschoben", "automations.learn.shift.load.line": "{kwh} kWh je Woche aus dem Netz verschiebbar", "automations.learn.shift.load.text": "{device} lief {runs} Mal aus dem Netz, obwohl am selben Tag Überschuss für den ganzen Lauf da war. Ein Start im Überschuss bis {latest} Uhr spart diese Netzenergie.", "automations.learn.shift.load.title": "{device} in den Überschuss verschieben", @@ -650,6 +691,7 @@ "automations.learn.threshold.too_low.text": "„{rule}“ schaltet bei {threshold} W ein und zieht danach Strom aus dem Netz. Nahe {soll} W entfallen etwa {kwh} kWh Netzbezug je Woche.", "automations.learn.threshold.too_low.title": "Schwelle von „{rule}“ ist zu niedrig", "automations.learn.undo.ignored": "Befund ausgeblendet", + "automations.learn.unit.actions_week": "Handgriffe/Woche", "automations.learn.unit.kwh_week": "kWh/Woche", "automations.learn.value.minutes": "{value} min", "automations.learn.value.per_hour": "{value} pro Stunde", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 683fc1c9..2738c91c 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -499,9 +499,11 @@ "automations.learn.battery.full_early.line": "Full at {time}, then about {kwh_after} kWh fed in", "automations.learn.battery.full_early.text": "On most days the battery is already full before solar noon, at a median of {time}. Afterwards about {kwh_after} kWh go into the grid.", "automations.learn.battery.full_early.title": "Battery is full too early", + "automations.learn.button.hide": "Hide", "automations.learn.button.later": "Later", "automations.learn.button.never": "Do not suggest again", "automations.learn.button.open_assistant": "Open in assistant", + "automations.learn.button.open_rule": "Open rule", "automations.learn.button.undo": "Undo", "automations.learn.check.competition.text": "Several rules switch on at the same surplus. When they fire together, the grid import follows. Staggered thresholds give each load its own place.", "automations.learn.check.competition.title": "Rules compete for the same surplus", @@ -547,6 +549,18 @@ "automations.learn.coupling.follow.text": "{b} was switched {hits} of {cases} times within {lag_s} seconds after {a} was switched. A rule can take that over, so you only have to switch {a}.", "automations.learn.coupling.follow.title": "{b} follows {a}", "automations.learn.drop_failed": "Dismissing did not work. Please try again.", + "automations.learn.effect.no_baseline.line": "No comparison data", + "automations.learn.effect.no_baseline.text": "No comparison data from before the change. Overridden by hand {overridden} of {fired} times.", + "automations.learn.effect.no_baseline.title": "{rule}", + "automations.learn.effect.not_measurable.line": "Not measurable yet", + "automations.learn.effect.not_measurable.text": "Not measurable yet, the week varies more than the effect. Overridden by hand {overridden} of {fired} times.", + "automations.learn.effect.not_measurable.title": "{rule}", + "automations.learn.effect.ok.line": "Before {before} {unit}, since then {since} {unit}", + "automations.learn.effect.ok.text": "Before {before} {unit}, since then {since} {unit}. Overridden by hand {overridden} of {fired} times.", + "automations.learn.effect.ok.title": "{rule}", + "automations.learn.effect.waiting.line": "Effect visible from {date}", + "automations.learn.effect.waiting.text": "Effect visible from {date}. Overridden by hand {overridden} of {fired} times.", + "automations.learn.effect.waiting.title": "{rule}", "automations.learn.fact.cause": "Cause", "automations.learn.fact.cause.clustered": "The commands came in bunches", "automations.learn.fact.cause.feedback": "The load itself flips the condition", @@ -581,6 +595,7 @@ "automations.learn.fix.min_runtime": "Set a minimum runtime", "automations.learn.fix.move_before": "Move before the outage", "automations.learn.fix.open_rule": "Open rule", + "automations.learn.fix.quiet_off": "Rebuild the rule", "automations.learn.fix.repeat": "Combine as a repeat", "automations.learn.fix.set_cooldown": "Cooldown {value} s", "automations.learn.fix.set_hysteresis": "Hysteresis {value} W", @@ -588,22 +603,36 @@ "automations.learn.fix.set_threshold": "Threshold to {value}", "automations.learn.fix.shift_time": "Shift the time window", "automations.learn.fix.stagger": "Stagger the thresholds", + "automations.learn.fix.surplus_switch": "Rebuild the rule", + "automations.learn.fix.surplus_wallbox": "Rebuild the rule", + "automations.learn.fix.time_point": "Use the new time", + "automations.learn.fix.time_point_learned": "Switch to the learned value", "automations.learn.group.check": "Rule check", "automations.learn.group.energy": "Energy", + "automations.learn.group.feedback": "Effect", "automations.learn.group.habit": "Habit", "automations.learn.group.reliability": "Reliability", "automations.learn.hint.dismissed": "Suggestion hidden", "automations.learn.ignore": "Ignore", + "automations.learn.lane.before": "Before", "automations.learn.lane.ist": "Actual", + "automations.learn.lane.since": "Since", "automations.learn.lane.soll": "Target", + "automations.learn.legend.before_since": "Before: the value before the change. Since: the value since the change.", "automations.learn.legend.day": "Actual: when it happened. Target: when the suggestion would switch.", "automations.learn.legend.events": "Actual: each event we saw. Target: what the suggestion would change.", "automations.learn.legend.label": "What do Actual and Target mean?", + "automations.learn.legend.label_before_since": "What do Before and Since mean?", "automations.learn.legend.scale": "Actual: the value we saw. Target: the suggested value.", "automations.learn.mark_label": "Show the finding for this rule", "automations.learn.param.deadband_w": "Deadband", "automations.learn.param.gain": "Gain", + "automations.learn.param.kwh_day": "Consumption per day", "automations.learn.param.max_change_w": "Change limit", + "automations.learn.param.on_w": "Switch on threshold", + "automations.learn.param.start": "Start", + "automations.learn.param.time": "Time", + "automations.learn.param.window_quarters": "Length in quarter hours", "automations.learn.regulator.quality.line": "Gain {gain}, target near {gain_soll}", "automations.learn.regulator.quality.text": "The regulator of „{scenario}“ does not fit the plant. Gain {gain}, target near {gain_soll}. The suggestions set the values that match the measured dead time and slope.", "automations.learn.regulator.quality.title": "Regulator of „{scenario}“ is not tuned", @@ -613,6 +642,18 @@ "automations.learn.season": "Applies from week {from} to week {to}", "automations.learn.season.all": "Applies all year", "automations.learn.season.heating": "Heating below {below} °C", + "automations.learn.season_shift.away_standby.line": "So far {old} kWh a day, now {new} kWh", + "automations.learn.season_shift.away_standby.text": "The consumption of {device} while away was {old} kWh a day and is {new} kWh now. The assistant replaces the rule, nothing is stored until you save.", + "automations.learn.season_shift.away_standby.title": "{rule}: the consumption while away has changed", + "automations.learn.season_shift.generic.line": "{param}: so far {old}, now {new}", + "automations.learn.season_shift.generic.text": "{param} was {old} and is {new} now. The assistant replaces the rule, nothing is stored until you save.", + "automations.learn.season_shift.generic.title": "{rule}: the values have moved", + "automations.learn.season_shift.surplus_window.line": "{param}: so far {old}, now {new}", + "automations.learn.season_shift.surplus_window.text": "The typical surplus window for {device} has changed. {param} was {old} and is {new} now. The assistant replaces the rule, nothing is stored until you save.", + "automations.learn.season_shift.surplus_window.title": "{rule}: the surplus window has moved", + "automations.learn.season_shift.switch_time.line": "So far {old}, now {new} fits", + "automations.learn.season_shift.switch_time.text": "When the rule was made, {old} fitted. {new} fits better now. The assistant replaces the rule, nothing is stored until you save.", + "automations.learn.season_shift.switch_time.title": "{rule}: the switching time has moved", "automations.learn.shift.load.line": "{kwh} kWh per week can move from the grid", "automations.learn.shift.load.text": "{device} ran {runs} times from the grid although the same day had enough surplus for the whole run. A start in the surplus until {latest} saves that grid energy.", "automations.learn.shift.load.title": "Move {device} into the surplus", @@ -650,6 +691,7 @@ "automations.learn.threshold.too_low.text": "“{rule}” switches on at {threshold} W and then draws power from the grid. Near {soll} W about {kwh} kWh of grid import per week would be avoided.", "automations.learn.threshold.too_low.title": "Threshold of “{rule}” is too low", "automations.learn.undo.ignored": "Finding hidden", + "automations.learn.unit.actions_week": "manual actions/week", "automations.learn.unit.kwh_week": "kWh/week", "automations.learn.value.minutes": "{value} min", "automations.learn.value.per_hour": "{value} per hour", diff --git a/dashboard/internal/webui/learn_summary_catalog_test.go b/dashboard/internal/webui/learn_summary_catalog_test.go index 266ebb81..634917e4 100644 --- a/dashboard/internal/webui/learn_summary_catalog_test.go +++ b/dashboard/internal/webui/learn_summary_catalog_test.go @@ -52,6 +52,12 @@ func autolearnSummaryKeys(t *testing.T) []string { for _, match := range summaryCodeLiteral.FindAllStringSubmatch(string(src), -1) { code := match[1] switch { + case code == "season_shift.": + // The suffix is the kind of the adopted suggestion. The browser maps + // every other kind to generic. + for _, kind := range []string{"switch_time", "away_standby", "surplus_window", "generic"} { + codes[code+kind] = true + } case strings.HasSuffix(code, "sun_"): codes[code+"on.after"] = true codes[code+"on.before"] = true diff --git a/dashboard/internal/webui/static/css/automations.css b/dashboard/internal/webui/static/css/automations.css index 59938f67..f6623d3f 100644 --- a/dashboard/internal/webui/static/css/automations.css +++ b/dashboard/internal/webui/static/css/automations.css @@ -1094,6 +1094,7 @@ button.auto-learn-tile[aria-expanded="true"]:not(:disabled) { background: var(-- .auto-learn-group.is-reliability { color: var(--warn); } .auto-learn-group.is-check { color: var(--info); } .auto-learn-group.is-energy { color: var(--flow-pv); } +.auto-learn-group.is-feedback { color: var(--ok); } .auto-learn-more { box-sizing: border-box; font: inherit; font-size: .88rem; font-weight: 600; color: var(--text-muted); cursor: pointer; background: transparent; border: 1px dashed var(--border); border-radius: var(--radius-md); padding: 0 1rem; min-width: 3.2rem; transition: transform 120ms var(--ease-out); } diff --git a/dashboard/internal/webui/static/js/automation-evidence.js b/dashboard/internal/webui/static/js/automation-evidence.js index e729d788..fe51fc52 100644 --- a/dashboard/internal/webui/static/js/automation-evidence.js +++ b/dashboard/internal/webui/static/js/automation-evidence.js @@ -298,31 +298,38 @@ } // Einheiten mit Katalogtext, sonst die Einheit wie geliefert. - const UNIT_KEYS = { kwh_week: 'automations.learn.unit.kwh_week' }; + const UNIT_KEYS = { kwh_week: 'automations.learn.unit.kwh_week', actions_week: 'automations.learn.unit.actions_week' }; function unitOf(ev, t) { return UNIT_KEYS[ev.unit] ? t(UNIT_KEYS[ev.unit]) : ev.unit; } // Ein Balkenpaar je Parameter, wenn die Evidenz Scales liefert. - // i18n-keys: automations.learn.param.gain, automations.learn.param.deadband_w, automations.learn.param.max_change_w + // i18n-keys: automations.learn.param.gain, automations.learn.param.deadband_w, automations.learn.param.max_change_w, automations.learn.param.time, automations.learn.param.start, automations.learn.param.window_quarters, automations.learn.param.on_w, automations.learn.param.kwh_day const PARAM_KEYS = { gain: 'automations.learn.param.gain', deadband_w: 'automations.learn.param.deadband_w', max_change_w: 'automations.learn.param.max_change_w', + time: 'automations.learn.param.time', + start: 'automations.learn.param.start', + window_quarters: 'automations.learn.param.window_quarters', + on_w: 'automations.learn.param.on_w', + kwh_day: 'automations.learn.param.kwh_day', }; function scaleBarsShape(ev, t) { return ev.scales.map((bar, index) => { + // Uhrzeiten laufen ueber den ganzen Tag, ohne Einheit an der Achse. + const clock = bar.unit === 'clock'; const top = Math.max(bar.ist || 0, bar.soll || 0); - const max = top > 0 ? top * 1.2 : 1; + const max = clock ? DAY : (top > 0 ? top * 1.2 : 1); const toX = (v) => pct(v, max); - const unit = bar.unit ? ' ' + bar.unit : ''; - const majors = [0, max / 2, max]; + const unit = bar.unit && !clock ? ' ' + bar.unit : ''; + const majors = clock ? [0, DAY / 2, DAY] : [0, max / 2, max]; const grid = gridLines(majors.map(toX)); // Der Einlauf staffelt die Balken je 40 ms, Soll folgt dem Ist mit 60 ms (CSS, --i). const istBar = ''; // i18n-ignore const sollBar = ''; // i18n-ignore const ticks = majors.map((v) => ({ x: toX(v), major: true })); - const labels = majors.map((v) => ({ x: toX(v), text: (Math.round(v * 100) / 100) + unit })); + const labels = majors.map((v) => ({ x: toX(v), text: clock ? clockText(v, true) : (Math.round(v * 100) / 100) + unit })); return '
' + esc(t(PARAM_KEYS[bar.name] || bar.name)) + '
' + lane(t('automations.learn.lane.ist'), laneSvg(grid + istBar)) // i18n-ignore + lane(t('automations.learn.lane.soll'), laneSvg(grid + sollBar), true) @@ -347,9 +354,18 @@ const sollBar = hasSoll ? '' : ''; const soll = hasSoll ? marks([ev.soll_value], toX, 'auto-learn-mark-soll auto-learn-mark-wide') : ''; const ticks = majors.map((v) => ({ x: toX(v), major: true })); - const labels = majors.map((v) => ({ x: toX(v), text: Math.round(v) + unit })); - return lane(t('automations.learn.lane.ist'), laneSvg(grid + seen + istBar + threshold)) // i18n-ignore - + lane(t('automations.learn.lane.soll'), laneSvg(grid + sollBar + soll), true) + // Unter 10 mit einer Nachkommastelle im Zahlformat der Seite, sonst als Zahl. + const decimal = (v) => { + if (Math.abs(v) >= 10) return Math.round(v); + const r = Math.round(v * 10) / 10; + const format = window.I18n && window.I18n.formatNumber; + return format ? format(r, Number.isInteger(r) ? 0 : 1) : r; + }; + const labels = majors.map((v) => ({ x: toX(v), text: decimal(v) + unit })); + // Zwei Labels (Vorher und Seitdem) benennen die Spuren, sonst Ist und Soll. + const beforeSince = Array.isArray(ev.labels) && ev.labels.length === 2; + return lane(beforeSince ? t('automations.learn.lane.before') : t('automations.learn.lane.ist'), laneSvg(grid + seen + istBar + threshold)) // i18n-ignore + + lane(beforeSince ? t('automations.learn.lane.since') : t('automations.learn.lane.soll'), laneSvg(grid + sollBar + soll), true) + axisHtml(ticks, labels); } diff --git a/dashboard/internal/webui/static/js/automation-suggestions.js b/dashboard/internal/webui/static/js/automation-suggestions.js index 3ab14f73..cfc819f2 100644 --- a/dashboard/internal/webui/static/js/automation-suggestions.js +++ b/dashboard/internal/webui/static/js/automation-suggestions.js @@ -34,6 +34,19 @@ // Ohne gemessenen Verbraucher bleibt der Name leer, der Text nennt dann den Verbraucher ohne Messung. if (code === 'baseload.drift' && !params.candidate) params.candidate = t('automations.learn.baseload.candidate.none'); if (code === 'battery.empty_early' && !params.candidates) params.candidates = t('automations.learn.battery.candidate.none'); + // Wirkung: die Einheit als Katalogtext, das Datum im Format der Seite. + if (code.indexOf('effect.') === 0) { + // i18n-keys: automations.learn.unit.kwh_week, automations.learn.unit.actions_week + if (params.unit) params.unit = t(CAT + 'unit.' + params.unit); + const formatDate = window.I18n && window.I18n.formatDate; + if (params.date && formatDate) params.date = formatDate(new Date(params.date + 'T12:00:00')); + } + // Schaltzeit, Verbrauch und Fenster haben je einen Katalogtext. Unbekannte Arten nehmen den allgemeinen. + if (code.indexOf('season_shift.') === 0) { + // i18n-keys: automations.learn.param.time, automations.learn.param.start, automations.learn.param.window_quarters, automations.learn.param.on_w, automations.learn.param.kwh_day, automations.learn.param.gain, automations.learn.param.deadband_w, automations.learn.param.max_change_w + if (params.key) params.param = t(CAT + 'param.' + params.key); + if (!/^season_shift\.(switch_time|away_standby|surplus_window)$/.test(code)) code = 'season_shift.generic'; + } if (/^switch_time\.sun_(on|off)$/.test(code)) { const offset = Number(params.offset_min) || 0; params.minutes = Math.abs(offset); @@ -86,14 +99,26 @@ // Die Legende hangt an der Form der Grafik. Ohne bekannte Form gibt es keine. function legend(s, t) { - const shape = s && s.evidence && s.evidence.shape; + const ev = s && s.evidence; + if (ev && ev.shape === 'scale' && Array.isArray(ev.labels) && ev.labels.length === 2) return t(CAT + 'legend.before_since', {}); + const shape = ev && ev.shape; if (SHAPES_WITH_LEGEND.indexOf(shape) < 0) return ''; return t(CAT + 'legend.' + shape, {}); } // Zahlen der Befunde als Zeilen aus Bezeichnung und Wert, wie im Vorschlagsband. const factRows = (facts, t) => (facts || []).map((f) => ({ label: t(CAT + 'fact.' + f.code, {}), value: valueOf(f, t) })); - const api = { arrange, title, line, text, legend, resolveSummary, factRows }; + // Der Befund nennt seine Regel oder Szene beim Namen. Ohne Treffer bleibt die Kennung. + function withRuleName(finding, doc) { + const ids = finding && Array.isArray(finding.rule_ids) ? finding.rule_ids : []; + const id = ids[0]; + const known = ((doc && doc.rules) || []).concat((doc && doc.scenarios) || []); + const hit = known.find((x) => x && x.id === id); + const name = hit && hit.name ? hit.name : id; + const summary = finding.summary || {}; + return { ...finding, summary: { ...summary, params: { ...(summary.params || {}), rule: name } } }; + } + const api = { arrange, title, line, text, legend, resolveSummary, factRows, withRuleName }; window.AutomationSuggestions = api; // Vorschlagsband oberhalb der Regeln. Laedt einmal beim Oeffnen der Seite. Die @@ -243,9 +268,11 @@ if (this.open && this.$nextTick) this.$nextTick(() => this.placeCaret()); }, - titleOf(s, t) { return api.title(s, t); }, - lineOf(s, t) { return api.line(s, t); }, - textOf(s, t) { return api.text(s, t); }, + // Befunde zur Wirkung und zur Jahreszeit nennen den Namen der Regel aus dem Dokument. + ruled(s) { return s && (s.kind === 'effect' || s.kind === 'season_shift') ? api.withRuleName(s, this.document) : s; }, + titleOf(s, t) { return api.title(this.ruled(s), t); }, + lineOf(s, t) { return api.line(this.ruled(s), t); }, + textOf(s, t) { return api.text(this.ruled(s), t); }, legendOf(s, t) { return api.legend(s, t); }, groupLabel(s, t) { return t(CAT + 'group.' + s.group, {}); }, evidenceOf(s, t) { return window.AutomationEvidence ? window.AutomationEvidence.render(s.evidence, t, { full: this.fullDay }) : ''; }, @@ -286,7 +313,23 @@ }, actionsOf(s) { const edit = Boolean(this.canEdit) && Boolean(s); - return { assistant: edit && Boolean(this.fixOf(s)), apply: edit && Boolean(this.opFixOf(s)), later: edit, dismiss: edit }; + // Wirkung: nur die Regel oeffnen, ausblenden mit dem Bearbeitungsrecht. + if (s && s.group === 'feedback') return { assistant: false, apply: false, later: false, dismiss: false, openRule: true, hide: edit }; + return { assistant: edit && Boolean(this.fixOf(s)), apply: edit && Boolean(this.opFixOf(s)), later: edit, dismiss: edit, openRule: false, hide: false }; + }, + // Die Regel oder Szene zur Befundkarte: Regeln im Reiter Regeln, Szenen aufgeklappt im Reiter Szenarien. + openRuleOf(s) { + const id = s && Array.isArray(s.rule_ids) ? s.rule_ids[0] : ''; + const doc = this.document || {}; + if ((doc.rules || []).some((rule) => rule.id === id)) { + this.view = 'rules'; + this.focusRule(id); + return; + } + if ((doc.scenarios || []).some((scenario) => scenario.id === id)) { + this.view = 'scenarios'; + this.scenarioExpanded[id] = true; + } }, async send(s, action) { diff --git a/dashboard/internal/webui/templates/automations.html b/dashboard/internal/webui/templates/automations.html index f4b12890..4f5bc05a 100644 --- a/dashboard/internal/webui/templates/automations.html +++ b/dashboard/internal/webui/templates/automations.html @@ -90,7 +90,7 @@

{{t "automations.le
diff --git a/dashboard/test/automation-evidence.test.mjs b/dashboard/test/automation-evidence.test.mjs index b0f3fc98..89e134e0 100644 --- a/dashboard/test/automation-evidence.test.mjs +++ b/dashboard/test/automation-evidence.test.mjs @@ -503,3 +503,38 @@ test('the evidence entrance is gated by is-enter and has a reduced-motion rule', assert.match(reduced, /auto-learn-chart-fade 200ms ease-out both/); assert.doesNotMatch(css, /(^|\n)\.auto-learn-is \{[^}]*animation/); }); + +test('the weekly action unit of a scale shows its catalog text on the axis', () => { + const { api, document } = load(); + const host = mount(document, api.render({ shape: 'scale', ist_value: 12, soll_value: 4, unit: 'actions_week' }, t)); + assert.ok(axisLabels(host).every((text) => text.endsWith(' automations.learn.unit.actions_week')), axisLabels(host).join('|')); +}); + +test('a scale with before and since labels names the lanes Vorher and Seitdem', () => { + const { api, document } = load(); + const host = mount(document, api.render({ shape: 'scale', ist_value: 80, soll_value: 40, unit: 'kwh_week', labels: ['before', 'since'] }, t)); + const lanes = Array.from(host.querySelectorAll('.auto-learn-lane-label')).map((n) => n.textContent); + assert.deepEqual(lanes, ['automations.learn.lane.before', 'automations.learn.lane.since']); +}); + +test('a scale without labels keeps the Ist and Soll lanes', () => { + const { api, document } = load(); + const host = mount(document, api.render({ shape: 'scale', ist_value: 80, soll_value: 40 }, t)); + const lanes = Array.from(host.querySelectorAll('.auto-learn-lane-label')).map((n) => n.textContent); + assert.deepEqual(lanes, ['automations.learn.lane.ist', 'automations.learn.lane.soll']); +}); + +test('scale axis labels below 10 keep one decimal', () => { + const { api, document } = load(); + const host = mount(document, api.render({ shape: 'scale', ist_value: 2.5, soll_value: 1, unit: 'kwh_week' }, t)); + assert.deepEqual(axisLabels(host).map((text) => text.split(' ')[0]), ['0', '2.5', '5']); +}); + +test('a clock bar scale runs over the day and labels 00:00, 12:00 and 24:00 without a unit', () => { + const { api, document } = load(); + const html = api.render({ shape: 'scale', scales: [{ name: 'time', ist: 1200, soll: 1260, unit: 'clock' }] }, t); + const host = mount(document, html); + assert.deepEqual(axisLabels(host), ['00:00', '12:00', '24:00']); + const istBar = host.querySelector('rect.auto-learn-ist'); + assert.ok(Math.abs(Number(istBar.getAttribute('width')) - (1200 / 1440) * 100) < 0.01, 'ist bar scales on 1440 minutes'); +}); diff --git a/dashboard/test/automation-suggestions.test.mjs b/dashboard/test/automation-suggestions.test.mjs index 2f206dca..5182a6bb 100644 --- a/dashboard/test/automation-suggestions.test.mjs +++ b/dashboard/test/automation-suggestions.test.mjs @@ -31,6 +31,9 @@ const FIX_CODES = ['min_runtime', 'repeat', 'open_rule', 'add_condition', 'shift const BUTTONS = ['open_assistant', 'later', 'never', 'undo']; const BAND_KEYS = ['title', 'count_one', 'count_many', 'learning', 'more', 'less']; const GROUPS = ['habit', 'check', 'reliability', 'energy']; +const EFFECT_CODES = ['effect.ok', 'effect.not_measurable', 'effect.waiting', 'effect.no_baseline']; +const SEASON_CODES = ['season_shift.switch_time', 'season_shift.away_standby', 'season_shift.surplus_window', 'season_shift.generic']; +const PARAM_CODES = ['time', 'start', 'window_quarters', 'on_w', 'kwh_day', 'gain', 'deadband_w', 'max_change_w']; // Every catalog key the band needs, for one language. function requiredKeys() { @@ -48,6 +51,13 @@ function requiredKeys() { keys.push('automations.learn.hint.dismissed', 'automations.learn.lane.ist', 'automations.learn.lane.soll'); keys.push('automations.learn.drop_failed'); keys.push('automations.learn.season.heating', 'automations.learn.unit.kwh_week'); + // Wirkung: Befunde der Regelwirkung, Spurmarken, Einheiten, Parameter und Befunde zur Jahreszeit. + keys.push('automations.learn.group.feedback', 'automations.learn.lane.before', 'automations.learn.lane.since'); + keys.push('automations.learn.legend.before_since', 'automations.learn.unit.actions_week'); + keys.push('automations.learn.button.open_rule', 'automations.learn.button.hide'); + EFFECT_CODES.forEach((code) => ['title', 'line', 'text'].forEach((part) => keys.push(`automations.learn.${code}.${part}`))); + SEASON_CODES.forEach((code) => ['title', 'line', 'text'].forEach((part) => keys.push(`automations.learn.${code}.${part}`))); + PARAM_CODES.forEach((name) => keys.push(`automations.learn.param.${name}`)); return keys; } @@ -402,8 +412,8 @@ test('the assistant button needs a template fix and the editing permission', asy const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [unplanned, templ], learning: { since: 1, devices: 1, days: 1 } })); await band.load(); band.canEdit = true; - assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: false, later: true, dismiss: true }); - assert.deepEqual(plain(band.actionsOf(band.items[1])), { assistant: true, apply: false, later: true, dismiss: true }); + assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: false, later: true, dismiss: true, openRule: false, hide: false }); + assert.deepEqual(plain(band.actionsOf(band.items[1])), { assistant: true, apply: false, later: true, dismiss: true, openRule: false, hide: false }); assert.equal(band.fixOf(band.items[1]).template, 'follow_switch'); close(); }); @@ -425,7 +435,7 @@ test('a fix with ops and no template gets the apply button with the fix label', const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [limit], learning: { since: 1, devices: 1, days: 1 } })); await band.load(); band.canEdit = true; - assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: true, later: true, dismiss: true }); + assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: true, later: true, dismiss: true, openRule: false, hide: false }); assert.equal(band.opFixOf(band.items[0]).code, 'add_condition'); assert.equal(band.applyLabelOf(band.items[0], catalogT('de')), catalogs.de['automations.learn.fix.add_condition']); band.canEdit = false; @@ -438,7 +448,7 @@ test('without the automations permission there are no buttons at all', async () const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [templ], learning: { since: 1, devices: 1, days: 1 } })); await band.load(); band.canEdit = false; - assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: false, later: false, dismiss: false }); + assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: false, later: false, dismiss: false, openRule: false, hide: false }); close(); }); @@ -791,3 +801,98 @@ test('an unknown monitoring request keeps the band as it is and the request', as assert.equal(window.__automationSuggestionRequest__, 'zz:9'); close(); }); + +test('effect codes translate the unit and the waiting date through the page format', () => { + const { api } = load({ formatDate: (d) => 'Datum ' + d.getDate() + '.' + (d.getMonth() + 1) + '.' }); + const { t } = recorder(); + const r = api.resolveSummary({ code: 'effect.ok', params: { unit: 'kwh_week', before: 1.25, since: 0.8 } }, t); + assert.equal(r.params.unit, 'automations.learn.unit.kwh_week'); + assert.equal(r.params.before, '1.3'); + const w = api.resolveSummary({ code: 'effect.waiting', params: { unit: 'actions_week', date: '2026-12-01' } }, t); + assert.equal(w.params.unit, 'automations.learn.unit.actions_week'); + assert.equal(w.params.date, 'Datum 1.12.'); +}); + +test('effect dates stay ISO without a page date format', () => { + const { api } = load(); + const { t } = recorder(); + const w = api.resolveSummary({ code: 'effect.waiting', params: { date: '2026-12-01' } }, t); + assert.equal(w.params.date, '2026-12-01'); +}); + +test('season shift codes get the translated parameter name, unknown kinds use the generic text', () => { + const { api } = load(); + const { t } = recorder(); + const known = api.resolveSummary({ code: 'season_shift.surplus_window', params: { key: 'window_quarters', old: 8, new: 12, device: 'Wallbox' } }, t); + assert.equal(known.code, 'season_shift.surplus_window'); + assert.equal(known.params.param, 'automations.learn.param.window_quarters'); + const unknown = api.resolveSummary({ code: 'season_shift.other', params: { key: 'on_w', old: 5, new: 7 } }, t); + assert.equal(unknown.code, 'season_shift.generic'); + assert.equal(unknown.params.param, 'automations.learn.param.on_w'); +}); + +test('withRuleName copies the finding and names its rule or scenario, with the id as fallback', () => { + const { api } = load(); + const doc = { rules: [{ id: 'r1', name: 'Pumpe Nacht' }], scenarios: [{ id: 's1', name: 'Urlaub' }] }; + const s = { id: 'effect:r1', kind: 'effect', rule_ids: ['r1'], summary: { code: 'effect.ok', params: { before: 1 } } }; + const named = api.withRuleName(s, doc); + assert.equal(named.summary.params.rule, 'Pumpe Nacht'); + assert.equal(named.summary.params.before, 1); + assert.equal(s.summary.params.rule, undefined, 'the original finding stays as it was'); + assert.equal(api.withRuleName({ ...s, rule_ids: ['s1'] }, doc).summary.params.rule, 'Urlaub'); + assert.equal(api.withRuleName({ ...s, rule_ids: ['x9'] }, doc).summary.params.rule, 'x9'); +}); + +test('the band titles an effect with the rule name from the page document', () => { + const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [], learning: { since: 1, devices: 1, days: 1 } })); + band.document = { rules: [{ id: 'r1', name: 'Pumpe Nacht' }], scenarios: [] }; + const { t, calls } = recorder(); + const s = { id: 'effect:r1', kind: 'effect', group: 'feedback', rule_ids: ['r1'], summary: { code: 'effect.not_measurable', params: { overridden: 0, fired: 3 } } }; + band.titleOf(s, t); + assert.equal(calls[0].key, 'automations.learn.effect.not_measurable.title'); + assert.equal(calls[0].params.rule, 'Pumpe Nacht'); + close(); +}); + +test('the legend of a before and since scale names both lanes', () => { + const { api } = load(); + const { t, calls } = recorder(); + api.legend({ summary: { code: 'effect.ok' }, evidence: { shape: 'scale', labels: ['before', 'since'] } }, t); + assert.equal(calls[0].key, 'automations.learn.legend.before_since'); +}); + +test('feedback findings offer the rule button and hide, other findings do not', async () => { + const feedback = { ...finding('effect:r1'), group: 'feedback', kind: 'effect', rule_ids: ['r1'] }; + const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [feedback, finding('p:1')], learning: { since: 1, devices: 1, days: 1 } })); + await band.load(); + band.canEdit = true; + assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: false, later: false, dismiss: false, openRule: true, hide: true }); + assert.deepEqual(plain(band.actionsOf(band.items[1])), { assistant: false, apply: false, later: true, dismiss: true, openRule: false, hide: false }); + band.canEdit = false; + assert.equal(band.actionsOf(band.items[0]).hide, false); + close(); +}); + +test('openRuleOf opens the rules view on the rule, or the scenarios view on an expanded scenario', async () => { + const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [], learning: { since: 1, devices: 1, days: 1 } })); + const focused = []; + band.focusRule = (id) => focused.push(id); + band.scenarioExpanded = {}; + band.view = 'scenarios'; + band.document = { rules: [{ id: 'r1', name: 'Pumpe' }], scenarios: [{ id: 's1', name: 'Urlaub' }] }; + band.openRuleOf({ rule_ids: ['r1'] }); + assert.equal(band.view, 'rules'); + assert.deepEqual(focused, ['r1']); + band.openRuleOf({ rule_ids: ['s1'] }); + assert.equal(band.view, 'scenarios'); + assert.equal(band.scenarioExpanded.s1, true); + close(); +}); + +test('scale axis labels below 10 use the decimal comma of the page format', () => { + const { evidence, document } = load(germanI18n); + const host = document.createElement('div'); + host.innerHTML = evidence.render({ shape: 'scale', ist_value: 2.5, soll_value: 1, unit: 'kwh_week' }, (key) => key); + const labels = Array.from(host.querySelectorAll('.auto-learn-axis-label')).map((n) => n.textContent.split(' ')[0]); + assert.deepEqual(labels, ['0', '2,5', '5']); +}); From a71c920c28d4abcde196043ceddee349b3020222 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:13:40 +0100 Subject: [PATCH 11/34] feat(webui): show the effect and season drift of adopted suggestions Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/automations.page.js | 19 +++++- .../webui/templates/automations-finding.html | 2 +- dashboard/internal/webui/webui_test.go | 2 +- dashboard/test/automations.page.test.mjs | 61 +++++++++++++++++++ 4 files changed, 81 insertions(+), 3 deletions(-) diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index d8b5b20e..4dcd8caa 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -2292,7 +2292,11 @@ }, findingText(finding) { // Schluessel und Parameter teilen sich Vorschlagsband und Regelmarken (automation-suggestions.js). - const { code, params } = window.AutomationSuggestions.resolveSummary(finding.summary, t); + // Wirkung und Jahreszeit nennen die Regel beim Namen (withRuleName). + const named = finding.kind === 'effect' || finding.kind === 'season_shift' + ? window.AutomationSuggestions.withRuleName(finding, this.document) + : finding; + const { code, params } = window.AutomationSuggestions.resolveSummary(named.summary, t); return { title: t(`automations.learn.${code}.title`, params), text: t(`automations.learn.${code}.text`, params), @@ -2344,6 +2348,19 @@ // Mit finding setzt jede Regel oder jedes Szenario, auf die alle Ops geschrieben wurden, // learned_from mit der Befund-Id als suggestion. applyFix(fix, finding = null, asSuggestion = true) { + // Ein Ersatz-Vorschlag oeffnet den Assistenten mit der Vorbelegung. Die Regel + // bleibt unveraendert, bis der Assistent sie ersetzt. + if (fix.template && fix.replace) { + const summary = (finding && finding.summary) || {}; + const origin = { + suggestion: (summary.params || {}).suggestion, + kind: String(summary.code || '').split('.')[1], + replaceId: fix.rule_id, + }; + this.openAssistantWith(fix.template, fix.prefill, origin); + this.closeFinding(); + return; + } const groups = Array.isArray(fix.rules) && fix.rules.length ? fix.rules.map((entry) => ({ code: fix.code, rule_id: entry.rule_id, ops: entry.ops || [] })) : [{ code: fix.code, rule_id: fix.rule_id, ops: fix.ops || [] }]; diff --git a/dashboard/internal/webui/templates/automations-finding.html b/dashboard/internal/webui/templates/automations-finding.html index 928f1c82..231a0d98 100644 --- a/dashboard/internal/webui/templates/automations-finding.html +++ b/dashboard/internal/webui/templates/automations-finding.html @@ -1,6 +1,6 @@ {{define "automations-finding"}} -
From f4755bb0f11b513f253fd0163a35f46860a5bac5 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:17:52 +0100 Subject: [PATCH 32/34] feat(monitoring): check the results of adopted suggestions in Monitoring An effect validates an adopted suggestion and asks for nothing, so it leaves the suggestion band. Monitoring lists the measured results under their own filter, with the confidence and a step to the rule. The rule marks stay. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_suggestions.go | 48 ++---------- .../cmd/dashboard/learn_suggestions_test.go | 54 ------------- dashboard/cmd/dashboard/main.go | 18 +++-- dashboard/cmd/dashboard/monitoring.go | 30 ++++++++ .../cmd/dashboard/monitoring_effects_test.go | 39 ++++++++++ dashboard/internal/autolearn/demo_test.go | 12 +-- dashboard/internal/autolearn/effect_store.go | 15 ++-- .../internal/autolearn/effect_store_test.go | 28 +++---- dashboard/internal/monitoring/notice.go | 46 +++++++++++- dashboard/internal/monitoring/notice_test.go | 39 ++++++++++ .../internal/webui/cache-bust-history.csv | 2 + dashboard/internal/webui/catalogs/de.json | 10 +-- dashboard/internal/webui/catalogs/en.json | 10 +-- .../internal/webui/static/css/automations.css | 1 - .../webui/static/js/automation-suggestions.js | 33 ++------ .../webui/static/js/automations.page.js | 13 ++++ .../webui/static/js/monitoring-model.js | 17 +++-- .../webui/static/js/monitoring.page.js | 20 ++++- .../internal/webui/templates/automations.html | 9 +-- dashboard/internal/webui/templates/base.html | 2 +- .../internal/webui/templates/monitoring.html | 2 +- .../test/automation-suggestions.test.mjs | 75 ++++--------------- dashboard/test/automations.page.test.mjs | 13 ++++ dashboard/test/monitoring-model.test.mjs | 29 +++++++ dashboard/test/monitoring.page.test.mjs | 28 ++++++- docs/dashboard/automations-learning.md | 24 +++--- docs/dashboard/monitoring.md | 17 +++-- 27 files changed, 365 insertions(+), 269 deletions(-) create mode 100644 dashboard/cmd/dashboard/monitoring_effects_test.go diff --git a/dashboard/cmd/dashboard/learn_suggestions.go b/dashboard/cmd/dashboard/learn_suggestions.go index 1e25143b..7e7fdfa8 100644 --- a/dashboard/cmd/dashboard/learn_suggestions.go +++ b/dashboard/cmd/dashboard/learn_suggestions.go @@ -25,15 +25,12 @@ type suggestionBook struct { recentC *float64 // readDoc returns the current rule document, nil keeps every suggestion. readDoc func() ([]byte, error) - // effects returns the effect findings of the adopted suggestions, nil for none. - effects func(now time.Time) []autolearn.Finding } // Visible returns the suggestions to show now, without dismissed or postponed // ones, without devices exists rejects and without the ones the current rule // document already holds. The rules are read on every call, so an applied -// suggestion vanishes before the next engine round. The effects of adopted -// suggestions follow the suggestions, for rules that still came from one. +// suggestion vanishes before the next engine round. func (b *suggestionBook) Visible(now time.Time, exists func(device string) bool) []autolearn.Finding { b.mu.Lock() all := append([]autolearn.Finding(nil), b.all...) @@ -41,39 +38,13 @@ func (b *suggestionBook) Visible(now time.Time, exists func(device string) bool) b.mu.Unlock() visible := b.state.Visible(all, now, exists, recentC) doc, ok := b.currentDoc() - if ok { - var out []autolearn.Finding - for _, f := range visible { - if !f.AppliedIn(doc) { - out = append(out, f) - } - } - visible = out - } - if b.effects == nil { + if !ok { return visible } - learned := learnedRuleIDs(doc) - for _, f := range b.state.Visible(b.effects(now), now, exists, nil) { - if !ok || (len(f.RuleIDs) > 0 && learned[f.RuleIDs[0]]) { - visible = append(visible, f) - } - } - return visible -} - -// learnedRuleIDs holds the IDs of the rules and scenarios of doc that came from -// a learned suggestion. -func learnedRuleIDs(doc autolearn.Doc) map[string]bool { - out := map[string]bool{} - for _, r := range doc.Rules { - if r.LearnedFrom != nil { - out[r.ID] = true - } - } - for _, sc := range doc.Scenarios { - if sc.LearnedFrom != nil { - out[sc.ID] = true + var out []autolearn.Finding + for _, f := range visible { + if !f.AppliedIn(doc) { + out = append(out, f) } } return out @@ -103,13 +74,6 @@ func (b *suggestionBook) Known(id string) bool { if b.state.Hidden(id) { return true } - if b.effects != nil { - for _, f := range b.effects(time.Now()) { - if f.ID == id { - return true - } - } - } b.mu.Lock() defer b.mu.Unlock() for _, f := range b.all { diff --git a/dashboard/cmd/dashboard/learn_suggestions_test.go b/dashboard/cmd/dashboard/learn_suggestions_test.go index fcb22d57..64c1eae6 100644 --- a/dashboard/cmd/dashboard/learn_suggestions_test.go +++ b/dashboard/cmd/dashboard/learn_suggestions_test.go @@ -350,57 +350,3 @@ func TestVisibleKeepsSuggestionWhenRuleUnreadable(t *testing.T) { t.Fatalf("visible = %d, want 1 when the rules cannot be read", len(got)) } } - -// effectRuleDoc holds r1 from a learned suggestion and r2 made by hand. -const effectRuleDoc = `{"rules":[{"id":"r1","name":"Heizung","enabled":true,"conditions":[],"actions":[],"learned_from":{"suggestion":"switchtime:r1:dev-a","kind":"switch_time","at":1700000000}},{"id":"r2","name":"Licht","enabled":true,"conditions":[],"actions":[]}]}` - -func effectFinding(rule string) autolearn.Finding { - return autolearn.Finding{ID: "effect:" + rule, Kind: "effect", Group: "feedback", RuleIDs: []string{rule}, Device: "dev-a", Severity: "info", Confidence: "high"} -} - -func effectBook(t *testing.T, doc string, effects ...autolearn.Finding) *suggestionBook { - t.Helper() - state := autolearn.LoadSuggestionState(filepath.Join(t.TempDir(), "suggestions.json"), nil) - return &suggestionBook{ - state: state, - readDoc: func() ([]byte, error) { return []byte(doc), nil }, - effects: func(time.Time) []autolearn.Finding { return effects }, - } -} - -func TestVisibleShowsEffectOfLearnedRule(t *testing.T) { - book := effectBook(t, effectRuleDoc, effectFinding("r1")) - got := book.Visible(time.Now(), func(string) bool { return true }) - if len(got) != 1 || got[0].ID != "effect:r1" { - t.Fatalf("visible = %+v, want effect:r1", got) - } -} - -func TestVisibleHidesEffectOfRuleWithoutLearnedFrom(t *testing.T) { - book := effectBook(t, effectRuleDoc, effectFinding("r2")) - if got := book.Visible(time.Now(), func(string) bool { return true }); len(got) != 0 { - t.Fatalf("effect of a hand made rule visible: %+v", got) - } -} - -func TestDismissedEffectStaysKnown(t *testing.T) { - book := effectBook(t, effectRuleDoc, effectFinding("r1")) - exists := func(string) bool { return true } - if err := book.Dismiss("effect:r1", time.Now()); err != nil { - t.Fatal(err) - } - if got := book.Visible(time.Now(), exists); len(got) != 0 { - t.Fatalf("dismissed effect visible: %+v", got) - } - if !book.Known("effect:r1") { - t.Fatal("dismissed effect must stay known") - } -} - -func TestVisibleShowsEffectWhenRuleUnreadable(t *testing.T) { - book := effectBook(t, "", effectFinding("r1")) - book.readDoc = func() ([]byte, error) { return nil, os.ErrNotExist } - if got := book.Visible(time.Now(), func(string) bool { return true }); len(got) != 1 { - t.Fatalf("visible = %d, want the effect without a readable document", len(got)) - } -} diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 5f887403..572bceab 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -684,7 +684,7 @@ func main() { effectStore := autolearn.LoadEffectStore(filepath.Join(autolearnDir, "effects.json"), log.Printf) learnHub.AddSaver("effects", effectStore) learnHub.AddResetter("effects", effectStore) - // Die Wirkung zeigt die Regelpruefung und das Band, solange das Muster-Lernen an ist. + // Die Wirkung zeigen die Regelpruefung und das Monitoring, solange das Muster-Lernen an ist. effectsOn := func() bool { if value, err := settingsStore.LoadSettings(); err == nil && value.AutomationPatternsDisabled { return false @@ -711,6 +711,16 @@ func main() { if monitoringSuggestions != nil { in.Suggestions = monitoringSuggestions() } + if effectsOn() { + var doc autolearn.Doc + ok := false + if raw, err := configManager.Read("automation_rules"); err == nil { + if parsed, err := autolearn.ParseDoc(raw); err == nil { + doc, ok = parsed, true + } + } + in.Effects, in.RuleNames = monitoringEffects(effectStore.Measured(time.Now()), doc, ok) + } return in } monitoringStore := monitoring.OpenStore(filepath.Join(autolearnDir, "monitoring.json"), log.Printf) @@ -751,12 +761,6 @@ func main() { seasonClose := &seasonCloser{store: seasonStore, days: dayStore.Days, learned: learnedClockMinutes(learnedStore), site: ruleSite(func() ([]byte, error) { return configManager.Read("automation_rules") }), loc: time.Local} suggestions := &suggestionBook{state: suggestionState, readDoc: func() ([]byte, error) { return configManager.Read("automation_rules") }} - suggestions.effects = func(now time.Time) []autolearn.Finding { - if !effectsOn() { - return nil - } - return effectStore.BandEntries(now) - } effectLoop := &effectRunner{ store: effectStore, readDoc: func() ([]byte, error) { return configManager.Read("automation_rules") }, diff --git a/dashboard/cmd/dashboard/monitoring.go b/dashboard/cmd/dashboard/monitoring.go index d593d349..dc18a348 100644 --- a/dashboard/cmd/dashboard/monitoring.go +++ b/dashboard/cmd/dashboard/monitoring.go @@ -57,6 +57,36 @@ func (m *monitoringRunner) Save() error { return m.store.Save() } +// monitoringEffects keeps the effects of the rules and scenarios that still came +// from a learned suggestion, and returns their names by ID. Without a readable +// rule document every effect stays, without names. +func monitoringEffects(effects []autolearn.Finding, doc autolearn.Doc, ok bool) ([]autolearn.Finding, map[string]string) { + names := map[string]string{} + if !ok { + return effects, names + } + for _, r := range doc.Rules { + if r.LearnedFrom != nil { + names[r.ID] = r.Name + } + } + for _, sc := range doc.Scenarios { + if sc.LearnedFrom != nil { + names[sc.ID] = sc.Name + } + } + var out []autolearn.Finding + for _, f := range effects { + if len(f.RuleIDs) == 0 { + continue + } + if _, adopted := names[f.RuleIDs[0]]; adopted { + out = append(out, f) + } + } + return out, names +} + // monitoringDeviceIcon wählt das Icon eines Lerngeräts aus seiner Energie-Rolle. func monitoringDeviceIcon(role energy.Role, switchable bool) string { switch { diff --git a/dashboard/cmd/dashboard/monitoring_effects_test.go b/dashboard/cmd/dashboard/monitoring_effects_test.go new file mode 100644 index 00000000..52f0bb0d --- /dev/null +++ b/dashboard/cmd/dashboard/monitoring_effects_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "testing" + + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" +) + +// monitoringEffectDoc holds r1 and s1 from a learned suggestion and r2 made by hand. +const monitoringEffectDoc = `{"rules":[{"id":"r1","name":"Heizung","enabled":true,"conditions":[],"actions":[],"learned_from":{"suggestion":"switchtime:r1:dev-a","kind":"switch_time","at":1700000000}},{"id":"r2","name":"Licht","enabled":true,"conditions":[],"actions":[]}],"scenarios":[{"id":"s1","name":"Trockner","enabled":true,"learned_from":{"suggestion":"surplus:dryer","kind":"surplus_window","at":1700000000}}]}` + +// effectRuleDoc holds r1 from a learned suggestion and r2 made by hand. +const effectRuleDoc = `{"rules":[{"id":"r1","name":"Heizung","enabled":true,"conditions":[],"actions":[],"learned_from":{"suggestion":"switchtime:r1:dev-a","kind":"switch_time","at":1700000000}},{"id":"r2","name":"Licht","enabled":true,"conditions":[],"actions":[]}]}` + +func effectFinding(rule string) autolearn.Finding { + return autolearn.Finding{ID: "effect:" + rule, Kind: "effect", RuleIDs: []string{rule}, Severity: "info"} +} + +func TestMonitoringEffectsKeepsAdoptedEntriesAndNamesThem(t *testing.T) { + doc, err := autolearn.ParseDoc([]byte(monitoringEffectDoc)) + if err != nil { + t.Fatal(err) + } + all := []autolearn.Finding{effectFinding("r1"), effectFinding("r2"), effectFinding("s1"), effectFinding("gone")} + got, names := monitoringEffects(all, doc, true) + if len(got) != 2 || got[0].ID != "effect:r1" || got[1].ID != "effect:s1" { + t.Fatalf("effects = %+v, want r1 and s1", got) + } + if names["r1"] != "Heizung" || names["s1"] != "Trockner" { + t.Errorf("names = %v", names) + } +} + +func TestMonitoringEffectsKeepsAllWhenRulesUnreadable(t *testing.T) { + got, names := monitoringEffects([]autolearn.Finding{effectFinding("r1")}, autolearn.Doc{}, false) + if len(got) != 1 || len(names) != 0 { + t.Fatalf("effects = %+v, names = %v, want the effect without names", got, names) + } +} diff --git a/dashboard/internal/autolearn/demo_test.go b/dashboard/internal/autolearn/demo_test.go index c9ac8f44..aaa18bf8 100644 --- a/dashboard/internal/autolearn/demo_test.go +++ b/dashboard/internal/autolearn/demo_test.go @@ -1181,15 +1181,15 @@ func TestDemoSeedShowsEveryEffectState(t *testing.T) { t.Errorf("%s: no scenario adopted from a window suggestion", name) } - // The threshold rule has a measured effect that the band shows with the grid share. - var band bool - for _, f := range store.BandEntries(now) { + // The threshold rule has a measured effect with the grid share that Monitoring lists. + var measured bool + for _, f := range store.Measured(now) { if f.ID == "effect:regel_wasch_ueberschuss_an" && f.Summary.Code == "effect.ok" { - band = true + measured = true } } - if !band { - t.Errorf("%s: no effect.ok band entry for regel_wasch_ueberschuss_an", name) + if !measured { + t.Errorf("%s: no measured effect.ok for regel_wasch_ueberschuss_an", name) } // The dehumidifier rule shows one reversal among four switch-offs. diff --git a/dashboard/internal/autolearn/effect_store.go b/dashboard/internal/autolearn/effect_store.go index 16f57ab4..57727d4c 100644 --- a/dashboard/internal/autolearn/effect_store.go +++ b/dashboard/internal/autolearn/effect_store.go @@ -14,8 +14,8 @@ import ( "github.com/Developer-Simon/energy-node-dashboard/internal/energystats" ) -// effectBandSpan is how long the effect of an adopted suggestion stays on the band. -const effectBandSpan = 8 * 7 * 24 * time.Hour +// effectListSpan is how long Monitoring lists the effect of an adopted suggestion. +const effectListSpan = 8 * 7 * 24 * time.Hour // effectEntry is the measured effect of one rule or scenario that came from a // learned suggestion. Before holds the baseline measures, Values the numbers @@ -207,9 +207,10 @@ func (s *EffectStore) Findings(now time.Time) []Finding { return out } -// BandEntries returns the feedback findings of the entries with a measured -// effect that is still shown on the band, sorted by rule ID. -func (s *EffectStore) BandEntries(now time.Time) []Finding { +// Measured returns the effect findings of the entries with a measured effect +// that Monitoring still lists, sorted by rule ID. They are the findings of the +// rule marks. +func (s *EffectStore) Measured(now time.Time) []Finding { s.mu.Lock() defer s.mu.Unlock() out := []Finding{} @@ -217,10 +218,10 @@ func (s *EffectStore) BandEntries(now time.Time) []Finding { if e.Result.Status != EffectStatusOK || e.Unit == "" { continue } - if !now.Before(time.Unix(e.At, 0).Add(effectBandSpan)) { + if !now.Before(time.Unix(e.At, 0).Add(effectListSpan)) { continue } - out = append(out, effectFinding(e, "effect:"+e.Rule, "feedback", now.Location())) + out = append(out, effectFinding(e, FindingID("effect", e.Rule), "check", now.Location())) } return out } diff --git a/dashboard/internal/autolearn/effect_store_test.go b/dashboard/internal/autolearn/effect_store_test.go index 7caff2c0..5b33a254 100644 --- a/dashboard/internal/autolearn/effect_store_test.go +++ b/dashboard/internal/autolearn/effect_store_test.go @@ -86,12 +86,12 @@ func TestEffectStoreFindingsAndBand(t *testing.T) { t.Errorf("Evidence = %+v", f.Evidence) } - band := s.BandEntries(now) - if len(band) != 1 || band[0].ID != "effect:r1" || band[0].Group != "feedback" { - t.Fatalf("BandEntries = %+v, want one feedback entry", band) + measured := s.Measured(now) + if len(measured) != 1 || measured[0].ID != "effect:r1" || measured[0].Group != "check" { + t.Fatalf("Measured = %+v, want the finding of the rule mark", measured) } - if late := s.BandEntries(at.Add(8*7*24*time.Hour + time.Hour)); len(late) != 0 { - t.Errorf("BandEntries eight weeks later = %d, want 0", len(late)) + if late := s.Measured(at.Add(8*7*24*time.Hour + time.Hour)); len(late) != 0 { + t.Errorf("Measured eight weeks later = %d, want 0", len(late)) } } @@ -111,7 +111,7 @@ func TestEffectStoreRemovedRuleIsDropped(t *testing.T) { if added := s.Sync(doc, at, days, nil, effMark()); added { t.Errorf("%s: Sync reported an added entry", name) } - if s.Len() != 0 || len(s.Findings(now)) != 0 || len(s.BandEntries(now)) != 0 { + if s.Len() != 0 || len(s.Findings(now)) != 0 || len(s.Measured(now)) != 0 { t.Errorf("%s: entry kept, Len = %d", name, s.Len()) } } @@ -167,8 +167,8 @@ func TestEffectStoreResetWithoutDays(t *testing.T) { if len(fs) != 1 || fs[0].Summary.Code != "effect.no_baseline" { t.Fatalf("Findings = %+v, want one effect.no_baseline", fs) } - if len(s.BandEntries(now)) != 0 { - t.Error("BandEntries not empty without a baseline") + if len(s.Measured(now)) != 0 { + t.Error("Measured not empty without a baseline") } } @@ -392,7 +392,7 @@ func TestSeasonDriftOneValuePerDay(t *testing.T) { } } -func TestSeasonDriftNotInBand(t *testing.T) { +func TestSeasonDriftNotMeasured(t *testing.T) { s, _, at := driftStore(t) for n := 1; n <= 12; n++ { tm := 1350.0 @@ -402,11 +402,11 @@ func TestSeasonDriftNotInBand(t *testing.T) { driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) } if len(seasonFindings(s.Findings(at.AddDate(0, 0, 12)))) != 1 { - t.Fatal("no season finding to test the band against") + t.Fatal("no season finding to test the measured list against") } - for _, f := range s.BandEntries(at.AddDate(0, 0, 12)) { + for _, f := range s.Measured(at.AddDate(0, 0, 12)) { if f.Kind == "season_shift" { - t.Errorf("BandEntries contains %q", f.ID) + t.Errorf("Measured contains %q", f.ID) } } } @@ -483,8 +483,8 @@ func TestEffectStoreCountOnlyWithoutUnit(t *testing.T) { if f.Evidence.Shape != "" || len(f.Evidence.Scales) != 0 || f.Evidence.IstValue != nil || f.Evidence.SollValue != nil { t.Errorf("Evidence = %+v, want none", f.Evidence) } - if band := s.BandEntries(now); len(band) != 0 { - t.Errorf("BandEntries = %d, want none without a unit", len(band)) + if band := s.Measured(now); len(band) != 0 { + t.Errorf("Measured = %d, want none without a unit", len(band)) } } diff --git a/dashboard/internal/monitoring/notice.go b/dashboard/internal/monitoring/notice.go index 55bf1203..832e8d55 100644 --- a/dashboard/internal/monitoring/notice.go +++ b/dashboard/internal/monitoring/notice.go @@ -29,7 +29,7 @@ type Ack struct { // Quelle (Kettenbefund), sonst null. FirstSeen und Ack setzt der Store. type Notice struct { ID string `json:"id"` - Source string `json:"source"` // energy, chain, learn + Source string `json:"source"` // energy, chain, learn, effect, suggest Severity string `json:"severity"` // warn, info Code string `json:"code"` Params map[string]any `json:"params,omitempty"` @@ -50,14 +50,20 @@ type Input struct { // Suggestions are the suggestions of the band as the automations page shows // them. Each one becomes a notice that opens it there. Suggestions []autolearn.Finding + // Effects are the measured effects of adopted suggestions. RuleNames gives + // the names of their rules and scenarios by ID. + Effects []autolearn.Finding + RuleNames map[string]string } -// Collect baut die Meldungen in fester Reihenfolge: energy, chain, learn. +// Collect baut die Meldungen in fester Reihenfolge: energy, chain, learn, +// effect, suggest. func Collect(in Input) []Notice { out := []Notice{} out = append(out, energyNotices(in)...) out = append(out, chainNotices(in.Snapshot)...) out = append(out, learnNotices(in.Findings)...) + out = append(out, effectNotices(in.Effects, in.RuleNames)...) out = append(out, suggestionNotices(in.Suggestions)...) return out } @@ -238,6 +244,42 @@ func learnNotices(findings []autolearn.Finding) []Notice { return out } +// effectNotices turns the measured effects into notices. They check an adopted +// suggestion and ask for nothing, so the step only opens the rule or scenario. +func effectNotices(list []autolearn.Finding, names map[string]string) []Notice { + var out []Notice + for _, f := range list { + if len(f.RuleIDs) == 0 { + continue + } + rule := f.RuleIDs[0] + params := make(map[string]any, len(f.Summary.Params)+3) + for k, v := range f.Summary.Params { + params[k] = v + } + params["kind"] = f.Kind + params["confidence"] = f.Confidence + params["rule"] = rule + if name := names[rule]; name != "" { + params["rule"] = name + } + n := Notice{ + ID: f.ID, + Source: "effect", + Severity: learnSeverity(f.Severity), + Code: f.Summary.Code, + Params: params, + Steps: []Step{{Code: "rule_open", Target: "rule", IDs: []string{rule}}}, + } + if f.Evidence.Shape != "" { + ev := f.Evidence + n.Evidence = &ev + } + out = append(out, n) + } + return out +} + // suggestionNotices turns the visible suggestions into notices. The step opens // the suggestion on the automations page. Their source is suggest, the page lists // them under the filter Vorschläge. diff --git a/dashboard/internal/monitoring/notice_test.go b/dashboard/internal/monitoring/notice_test.go index c36f1280..90ef58f4 100644 --- a/dashboard/internal/monitoring/notice_test.go +++ b/dashboard/internal/monitoring/notice_test.go @@ -145,3 +145,42 @@ func TestCollectOpensScenarioRegulatorFinding(t *testing.T) { t.Errorf("facts = %+v", got[0].Facts) } } + +// A measured effect becomes a notice of its own source that names the rule and opens it. +func TestMeasuredEffectsBecomeNoticesThatOpenTheRule(t *testing.T) { + in := Input{ + Effects: []autolearn.Finding{{ + ID: "effect:r1", Kind: "effect", Severity: "info", Confidence: "estimate", RuleIDs: []string{"r1"}, + Summary: autolearn.Text{Code: "effect.ok", Params: map[string]any{"before": 20.0, "since": 2.0}}, + Evidence: autolearn.Evidence{Shape: "scale", Labels: []string{"before", "since"}}, + }, { + ID: "effect:gone", Kind: "effect", Severity: "info", Confidence: "high", RuleIDs: []string{"gone"}, + Summary: autolearn.Text{Code: "effect.not_measurable"}, + }}, + RuleNames: map[string]string{"r1": "Entfeuchter aus"}, + } + got := Collect(in) + if len(got) != 2 { + t.Fatalf("notices = %+v, want two", got) + } + n := got[0] + if n.ID != "effect:r1" || n.Source != "effect" || n.Severity != "info" || n.Code != "effect.ok" { + t.Errorf("notice = %+v", n) + } + if n.Params["rule"] != "Entfeuchter aus" || n.Params["kind"] != "effect" || n.Params["confidence"] != "estimate" || n.Params["before"] != 20.0 { + t.Errorf("params = %+v", n.Params) + } + if len(n.Steps) != 1 || n.Steps[0].Code != "rule_open" || n.Steps[0].Target != "rule" || + len(n.Steps[0].IDs) != 1 || n.Steps[0].IDs[0] != "r1" { + t.Errorf("steps = %+v, want one rule_open step with the rule id", n.Steps) + } + if n.Evidence == nil || n.Evidence.Shape != "scale" { + t.Errorf("evidence = %+v", n.Evidence) + } + if got[1].Params["rule"] != "gone" || got[1].Evidence != nil { + t.Errorf("without a name the ID stands, without a shape no evidence: %+v", got[1]) + } + if in.Effects[0].Summary.Params["rule"] != nil { + t.Error("Collect changed the params of the finding") + } +} diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index 1f50f54d..79354015 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -3,6 +3,8 @@ v0.11.22-pre.38,2026-11-29,css/automations.css,26, v0.11.22-pre.38,2026-11-29,js/automation-evidence.js,7, v0.11.22-pre.38,2026-11-29,js/automation-suggestions.js,7, v0.11.22-pre.38,2026-11-29,js/automations.page.js,33, +v0.11.22-pre.38,2026-11-29,js/monitoring-model.js,5, +v0.11.22-pre.38,2026-11-29,js/monitoring.page.js,4, v0.11.22-pre.37,2026-11-25,css/settings-controls.css,21,"settings, diagnostics: system card on the versions page" v0.11.22-pre.37,2026-11-25,js/versions.page.js,11,"settings, diagnostics: system card on the versions page" v0.11.22-pre.36,2026-11-23,css/monitoring.css,2, diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 6e3f79ab..fc8e3481 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -499,11 +499,9 @@ "automations.learn.battery.full_early.line": "Voll um {time}, danach rund {kwh_after} kWh Einspeisung", "automations.learn.battery.full_early.text": "An den meisten Tagen ist der Akku schon vor dem Sonnenhöchststand voll, im Median um {time}. Danach gehen rund {kwh_after} kWh ins Netz.", "automations.learn.battery.full_early.title": "Akku ist zu früh voll", - "automations.learn.button.hide": "Ausblenden", "automations.learn.button.later": "Später", "automations.learn.button.never": "Nicht mehr vorschlagen", "automations.learn.button.open_assistant": "Im Assistenten öffnen", - "automations.learn.button.open_rule": "Regel öffnen", "automations.learn.button.undo": "Rückgängig", "automations.learn.check.competition.text": "Mehrere Regeln schalten beim selben Überschuss ein. Lösen sie zusammen aus, zieht danach der Netzbezug. Gestaffelte Schwellen geben jeder Last ihren eigenen Platz.", "automations.learn.check.competition.title": "Regeln konkurrieren um denselben Überschuss", @@ -612,7 +610,6 @@ "automations.learn.fix.time_point_learned": "Auf den Lernwert umstellen", "automations.learn.group.check": "Regelprüfung", "automations.learn.group.energy": "Energie", - "automations.learn.group.feedback": "Wirkung", "automations.learn.group.habit": "Gewohnheit", "automations.learn.group.reliability": "Zuverlässigkeit", "automations.learn.hint.dismissed": "Vorschlag ausgeblendet", @@ -621,11 +618,9 @@ "automations.learn.lane.ist": "Ist", "automations.learn.lane.since": "Seitdem", "automations.learn.lane.soll": "Soll", - "automations.learn.legend.before_since": "Vorher: der Wert vor der Übernahme. Seitdem: der Wert seit der Übernahme.", "automations.learn.legend.day": "Ist: wann es passiert ist. Soll: wann der Vorschlag schalten würde.", "automations.learn.legend.events": "Ist: jedes beobachtete Ereignis. Soll: was der Vorschlag ändern würde.", "automations.learn.legend.label": "Was bedeuten Ist und Soll?", - "automations.learn.legend.label_before_since": "Was bedeuten Vorher und Seitdem?", "automations.learn.legend.scale": "Ist: der beobachtete Wert. Soll: der vorgeschlagene Wert.", "automations.learn.mark_label": "Befund zu dieser Regel anzeigen", "automations.learn.param.deadband_w": "Totzone", @@ -3818,6 +3813,7 @@ "monitoring.energy_line.new": "{count} neu", "monitoring.energy_line.none": "Keine offenen Meldungen zur Energie", "monitoring.energy_line.open": "Im Monitoring ansehen", + "monitoring.fact.confidence": "Belastbarkeit", "monitoring.fact.direction": "Richtung", "monitoring.fact.direction_value": "{az}° ({compass}), {el}° über dem Horizont", "monitoring.fact.loss": "Verlust", @@ -3828,6 +3824,7 @@ "monitoring.fact.value": "Wert", "monitoring.fact.weeks": "Kalenderwochen", "monitoring.filter.all": "Alle", + "monitoring.filter.effect": "Erfolgskontrolle", "monitoring.filter.energy": "Energie", "monitoring.filter.label": "Quelle", "monitoring.filter.learn": "Lernfunktionen", @@ -3903,6 +3900,7 @@ "monitoring.site.surplus_note": "Prognose von 10 Uhr", "monitoring.site.to_forecast": "Zur Prognose", "monitoring.source.chain": "Messketten", + "monitoring.source.effect": "Erfolgskontrolle", "monitoring.source.energy": "Energie-Bilanz", "monitoring.source.learn": "Lernfunktionen", "monitoring.source.suggest": "Vorschläge", @@ -3926,6 +3924,8 @@ "monitoring.step.load_mode_auto.button": "Zur Einstellung", "monitoring.step.role_keep": "Oder alle ohne Rolle lassen", "monitoring.step.role_keep.button": "Ohne Rolle lassen", + "monitoring.step.rule_open": "Die geprüfte Regel steht unter Automationen", + "monitoring.step.rule_open.button": "Regel öffnen", "monitoring.step.set_load_role": "Dem Hauszähler die Rolle Hauszähler geben", "monitoring.step.set_load_role.button": "Rolle setzen", "monitoring.step.set_role": "Rolle der Werte neu setzen", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index ce9e745b..a1561a1e 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -499,11 +499,9 @@ "automations.learn.battery.full_early.line": "Full at {time}, then about {kwh_after} kWh fed in", "automations.learn.battery.full_early.text": "On most days the battery is already full before solar noon, at a median of {time}. Afterwards about {kwh_after} kWh go into the grid.", "automations.learn.battery.full_early.title": "Battery is full too early", - "automations.learn.button.hide": "Hide", "automations.learn.button.later": "Later", "automations.learn.button.never": "Do not suggest again", "automations.learn.button.open_assistant": "Open in assistant", - "automations.learn.button.open_rule": "Open rule", "automations.learn.button.undo": "Undo", "automations.learn.check.competition.text": "Several rules switch on at the same surplus. When they fire together, the grid import follows. Staggered thresholds give each load its own place.", "automations.learn.check.competition.title": "Rules compete for the same surplus", @@ -612,7 +610,6 @@ "automations.learn.fix.time_point_learned": "Switch to the learned value", "automations.learn.group.check": "Rule check", "automations.learn.group.energy": "Energy", - "automations.learn.group.feedback": "Effect", "automations.learn.group.habit": "Habit", "automations.learn.group.reliability": "Reliability", "automations.learn.hint.dismissed": "Suggestion hidden", @@ -621,11 +618,9 @@ "automations.learn.lane.ist": "Actual", "automations.learn.lane.since": "Since", "automations.learn.lane.soll": "Target", - "automations.learn.legend.before_since": "Before: the value before the change. Since: the value since the change.", "automations.learn.legend.day": "Actual: when it happened. Target: when the suggestion would switch.", "automations.learn.legend.events": "Actual: each event we saw. Target: what the suggestion would change.", "automations.learn.legend.label": "What do Actual and Target mean?", - "automations.learn.legend.label_before_since": "What do Before and Since mean?", "automations.learn.legend.scale": "Actual: the value we saw. Target: the suggested value.", "automations.learn.mark_label": "Show the finding for this rule", "automations.learn.param.deadband_w": "Deadband", @@ -3818,6 +3813,7 @@ "monitoring.energy_line.new": "{count} new", "monitoring.energy_line.none": "No open notices about energy", "monitoring.energy_line.open": "Open in monitoring", + "monitoring.fact.confidence": "Confidence", "monitoring.fact.direction": "Direction", "monitoring.fact.direction_value": "{az}° ({compass}), {el}° above the horizon", "monitoring.fact.loss": "Loss", @@ -3828,6 +3824,7 @@ "monitoring.fact.value": "Value", "monitoring.fact.weeks": "Calendar weeks", "monitoring.filter.all": "All", + "monitoring.filter.effect": "Results check", "monitoring.filter.energy": "Energy", "monitoring.filter.label": "Source", "monitoring.filter.learn": "Learning", @@ -3903,6 +3900,7 @@ "monitoring.site.surplus_note": "Forecast from 10:00", "monitoring.site.to_forecast": "To the forecast", "monitoring.source.chain": "Measurement chains", + "monitoring.source.effect": "Results check", "monitoring.source.energy": "Energy balance", "monitoring.source.learn": "Learning", "monitoring.source.suggest": "Suggestions", @@ -3926,6 +3924,8 @@ "monitoring.step.load_mode_auto.button": "To the setting", "monitoring.step.role_keep": "Or leave all of them without a role", "monitoring.step.role_keep.button": "Leave without role", + "monitoring.step.rule_open": "The checked rule is under Automations", + "monitoring.step.rule_open.button": "Open the rule", "monitoring.step.set_load_role": "Give the house meter the role house meter", "monitoring.step.set_load_role.button": "Set role", "monitoring.step.set_role": "Set the role of the values again", diff --git a/dashboard/internal/webui/static/css/automations.css b/dashboard/internal/webui/static/css/automations.css index 344f0ad2..ab60598e 100644 --- a/dashboard/internal/webui/static/css/automations.css +++ b/dashboard/internal/webui/static/css/automations.css @@ -1098,7 +1098,6 @@ button.auto-learn-tile[aria-expanded="true"]:not(:disabled) { background: var(-- .auto-learn-group.is-reliability { color: var(--warn); } .auto-learn-group.is-check { color: var(--info); } .auto-learn-group.is-energy { color: var(--flow-pv); } -.auto-learn-group.is-feedback { color: var(--ok); } .auto-learn-more { box-sizing: border-box; font: inherit; font-size: .88rem; font-weight: 600; color: var(--text-muted); cursor: pointer; background: transparent; border: 1px dashed var(--border); border-radius: var(--radius-md); padding: 0 1rem; min-width: 3.2rem; transition: transform 120ms var(--ease-out); } diff --git a/dashboard/internal/webui/static/js/automation-suggestions.js b/dashboard/internal/webui/static/js/automation-suggestions.js index b34266cb..a5a8a83c 100644 --- a/dashboard/internal/webui/static/js/automation-suggestions.js +++ b/dashboard/internal/webui/static/js/automation-suggestions.js @@ -99,9 +99,7 @@ // Die Legende hangt an der Form der Grafik. Ohne bekannte Form gibt es keine. function legend(s, t) { - const ev = s && s.evidence; - if (ev && ev.shape === 'scale' && Array.isArray(ev.labels) && ev.labels.length === 2) return t(CAT + 'legend.before_since', {}); - const shape = ev && ev.shape; + const shape = s && s.evidence && s.evidence.shape; if (SHAPES_WITH_LEGEND.indexOf(shape) < 0) return ''; return t(CAT + 'legend.' + shape, {}); } @@ -268,11 +266,9 @@ if (this.open && this.$nextTick) this.$nextTick(() => this.placeCaret()); }, - // Befunde zur Wirkung und zur Jahreszeit nennen den Namen der Regel aus dem Dokument. - ruled(s) { return s && (s.kind === 'effect' || s.kind === 'season_shift') ? api.withRuleName(s, this.document) : s; }, - titleOf(s, t) { return api.title(this.ruled(s), t); }, - lineOf(s, t) { return api.line(this.ruled(s), t); }, - textOf(s, t) { return api.text(this.ruled(s), t); }, + titleOf(s, t) { return api.title(s, t); }, + lineOf(s, t) { return api.line(s, t); }, + textOf(s, t) { return api.text(s, t); }, legendOf(s, t) { return api.legend(s, t); }, groupLabel(s, t) { return t(CAT + 'group.' + s.group, {}); }, evidenceOf(s, t) { return window.AutomationEvidence ? window.AutomationEvidence.render(s.evidence, t, { full: this.fullDay }) : ''; }, @@ -287,8 +283,6 @@ }, // Die Wochen gelten nur mit Zeitraum. Ein Befund nur mit Heizzeit zeigt die Heizzeit daneben. seasonOf(s, t) { - // Befunde der Rueckmeldung gelten nicht fuer eine Jahreszeit, sie zeigen keine Pille. - if (s.group === 'feedback') return ''; const season = s.season; if (!season) return t(CAT + 'season.all', {}); if (!season.from_week || !season.to_week) return ''; @@ -315,25 +309,8 @@ }, actionsOf(s) { const edit = Boolean(this.canEdit) && Boolean(s); - // Wirkung: nur die Regel oeffnen, ausblenden mit dem Bearbeitungsrecht. - if (s && s.group === 'feedback') return { assistant: false, apply: false, later: false, dismiss: false, openRule: true, hide: edit }; - return { assistant: edit && Boolean(this.fixOf(s)), apply: edit && Boolean(this.opFixOf(s)), later: edit, dismiss: edit, openRule: false, hide: false }; + return { assistant: edit && Boolean(this.fixOf(s)), apply: edit && Boolean(this.opFixOf(s)), later: edit, dismiss: edit }; }, - // Die Regel oder Szene zur Befundkarte: Regeln im Reiter Regeln, Szenen aufgeklappt im Reiter Szenarien. - openRuleOf(s) { - const id = s && Array.isArray(s.rule_ids) ? s.rule_ids[0] : ''; - const doc = this.document || {}; - if ((doc.rules || []).some((rule) => rule.id === id)) { - this.view = 'rules'; - this.focusRule(id); - return; - } - if ((doc.scenarios || []).some((scenario) => scenario.id === id)) { - this.view = 'scenarios'; - this.scenarioExpanded[id] = true; - } - }, - async send(s, action) { const response = await window.fetch(base() + REQUEST_PATH + '/' + encodeURIComponent(s.id) + '/' + action, { method: 'POST', diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index 311ff581..6e4e3792 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -1377,9 +1377,22 @@ // Die Device Map verweist auf eine Regel: aufklappen, zur Regel scrollen // und sie kurz hervorheben. + // Zeigt die Regel im Reiter Regeln, ein Szenario aufgeklappt im Reiter Szenarien. focusRule(ruleId) { window.__automationFocusRequest__ = null; if (!ruleId) return; + const doc = this.document || {}; + if ((doc.scenarios || []).some((scenario) => scenario.id === ruleId)) { + this.view = 'scenarios'; + this.scenarioExpanded[ruleId] = true; + const show = () => { + const node = document.querySelector(`[data-scenario-id="${CSS.escape(ruleId)}"]`); + if (node) node.scrollIntoView({behavior: window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'start'}); + }; + if (this.$nextTick) this.$nextTick(show); else show(); + return; + } + if ((doc.rules || []).some((rule) => rule.id === ruleId)) this.view = 'rules'; this.expanded[ruleId] = true; this.flashRule = ruleId; setTimeout(() => { if (this.flashRule === ruleId) this.flashRule = ''; }, 1600); diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index a8484694..46f1b61a 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -7,20 +7,19 @@ const pad = (n) => String(n).padStart(2, '0'); // Quelle für Filter und Gruppen: Energie-Bilanz und Messketten zusammen, Vorschläge - // für sich, sonst Lernfunktionen. + // und Erfolgskontrolle für sich, sonst Lernfunktionen. function sourceOf(notice) { if (notice.source === 'energy' || notice.source === 'chain') return 'energy'; - return notice.source === 'suggest' ? 'suggest' : 'learn'; + return notice.source === 'suggest' || notice.source === 'effect' ? notice.source : 'learn'; } - // Lernbefunde und Vorschläge teilen Texte und Belege der Automationen. + // Lernbefunde, Vorschläge und Erfolgskontrolle teilen Texte und Belege der Automationen. function isLearned(notice) { - const source = sourceOf(notice); - return source === 'learn' || source === 'suggest'; + return sourceOf(notice) !== 'energy'; } function filterNotices(notices, filter) { - if (filter === 'energy' || filter === 'learn' || filter === 'suggest') { + if (filter === 'energy' || filter === 'learn' || filter === 'suggest' || filter === 'effect') { return notices.filter((n) => sourceOf(n) === filter); } return notices.slice(); @@ -161,6 +160,10 @@ return rows; } if (sourceOf(notice) === 'learn' && p.kind === 'shade') return shadeFacts(notice, p, t); + if (sourceOf(notice) === 'effect') { + const confidence = p.confidence === 'high' ? t('automations.learn.confidence.sure') : t('automations.learn.confidence.estimate'); + return [[t('monitoring.fact.confidence'), confidence]]; + } if (isLearned(notice) && Array.isArray(notice.facts) && notice.facts.length) return learnFacts(notice.facts, t); return []; } @@ -173,7 +176,7 @@ if (target === 'efficiency') return !!can.view_efficiency; if (target === 'devicemap') return !!can.view_device_map; if (target === 'action.role_keep') return !!can.edit_energy; - if (target === 'suggestion') return !!can.view_automations; + if (target === 'suggestion' || target === 'rule') return !!can.view_automations; return false; } diff --git a/dashboard/internal/webui/static/js/monitoring.page.js b/dashboard/internal/webui/static/js/monitoring.page.js index 382786ad..924273f5 100644 --- a/dashboard/internal/webui/static/js/monitoring.page.js +++ b/dashboard/internal/webui/static/js/monitoring.page.js @@ -3,8 +3,9 @@ // mit dem CSRF-Token der Sitzung. Die Texte baut window.MonitoringModel. // // i18n-keys: monitoring.filter.all, monitoring.filter.energy, monitoring.filter.learn, -// monitoring.filter.suggest, monitoring.source.energy, monitoring.source.chain, -// monitoring.source.learn, monitoring.source.suggest, +// monitoring.filter.suggest, monitoring.filter.effect, monitoring.source.energy, +// monitoring.source.chain, monitoring.source.learn, monitoring.source.suggest, +// monitoring.source.effect, // monitoring.group.new, monitoring.group.known, monitoring.steps.title, // monitoring.ack.button, monitoring.ack.done, monitoring.ack.undo, monitoring.ack.no_right, // monitoring.badge.new @@ -21,12 +22,14 @@ { id: 'energy', key: 'monitoring.filter.energy' }, { id: 'learn', key: 'monitoring.filter.learn' }, { id: 'suggest', key: 'monitoring.filter.suggest' }, + { id: 'effect', key: 'monitoring.filter.effect' }, ]; const SOURCE_KEYS = { energy: 'monitoring.source.energy', chain: 'monitoring.source.chain', learn: 'monitoring.source.learn', suggest: 'monitoring.source.suggest', + effect: 'monitoring.source.effect', }; const GROUP_KEYS = { new: 'monitoring.group.new', known: 'monitoring.group.known' }; // Sprungziel der Schritte auf die Seite (Reiter) und das Panel, das den Reiter besitzt. @@ -232,6 +235,7 @@ if (!step || !step.target) return; if (step.target === 'learned') { this.goLearned(step.key); return; } if (step.target === 'suggestion') { this.goSuggestion((step.ids || [])[0]); return; } + if (step.target === 'rule') { this.goRule((step.ids || [])[0]); return; } if (step.target === 'action.role_keep') { this.roleKeep(step.ids); return; } const panel = panelFor(step.target); if (!panel) return; @@ -262,6 +266,18 @@ }); }, + // Sprung zur Regel oder zum Szenario. Erst der Reiter, damit die Seite beim Scrollen + // sichtbar ist. Ist sie noch nicht geladen, nimmt sie die Anfrage beim Laden entgegen. + goRule(id) { + if (!id) return; + window.__automationFocusRequest__ = id; + openTab('automations-panel'); + this.$nextTick(() => { + if (window.__automationFocusRequest__ !== id) return; + window.dispatchEvent(new CustomEvent('automation-focus-rule', { detail: { id } })); + }); + }, + // Sprung zum aufgeklappten Vorschlag. Ist die Automationen-Seite noch nicht // geladen, nimmt ihr Band die Anfrage in load() entgegen. goSuggestion(id) { diff --git a/dashboard/internal/webui/templates/automations.html b/dashboard/internal/webui/templates/automations.html index 674604d1..f4b12890 100644 --- a/dashboard/internal/webui/templates/automations.html +++ b/dashboard/internal/webui/templates/automations.html @@ -90,14 +90,14 @@

{{t "automations.le
-
@@ -119,7 +119,7 @@

- @@ -139,11 +139,8 @@

x-on:click="openAssistantWith(fixOf(current).template, fixOf(current).prefill, originOf(current))">{{t "automations.learn.button.open_assistant"}} - -
diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index f5cbe69b..fb078188 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -237,7 +237,7 @@

{{t "no_access.title"}}

{{if index .Can "view_history"}}

{{t "panel.history_loading"}}

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

{{t "panel.stats_loading"}}

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

{{t "panel.efficiency_loading"}}

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

{{t "panel.monitoring_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_config"}}

{{t "panel.config_loading"}}

{{end}} diff --git a/dashboard/internal/webui/templates/monitoring.html b/dashboard/internal/webui/templates/monitoring.html index 0dd05529..37d771a7 100644 --- a/dashboard/internal/webui/templates/monitoring.html +++ b/dashboard/internal/webui/templates/monitoring.html @@ -19,7 +19,7 @@
diff --git a/dashboard/test/automation-suggestions.test.mjs b/dashboard/test/automation-suggestions.test.mjs index 52ef4927..ef623537 100644 --- a/dashboard/test/automation-suggestions.test.mjs +++ b/dashboard/test/automation-suggestions.test.mjs @@ -52,9 +52,7 @@ function requiredKeys() { keys.push('automations.learn.drop_failed'); keys.push('automations.learn.season.heating', 'automations.learn.unit.kwh_week'); // Wirkung: Befunde der Regelwirkung, Spurmarken, Einheiten, Parameter und Befunde zur Jahreszeit. - keys.push('automations.learn.group.feedback', 'automations.learn.lane.before', 'automations.learn.lane.since'); - keys.push('automations.learn.legend.before_since', 'automations.learn.unit.actions_week'); - keys.push('automations.learn.button.open_rule', 'automations.learn.button.hide'); + keys.push('automations.learn.lane.before', 'automations.learn.lane.since', 'automations.learn.unit.actions_week'); EFFECT_CODES.forEach((code) => ['title', 'line', 'text'].forEach((part) => keys.push(`automations.learn.${code}.${part}`))); SEASON_CODES.forEach((code) => ['title', 'line', 'text'].forEach((part) => keys.push(`automations.learn.${code}.${part}`))); PARAM_CODES.forEach((name) => keys.push(`automations.learn.param.${name}`)); @@ -412,8 +410,8 @@ test('the assistant button needs a template fix and the editing permission', asy const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [unplanned, templ], learning: { since: 1, devices: 1, days: 1 } })); await band.load(); band.canEdit = true; - assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: false, later: true, dismiss: true, openRule: false, hide: false }); - assert.deepEqual(plain(band.actionsOf(band.items[1])), { assistant: true, apply: false, later: true, dismiss: true, openRule: false, hide: false }); + assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: false, later: true, dismiss: true }); + assert.deepEqual(plain(band.actionsOf(band.items[1])), { assistant: true, apply: false, later: true, dismiss: true }); assert.equal(band.fixOf(band.items[1]).template, 'follow_switch'); close(); }); @@ -435,7 +433,7 @@ test('a fix with ops and no template gets the apply button with the fix label', const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [limit], learning: { since: 1, devices: 1, days: 1 } })); await band.load(); band.canEdit = true; - assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: true, later: true, dismiss: true, openRule: false, hide: false }); + assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: true, later: true, dismiss: true }); assert.equal(band.opFixOf(band.items[0]).code, 'add_condition'); assert.equal(band.applyLabelOf(band.items[0], catalogT('de')), catalogs.de['automations.learn.fix.add_condition']); band.canEdit = false; @@ -448,7 +446,7 @@ test('without the automations permission there are no buttons at all', async () const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [templ], learning: { since: 1, devices: 1, days: 1 } })); await band.load(); band.canEdit = false; - assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: false, later: false, dismiss: false, openRule: false, hide: false }); + assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: false, later: false, dismiss: false }); close(); }); @@ -636,15 +634,6 @@ test('a heating only season shows no week range, a dated season shows its weeks' close(); }); -test('a feedback finding shows no season pill, even without a season', () => { - const { band, close } = loadBand(listRoutes({ enabled: false, suggestions: [] })); - const t = catalogT('de'); - assert.equal(band.seasonOf({ group: 'feedback' }, t), ''); - assert.equal(band.seasonOf({ group: 'feedback', season: { from_week: 40, to_week: 16 } }, t), ''); - assert.equal(band.seasonOf({ group: 'check' }, t), catalogs.de['automations.learn.season.all']); - close(); -}); - test('a finding with only the heating limit shows the chip and no week range', () => { const { band, close } = loadBand(listRoutes({ enabled: false, suggestions: [] })); const t = catalogT('de'); @@ -852,52 +841,6 @@ test('withRuleName copies the finding and names its rule or scenario, with the i assert.equal(api.withRuleName({ ...s, rule_ids: ['x9'] }, doc).summary.params.rule, 'x9'); }); -test('the band titles an effect with the rule name from the page document', () => { - const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [], learning: { since: 1, devices: 1, days: 1 } })); - band.document = { rules: [{ id: 'r1', name: 'Pumpe Nacht' }], scenarios: [] }; - const { t, calls } = recorder(); - const s = { id: 'effect:r1', kind: 'effect', group: 'feedback', rule_ids: ['r1'], summary: { code: 'effect.not_measurable', params: { overridden: 0, fired: 3 } } }; - band.titleOf(s, t); - assert.equal(calls[0].key, 'automations.learn.effect.not_measurable.title'); - assert.equal(calls[0].params.rule, 'Pumpe Nacht'); - close(); -}); - -test('the legend of a before and since scale names both lanes', () => { - const { api } = load(); - const { t, calls } = recorder(); - api.legend({ summary: { code: 'effect.ok' }, evidence: { shape: 'scale', labels: ['before', 'since'] } }, t); - assert.equal(calls[0].key, 'automations.learn.legend.before_since'); -}); - -test('feedback findings offer the rule button and hide, other findings do not', async () => { - const feedback = { ...finding('effect:r1'), group: 'feedback', kind: 'effect', rule_ids: ['r1'] }; - const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [feedback, finding('p:1')], learning: { since: 1, devices: 1, days: 1 } })); - await band.load(); - band.canEdit = true; - assert.deepEqual(plain(band.actionsOf(band.items[0])), { assistant: false, apply: false, later: false, dismiss: false, openRule: true, hide: true }); - assert.deepEqual(plain(band.actionsOf(band.items[1])), { assistant: false, apply: false, later: true, dismiss: true, openRule: false, hide: false }); - band.canEdit = false; - assert.equal(band.actionsOf(band.items[0]).hide, false); - close(); -}); - -test('openRuleOf opens the rules view on the rule, or the scenarios view on an expanded scenario', async () => { - const { band, close } = loadBand(listRoutes({ enabled: true, suggestions: [], learning: { since: 1, devices: 1, days: 1 } })); - const focused = []; - band.focusRule = (id) => focused.push(id); - band.scenarioExpanded = {}; - band.view = 'scenarios'; - band.document = { rules: [{ id: 'r1', name: 'Pumpe' }], scenarios: [{ id: 's1', name: 'Urlaub' }] }; - band.openRuleOf({ rule_ids: ['r1'] }); - assert.equal(band.view, 'rules'); - assert.deepEqual(focused, ['r1']); - band.openRuleOf({ rule_ids: ['s1'] }); - assert.equal(band.view, 'scenarios'); - assert.equal(band.scenarioExpanded.s1, true); - close(); -}); - test('scale axis labels below 10 use the decimal comma of the page format', () => { const { evidence, document } = load(germanI18n); const host = document.createElement('div'); @@ -905,3 +848,11 @@ test('scale axis labels below 10 use the decimal comma of the page format', () = const labels = Array.from(host.querySelectorAll('.auto-learn-axis-label')).map((n) => n.textContent.split(' ')[0]); assert.deepEqual(labels, ['0', '2,5', '5']); }); + +test('the band has no effect actions, adopted rules are checked in monitoring', () => { + const { band, close } = loadBand(listRoutes({ enabled: false, suggestions: [] })); + assert.equal(band.openRuleOf, undefined); + assert.equal('openRule' in band.actionsOf(finding('p:1')), false); + assert.equal('hide' in band.actionsOf(finding('p:1')), false); + close(); +}); diff --git a/dashboard/test/automations.page.test.mjs b/dashboard/test/automations.page.test.mjs index 29a6b432..1900daeb 100644 --- a/dashboard/test/automations.page.test.mjs +++ b/dashboard/test/automations.page.test.mjs @@ -1778,6 +1778,19 @@ test('focusRule expands the rule and marks it for the flash', () => { assert.equal(component.flashRule, 'r 1'); }); +test('focusRule opens the rules view for a rule and the expanded scenario for a scenario', () => { + const { component, window } = createAutomationsPanel(); + window.CSS = { escape: value => value }; + component.document = { version: 1, settings: {}, rules: [{ id: 'r1', name: 'A', conditions: [], actions: [] }], scenarios: [{ id: 's1', name: 'B' }] }; + component.view = 'scenarios'; + component.focusRule('r1'); + assert.equal(component.view, 'rules'); + assert.equal(component.expanded.r1, true); + component.focusRule('s1'); + assert.equal(component.view, 'scenarios'); + assert.equal(component.scenarioExpanded.s1, true); +}); + test('customBalanceFields lists categories by label and keeps a removed one used in a rule', () => { const { component } = createAutomationsPanel(); component.categories = { diff --git a/dashboard/test/monitoring-model.test.mjs b/dashboard/test/monitoring-model.test.mjs index a5eff704..bbf96817 100644 --- a/dashboard/test/monitoring-model.test.mjs +++ b/dashboard/test/monitoring-model.test.mjs @@ -162,3 +162,32 @@ test('learned notices list their figures only with the suggestion band, shade ke assert.equal(M.facts(notice, t).length, 0); assert.equal(M.facts({ ...notice, facts: undefined }, t).length, 0); }); + +test('effect notices form their own filter and read the texts of the automations', () => { + const notices = [ + { id: 'effect:r1', source: 'effect' }, + { id: 'learn:x', source: 'learn' }, + { id: 'suggest:y', source: 'suggest' }, + ]; + assert.equal(M.sourceOf(notices[0]), 'effect'); + assert.equal(M.isLearned(notices[0]), true); + assert.deepEqual(M.filterNotices(notices, 'effect').map((n) => n.id), ['effect:r1']); + assert.deepEqual(M.filterNotices(notices, 'learn').map((n) => n.id), ['learn:x']); + const notice = { source: 'effect', code: 'effect.ok', params: { rule: 'Pumpe', before: 20, since: 2 } }; + assert.equal(M.title(notice, t), 'automations.learn.effect.ok.title' + JSON.stringify(notice.params)); + assert.equal(M.text(notice, t), 'automations.learn.effect.ok.text' + JSON.stringify(notice.params)); +}); + +test('an effect notice says how certain it is', () => { + const notice = (confidence) => ({ source: 'effect', code: 'effect.ok', params: { kind: 'effect', confidence } }); + assert.deepEqual(M.facts(notice('high'), t), [['monitoring.fact.confidence', 'automations.learn.confidence.sure']]); + assert.deepEqual(M.facts(notice('estimate'), t), [['monitoring.fact.confidence', 'automations.learn.confidence.estimate']]); +}); + +test('the rule step needs the right to view automations', () => { + const notice = { id: 'effect:r1', source: 'effect', steps: [{ code: 'rule_open', target: 'rule', ids: ['r1'] }] }; + const withRight = M.steps(notice, { view_automations: true }, t)[0]; + assert.equal(withRight.target, 'rule'); + assert.equal(withRight.label, 'monitoring.step.rule_open.button'); + assert.equal(M.steps(notice, {}, t)[0].target, ''); +}); diff --git a/dashboard/test/monitoring.page.test.mjs b/dashboard/test/monitoring.page.test.mjs index dce3533f..bffff2eb 100644 --- a/dashboard/test/monitoring.page.test.mjs +++ b/dashboard/test/monitoring.page.test.mjs @@ -63,7 +63,7 @@ function createPanel({ roles = ['edit_setup'], notices = null, ackReply = null, component.$refs = {}; component.$nextTick = (callback) => callback(); component.$watch = () => {}; - return { component, calls }; + return { component, calls, window: dom.window }; } test('load() splits the notices into a new and an acknowledged group', async () => { @@ -134,3 +134,29 @@ test('goLearned(key) clears the focus first so a repeated key is followed again' assert.deepEqual(writes, ['', 'site/day_start', '', 'site/day_start']); assert.equal(value, 'site/day_start'); }); + +test('the effect filter is listed and counts the effect notices', async () => { + const notices = [{ id: 'effect:r1', source: 'effect', severity: 'info', code: 'effect.not_measurable', params: { rule: 'R' }, steps: [], first_seen: NOW, ack: null }]; + const { component } = createPanel({ notices }); + await component.load(); + const chip = component.filters().find((f) => f.id === 'effect'); + assert.equal(chip.label, catalog('de')['monitoring.filter.effect']); + assert.equal(chip.count, 1); + assert.equal(component.rowMeta(component.notices[0]).startsWith(catalog('de')['monitoring.source.effect']), true); +}); + +test('the rule step opens the automations tab and asks it to show the rule', async () => { + const notices = [{ id: 'effect:r1', source: 'effect', severity: 'info', code: 'effect.ok', params: { rule: 'R' }, steps: [{ code: 'rule_open', target: 'rule', ids: ['r1'] }], first_seen: NOW, ack: null }]; + const { component, window } = createPanel({ roles: ['view_automations'], notices }); + await component.load(); + const seen = []; + const tab = window.document.createElement('button'); + tab.setAttribute('role', 'tab'); + tab.setAttribute('aria-controls', 'automations-panel'); + tab.addEventListener('click', () => seen.push('tab')); + window.document.body.appendChild(tab); + window.addEventListener('automation-focus-rule', (event) => seen.push('rule ' + event.detail.id)); + component.runStep(component.notices[0], 0); + assert.deepEqual(seen, ['tab', 'rule r1']); + assert.equal(window.__automationFocusRequest__, 'r1'); +}); diff --git a/docs/dashboard/automations-learning.md b/docs/dashboard/automations-learning.md index dd3c11a6..95abfc8c 100644 --- a/docs/dashboard/automations-learning.md +++ b/docs/dashboard/automations-learning.md @@ -124,14 +124,14 @@ value has these parts: The rule card shows the current value, its bounds and how the value moved over the year, with the high and the low and the months they fell in. -## Effect and season drift +## Results check and season drift Once you adopt a suggestion, the node measures what it changed. -### Effect +### Results check - The first effect appears in the first full calendar week after the change. - Until then the card says **Effect visible from** and a date. + Until then the mark on the rule says **Effect visible from** and a date. - The comparison uses up to four full weeks before the change as the baseline. At least two of them need data on five days. - Each week is measured in one unit. Device energy is shown in kWh per week, @@ -142,17 +142,19 @@ Once you adopt a suggestion, the node measures what it changed. instead, and the other suggestions use no season correction. The effect is then marked **Estimate**. Manual actions have no season correction and are therefore always an estimate. -- The card shows the value before the change and the value since, and the number - of times you overrode the rule by hand. -- While the rule carries the learned mark, the rule also shows an info mark with - the effect. -- After **Delete learned data** the card of an adopted rule says **No comparison +- The result shows the value before the change and the value since, and the + number of times you overrode the rule by hand. +- Every rule and scenario that came from a suggestion shows an info mark with its + result. +- After **Delete learned data** the mark of an adopted rule says **No comparison data**, because the days before the change are gone. -- When the range of the effect includes zero, the card says **Not measurable +- When the range of the effect includes zero, the result says **Not measurable yet** instead of a number. This happens when the week varies more than the effect. -- The effect stays on the band for eight weeks after the change, or until you - press **Hide**, which dismisses it. +- [Monitoring](monitoring.md#notices) lists each measured result under **Results + check** for eight weeks after the change, with its confidence. **Acknowledge** + moves it to the acknowledged notices. A result is not a suggestion, so the + suggestion band does not show it. ### Season drift diff --git a/docs/dashboard/monitoring.md b/docs/dashboard/monitoring.md index ac637911..306cb943 100644 --- a/docs/dashboard/monitoring.md +++ b/docs/dashboard/monitoring.md @@ -5,11 +5,12 @@ title: "Monitoring" # Monitoring The **Monitoring** tab collects what the node wants you to look at. It shows -notices about the energy balance, the measurement chains and the learning -functions, it shows the forecast the node uses for the surplus, the comparison -with the previous year, and the values the system has learned. The tab sits -before [Diagnostics](diagnostics.md). It needs the permission `view_monitoring`, -see [Rights](#rights). While a notice is new, the tab shows a dot. +notices about the energy balance, the measurement chains, the learning functions +and the results of adopted suggestions. It also shows the forecast the node uses +for the surplus, the comparison with the previous year, and the values the system +has learned. The tab sits before [Diagnostics](diagnostics.md). It needs the +permission `view_monitoring`, see [Rights](#rights). While a notice is new, the +tab shows a dot. Diagnostics stays a separate tab. It covers devices, services and the broker. Monitoring covers the energy side and what the system has learned. @@ -21,14 +22,14 @@ described on one page, [Automations: Learning](automations-learning.md). The top left of the tab switches between **Notices**, **Learned values** and **Forecast**. The filter on the right limits the notices to **All**, **Energy**, -**Learning** or **Suggestions**. +**Learning**, **Suggestions** or **Results check**. The list has two groups, **New** and **Acknowledged**. Select a notice to see its card. The card has the text, the facts of the notice, the evidence if there is one, the recommended steps and the footer with the acknowledgement. On a narrow screen the card opens below the notice, and a second tap closes it again. -Notices come from four sources: +Notices come from five sources: | Source | Notices | |---|---| @@ -36,6 +37,7 @@ Notices come from four sources: | Measurement chains | A finding of a [measurement chain](energy.md#measurement-chains), such as a unit error, a frozen value, a contradiction or a sign error. The card shows the time since the finding started. | | Learning | A finding that belongs to no rule and to no suggestion, for example a fixed shade that reduces the PV power, a battery that is full early or empty before morning, or a rising base load without a switchable device. The card shows the direction and height of the shade, the calendar weeks, the loss per year and a daily curve. | | Suggestions | Every suggestion of the [suggestion band](automations-rules.md#suggestions). **Open suggestion** opens it on the Automations page. The chip **Suggestions** lists only these, **All** includes them. | +| Results check | The measured [result](automations-learning.md#results-check) of an adopted suggestion, with the value before and since and its confidence, for eight weeks after the change. **Open the rule** shows the rule or scenario on the Automations page. | Findings that belong to a rule stay on the rule card in [Automations](automations-rules.md). Findings with a suggestion to apply stay in @@ -62,6 +64,7 @@ a button leads to the place for it: - **Measurement chain** opens the dialog of the chain on the Energy tab. - **Efficiency** and **Device map** open their tabs. - **Learned values** switches the tab to the learned values. +- **Open the rule** shows the checked rule or scenario on the Automations page. A step that leads to a place you may not see is hidden, and its text stays. A shade notice names the direction and the height. It also says that nothing needs From 0f295106cdb64756039159861ba339dabadbd6f6 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 29 Nov 2026 18:35:59 +0000 Subject: [PATCH 33/34] chore(release): bump component versions --- dashboard/VERSION | 2 +- services/automation/manifest.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dashboard/VERSION b/dashboard/VERSION index 61e24d2f..4e86b954 100644 --- a/dashboard/VERSION +++ b/dashboard/VERSION @@ -1 +1 @@ -v0.11.22-pre.37 +v0.11.22-pre.38 diff --git a/services/automation/manifest.json b/services/automation/manifest.json index 247a4c54..55a2b0ac 100644 --- a/services/automation/manifest.json +++ b/services/automation/manifest.json @@ -1,6 +1,6 @@ { "service_id": "automation", - "version": "0.7.3-pre.7", + "version": "0.7.3-pre.8", "unit": "automation.service", "bootstrap_step": "88", "schema": "config.schema.json", From dcc66ee057db1fd4ea25334c0639b0476da00a8b Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 29 Nov 2026 18:36:51 +0000 Subject: [PATCH 34/34] docs(changelog): update changelogs --- changelog/highlights/300.json | 65 ++++++++++++++++++++++++++++++++ dashboard/CHANGELOG.md | 34 ++++++++++++++++- services/automation/CHANGELOG.md | 4 +- 3 files changed, 100 insertions(+), 3 deletions(-) create mode 100644 changelog/highlights/300.json diff --git a/changelog/highlights/300.json b/changelog/highlights/300.json new file mode 100644 index 00000000..ed85d8e3 --- /dev/null +++ b/changelog/highlights/300.json @@ -0,0 +1,65 @@ +{ + "de": { + "*": "Monitoring prüft, was übernommene Vorschläge bringen, Regeln melden einen Saisonwechsel" + }, + "en": { + "*": "Monitoring checks the results of adopted suggestions and rules report a season drift" + }, + "tour": { + "*": { + "steps": [ + { + "device": "any", + "need": "view_monitoring", + "open": [ + "monitoring-effect" + ], + "panel": "monitoring-panel", + "target": "monitoring-effect", + "text": { + "de": "Nach dem Übernehmen eines Vorschlags zeigt das Monitoring unter Erfolgskontrolle den Wert vorher und seitdem. Das beginnt nach der ersten vollen Woche.", + "en": "After you adopt a suggestion, Monitoring shows the value before and since under Results check. It appears after the first full week." + }, + "title": { + "de": "Erfolgskontrolle", + "en": "Results check" + } + }, + { + "device": "any", + "need": "view_automations", + "open": [ + "automations-rules" + ], + "panel": "automations-panel", + "target": "rule-effect", + "text": { + "de": "Die Regel trägt dasselbe Ergebnis. Wandern ihre Zeiten oder Werte mit der Jahreszeit, warnt die Marke und bietet eine Anpassung an.", + "en": "The rule carries the same result. When its times or values move with the season, the mark warns and offers an adjustment." + }, + "title": { + "de": "Die Marke an der Regel", + "en": "The mark on the rule" + } + }, + { + "device": "any", + "need": "view_monitoring", + "open": [ + "monitoring-learned" + ], + "panel": "monitoring-panel", + "target": "monitoring-learned", + "text": { + "de": "Das Monitoring listet, was der Node gelernt hat. Regeln können diese Werte nutzen.", + "en": "Monitoring lists what the node has learned. Rules can use these values." + }, + "title": { + "de": "Lernwerte", + "en": "Learned values" + } + } + ] + } + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index 5a8511ba..c3446ba2 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.11.22-pre.37 (2026-11-06) +## v0.11.22-pre.38 (2026-11-06) ### Features @@ -36,10 +36,23 @@ - **autolearn:** Automation suggestions for surplus and load shifts are checked against your data (#295) (6c255ad) - **autolearn:** Learning functions can take minute values from Home Assistant (#294) (7aa657e) - **monitoring:** Monitoring shows the forecast check, a year comparison and the learned values as a usual day (#297) (4f93975) +- **dashboard:** show system versions on the versions page (#299) (18a2b0b) +- **automations:** mark rules that came from a learned suggestion (f85130f) +- **webui:** record which suggestion a saved rule came from (ae2baed) +- **autolearn:** measure the effect of an adopted suggestion against the season (a1e9dc6) +- **autolearn:** keep the effect of adopted rules in a store (f0d3d9e) +- **autolearn:** show the effect of adopted suggestions on the rule and in the band (d024c0d) +- **autolearn:** report when an adopted suggestion drifts with the season (479c125) +- **webui:** show the effect of adopted suggestions in the band (85a5fed) +- **webui:** show the effect and season drift of adopted suggestions (a71c920) +- **demo:** show an effect and a season drift (71ee735) +- **demo:** show every effect state and drift kind (c3e766b) +- **webui:** let a tour expand the suggestions band (fa55c0a) +- **monitoring:** check the results of adopted suggestions in Monitoring (f4755bb) +- **automations:** Monitoring checks the results of adopted suggestions and rules report a season drift (#300) - **dashboard:** read the system package versions (8d025b3) - **dashboard:** serve system versions to setup users (8e71270) - **dashboard:** show the kernel and the Debian point release (93d002d) -- **dashboard:** show system versions on the versions page (#299) - **autolearn:** expose forecast days and the rules that read a learned value (25d731e) - **demo:** seed a forecast check and a year of season weeks (4a39a77) - **monitoring:** serve the forecast check and the season weeks from the api (d11383f) @@ -354,6 +367,21 @@ - **storage:** wipe old file system signatures before formatting a stick (#245) (aeafa63) - **storage:** set up, back up and replug the additional drive reliably (#247) (b668394) - **automations:** correct the learning feature after the full review (#296) (88f3c75) +- **webui:** mark rules adopted from the suggestions band (6e20041) +- **autolearn:** accept baseline weeks with five days of data (fbbda8c) +- **autolearn:** keep the comparison values when a drifted rule is replaced (a95dcb5) +- **webui:** show the assistant for a drift fix and fit the effect card (fdb5ff8) +- **autolearn:** compare only values that drift with the season (51a586e) +- **backup:** include the measured effects in the backup (7aa2448) +- **autolearn:** show only the override count without a measure (b591b99) +- **autolearn:** keep rating a surplus window after its rule was adopted (cfc5906) +- **autolearn:** judge the season drift only after a complete daily round (573643f) +- **demo:** keep every effect state visible on any day (65558cd) +- **webui:** write the drift scale axes in the number format of the page (43f4528) +- **webui:** name the scenario in the surplus window drift (e41a11d) +- **demo:** adopt the surplus window as a scenario and count one effect in hand switches (49a32f9) +- **webui:** fit the effect axis on phones and say what a threshold fix does (0b4bef6) +- **webui:** label only the ends of the before and since axis (222cf12) - **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **monitoring:** keep texts and locale out of the insight model (57e2a44) - **monitoring:** show the legend items for statistics weeks and gaps (82cde6e) @@ -518,6 +546,7 @@ ### Tests +- **demo:** expect a sure effect beside the estimates (aa987aa) - **demo:** fake the system packages for the versions page (ca2dc1e) - **autolearn:** keep the cycle test window open until today (ab438d5) - **webui:** follow the template cache-bust mark (c30a3db) @@ -541,6 +570,7 @@ ### Chores +- **webui:** bump the cache marks of the changed automation assets (fa93e53) - **dashboard:** bump the cache-bust marks for the system card (31ecbb8) - **dashboard:** move the cache history rows to the current pre-release (8a60da5) - **monitoring:** drop the texts of the old learned values list (d6da484) diff --git a/services/automation/CHANGELOG.md b/services/automation/CHANGELOG.md index d27e4532..1314300b 100644 --- a/services/automation/CHANGELOG.md +++ b/services/automation/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.7.3-pre.7 (2026-11-23) +## v0.7.3-pre.8 (2026-11-29) ### Features @@ -10,6 +10,8 @@ - **automations:** Rules can follow learned values with bounds and react to a quiet or active house (#284) (8aae55b) - **autolearn:** The node records minute values and keeps every regulator step as a base for learning (#293) (19e65e7) - **autolearn:** Automation suggestions for surplus and load shifts are checked against your data (#295) (6c255ad) +- **automations:** mark rules that came from a learned suggestion (f85130f) +- **automations:** Monitoring checks the results of adopted suggestions and rules report a season drift (#300) - **automation:** compare a learned number in a condition (service) (9f690c9) - **automation:** publish every regulator step of a scenario (b82ff94) - **automation:** resolve learned values with bounds and a fallback (1049a08)