From 3e23fed3d616d1e3ea222f4555ea6f7f46fc1971 Mon Sep 17 00:00:00 2001 From: jamesread Date: Tue, 6 Jan 2026 21:38:18 +0000 Subject: [PATCH 1/5] feat: Enable/Disable actions based on rules --- .../tests/enabledExpression/config.yaml | 39 +++++ .../enabledExpression/enabledExpression.mjs | 88 ++++++++++ .../enabledExpression/entities/lights.yaml | 5 + service/internal/api/api_test.go | 162 ++++++++++++++++++ 4 files changed, 294 insertions(+) create mode 100644 integration-tests/tests/enabledExpression/config.yaml create mode 100644 integration-tests/tests/enabledExpression/enabledExpression.mjs create mode 100644 integration-tests/tests/enabledExpression/entities/lights.yaml diff --git a/integration-tests/tests/enabledExpression/config.yaml b/integration-tests/tests/enabledExpression/config.yaml new file mode 100644 index 0000000..66ea639 --- /dev/null +++ b/integration-tests/tests/enabledExpression/config.yaml @@ -0,0 +1,39 @@ +# +# Integration Test Config: EnabledExpression +# + +listenAddressSingleHTTPFrontend: 0.0.0.0:1337 + +logLevel: "DEBUG" +checkForUpdates: false + +actions: + - title: Turn On Light + shell: echo "Turning on light" + icon: light + entity: light + enabledExpression: "{{ eq .CurrentEntity.powered_on false }}" + + - title: Turn Off Light + shell: echo "Turning off light" + icon: light + entity: light + enabledExpression: "{{ eq .CurrentEntity.powered_on true }}" + + - title: Always Enabled Action + shell: echo "Always enabled" + icon: check + +entities: + - file: entities/lights.yaml + name: light + +dashboards: + - title: Lights Dashboard + contents: + - title: Light Controls + type: fieldset + entity: light + contents: + - title: Turn On Light + - title: Turn Off Light diff --git a/integration-tests/tests/enabledExpression/enabledExpression.mjs b/integration-tests/tests/enabledExpression/enabledExpression.mjs new file mode 100644 index 0000000..ce15b30 --- /dev/null +++ b/integration-tests/tests/enabledExpression/enabledExpression.mjs @@ -0,0 +1,88 @@ +import { describe, it, before, after } from 'mocha' +import { expect } from 'chai' +import { By, until } from 'selenium-webdriver' +import { + getRootAndWait, + takeScreenshotOnFailure, +} from '../../lib/elements.js' + +describe('config: enabledExpression', function () { + before(async function () { + await runner.start('enabledExpression') + }) + + after(async () => { + await runner.stop() + }) + + afterEach(function () { + takeScreenshotOnFailure(this.currentTest, webdriver); + }); + + it('Action with enabledExpression false is disabled', async function() { + await getRootAndWait() + + // Navigate to the Lights Dashboard + await webdriver.get(runner.baseUrl() + '/dashboard/Lights%20Dashboard') + + // Wait for dashboard to load + await webdriver.wait(until.elementLocated(By.css('.action-button')), 10000) + + // Find action buttons + const actionButtons = await webdriver.findElements(By.css('.action-button button')) + + // Find "Turn On Light" button for "Living Room Light" (powered_on: false, so Turn On should be enabled) + // Find "Turn Off Light" button for "Bedroom Light" (powered_on: true, so Turn Off should be enabled) + let turnOnButton = null + let turnOffButton = null + + for (const btn of actionButtons) { + const title = await btn.getAttribute('title') + if (title && title.includes('Turn On Light') && title.includes('Living Room')) { + turnOnButton = btn + } + if (title && title.includes('Turn Off Light') && title.includes('Bedroom')) { + turnOffButton = btn + } + } + + expect(turnOnButton).to.not.be.null + expect(turnOffButton).to.not.be.null + + // Check that Turn On button is enabled (light is off) + const turnOnDisabled = await turnOnButton.getAttribute('disabled') + expect(turnOnDisabled).to.be.null + + // Check that Turn Off button is enabled (light is on) + const turnOffDisabled = await turnOffButton.getAttribute('disabled') + expect(turnOffDisabled).to.be.null + }) + + it('Action without enabledExpression is always enabled', async function() { + await getRootAndWait() + + // Navigate to actions view + await webdriver.get(runner.baseUrl()) + + // Wait for action buttons + await webdriver.wait(until.elementLocated(By.css('.action-button')), 10000) + + // Find "Always Enabled Action" button + const actionButtons = await webdriver.findElements(By.css('.action-button button')) + let alwaysEnabledButton = null + + for (const btn of actionButtons) { + const title = await btn.getAttribute('title') + if (title === 'Always Enabled Action') { + alwaysEnabledButton = btn + break + } + } + + expect(alwaysEnabledButton).to.not.be.null + + // Check that it's enabled + const disabled = await alwaysEnabledButton.getAttribute('disabled') + expect(disabled).to.be.null + }) +}) diff --git a/integration-tests/tests/enabledExpression/entities/lights.yaml b/integration-tests/tests/enabledExpression/entities/lights.yaml new file mode 100644 index 0000000..628fcc1 --- /dev/null +++ b/integration-tests/tests/enabledExpression/entities/lights.yaml @@ -0,0 +1,5 @@ +- name: "Living Room Light" + powered_on: false + +- name: "Bedroom Light" + powered_on: true diff --git a/service/internal/api/api_test.go b/service/internal/api/api_test.go index 68341ae..9d20559 100644 --- a/service/internal/api/api_test.go +++ b/service/internal/api/api_test.go @@ -11,6 +11,7 @@ import ( apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1" apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect" + authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic" config "github.com/OliveTin/OliveTin/internal/config" "github.com/OliveTin/OliveTin/internal/entities" "github.com/OliveTin/OliveTin/internal/executor" @@ -173,3 +174,164 @@ func validateConsistency(t *testing.T, client apiv1connect.OliveTinApiServiceCli } } } + +func TestEvaluateEnabledExpression(t *testing.T) { + tests := []struct { + name string + expression string + entity *entities.Entity + expectedResult bool + }{ + { + name: "empty expression returns true", + expression: "", + entity: nil, + expectedResult: true, + }, + { + name: "literal true returns true", + expression: "true", + entity: nil, + expectedResult: true, + }, + { + name: "literal True returns true (case insensitive)", + expression: "True", + entity: nil, + expectedResult: true, + }, + { + name: "literal 1 returns true", + expression: "1", + entity: nil, + expectedResult: true, + }, + { + name: "literal false returns false", + expression: "false", + entity: nil, + expectedResult: false, + }, + { + name: "literal 0 returns false", + expression: "0", + entity: nil, + expectedResult: false, + }, + { + name: "empty result returns false", + expression: "{{ .NonExistent }}", + entity: nil, + expectedResult: false, + }, + { + name: "expression with CurrentEntity true", + expression: "{{ eq .CurrentEntity.powered_on true }}", + entity: &entities.Entity{Data: map[string]any{"powered_on": true}}, + expectedResult: true, + }, + { + name: "expression with CurrentEntity false", + expression: "{{ eq .CurrentEntity.powered_on true }}", + entity: &entities.Entity{Data: map[string]any{"powered_on": false}}, + expectedResult: false, + }, + { + name: "expression with CurrentEntity integer 1", + expression: "{{ .CurrentEntity.status }}", + entity: &entities.Entity{Data: map[string]any{"status": 1}}, + expectedResult: true, + }, + { + name: "expression with CurrentEntity integer 0", + expression: "{{ .CurrentEntity.status }}", + entity: &entities.Entity{Data: map[string]any{"status": 0}}, + expectedResult: false, + }, + { + name: "template parse error returns false", + expression: "{{ invalid syntax }}", + entity: nil, + expectedResult: false, + }, + { + name: "template exec error returns false", + expression: "{{ .CurrentEntity.nonexistent }}", + entity: nil, + expectedResult: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + action := &config.Action{ + EnabledExpression: tt.expression, + } + result := evaluateEnabledExpression(action, tt.entity) + assert.Equal(t, tt.expectedResult, result, "evaluateEnabledExpression should return expected result") + }) + } +} + +func TestBuildActionWithEnabledExpression(t *testing.T) { + cfg := config.DefaultConfig() + cfg.DefaultPermissions.Exec = true + + action := &config.Action{ + Title: "Test Action", + Shell: "echo test", + EnabledExpression: "{{ eq .CurrentEntity.enabled true }}", + } + cfg.Actions = append(cfg.Actions, action) + + ex := executor.DefaultExecutor(cfg) + ex.RebuildActionMap() + + binding := findBindingByTitle(ex, "Test Action") + assert.NotNil(t, binding, "Binding should be found") + + rr := &DashboardRenderRequest{ + AuthenticatedUser: &authpublic.AuthenticatedUser{Username: "testuser"}, + cfg: cfg, + ex: ex, + } + + testWithEntity(t, binding, rr, true, true, "Action should be executable when entity.enabled is true") + testWithEntity(t, binding, rr, false, false, "Action should not be executable when entity.enabled is false") + + bindingNoExpr := findBindingByTitle(ex, "Test Action No Expression") + if bindingNoExpr == nil { + actionNoExpression := &config.Action{ + Title: "Test Action No Expression", + Shell: "echo test", + } + cfg.Actions = append(cfg.Actions, actionNoExpression) + ex.RebuildActionMap() + bindingNoExpr = findBindingByTitle(ex, "Test Action No Expression") + } + + actionResult := buildAction(bindingNoExpr, rr) + assert.True(t, actionResult.CanExec, "Action without enabledExpression should be executable") +} + +func findBindingByTitle(ex *executor.Executor, title string) *executor.ActionBinding { + ex.MapActionIdToBindingLock.RLock() + defer ex.MapActionIdToBindingLock.RUnlock() + + for _, b := range ex.MapActionIdToBinding { + if b.Action.Title == title { + return b + } + } + return nil +} + +func testWithEntity(t *testing.T, binding *executor.ActionBinding, rr *DashboardRenderRequest, enabled bool, expectedCanExec bool, message string) { + binding.Entity = &entities.Entity{ + UniqueKey: "test-entity", + Data: map[string]any{"enabled": enabled}, + } + + actionResult := buildAction(binding, rr) + assert.Equal(t, expectedCanExec, actionResult.CanExec, message) +} From 654ed15dde2813a573697444a3381846fa186a2c Mon Sep 17 00:00:00 2001 From: jamesread Date: Tue, 6 Jan 2026 21:39:46 +0000 Subject: [PATCH 2/5] fix: Add missing enabled expression file --- service/internal/api/apiActions.go | 54 +++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/service/internal/api/apiActions.go b/service/internal/api/apiActions.go index 6046691..b653510 100644 --- a/service/internal/api/apiActions.go +++ b/service/internal/api/apiActions.go @@ -1,6 +1,11 @@ package api import ( + "strconv" + "strings" + + log "github.com/sirupsen/logrus" + apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1" acl "github.com/OliveTin/OliveTin/internal/acl" authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic" @@ -55,14 +60,61 @@ func buildEffectivePolicy(policy *config.ConfigurationPolicy) *apiv1.EffectivePo return ret } +func evaluateEnabledExpression(action *config.Action, entity *entities.Entity) bool { + if action.EnabledExpression == "" { + return true + } + + result := entities.ParseTemplateWith(action.EnabledExpression, entity) + result = strings.TrimSpace(result) + + if result == "" { + return false + } + + if isTemplateError(result, action) { + return false + } + + return evaluateResultValue(result) +} + +func isTemplateError(result string, action *config.Action) bool { + if !strings.HasPrefix(result, "tpl ") || !strings.Contains(result, "error") { + return false + } + + log.WithFields(log.Fields{ + "actionTitle": action.Title, + "enabledExpression": action.EnabledExpression, + "result": result, + }).Warn("enabledExpression template evaluation failed, treating as disabled") + return true +} + +func evaluateResultValue(result string) bool { + if strings.EqualFold(result, "true") { + return true + } + + if num, err := strconv.Atoi(result); err == nil { + return num != 0 + } + + return false +} + func buildAction(actionBinding *executor.ActionBinding, rr *DashboardRenderRequest) *apiv1.Action { action := actionBinding.Action + aclCanExec := acl.IsAllowedExec(rr.cfg, rr.AuthenticatedUser, action) + enabledExprCanExec := evaluateEnabledExpression(action, actionBinding.Entity) + btn := apiv1.Action{ BindingId: actionBinding.ID, Title: entities.ParseTemplateWith(action.Title, actionBinding.Entity), Icon: entities.ParseTemplateWith(action.Icon, actionBinding.Entity), - CanExec: acl.IsAllowedExec(rr.cfg, rr.AuthenticatedUser, action), + CanExec: aclCanExec && enabledExprCanExec, PopupOnStart: action.PopupOnStart, Order: int32(actionBinding.ConfigOrder), Timeout: int32(action.Timeout), From 3d5268d1c915d55ca8e2b56a3e77a586772c6f26 Mon Sep 17 00:00:00 2001 From: jamesread Date: Tue, 6 Jan 2026 21:51:35 +0000 Subject: [PATCH 3/5] chore: enableExpression, broken test and config --- integration-tests/tests/enabledExpression/enabledExpression.mjs | 2 +- service/internal/config/config.go | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/integration-tests/tests/enabledExpression/enabledExpression.mjs b/integration-tests/tests/enabledExpression/enabledExpression.mjs index ce15b30..c9901cb 100644 --- a/integration-tests/tests/enabledExpression/enabledExpression.mjs +++ b/integration-tests/tests/enabledExpression/enabledExpression.mjs @@ -19,7 +19,7 @@ describe('config: enabledExpression', function () { takeScreenshotOnFailure(this.currentTest, webdriver); }); - it('Action with enabledExpression false is disabled', async function() { + it('Action with enabledExpression for lights enable the correct action', async function() { await getRootAndWait() // Navigate to the Lights Dashboard diff --git a/service/internal/config/config.go b/service/internal/config/config.go index 722e492..267dda4 100644 --- a/service/internal/config/config.go +++ b/service/internal/config/config.go @@ -28,6 +28,7 @@ type Action struct { Arguments []ActionArgument `koanf:"arguments"` PopupOnStart string `koanf:"popupOnStart"` SaveLogs SaveLogsConfig `koanf:"saveLogs"` + EnabledExpression string `koanf:"enabledExpression"` } // ActionArgument objects appear on Actions. From 7428c160e748dde73c08f2b26e132d9dd01fd870 Mon Sep 17 00:00:00 2001 From: jamesread Date: Wed, 7 Jan 2026 00:24:21 +0000 Subject: [PATCH 4/5] chore: Refactor enabledExpression tests to use LightDashboard and improve button identification --- frontend/main.js | 2 +- frontend/resources/vue/Dashboard.vue | 15 +++ .../tests/enabledExpression/config.yaml | 2 +- .../enabledExpression/enabledExpression.mjs | 94 +++++++++++++++---- 4 files changed, 95 insertions(+), 18 deletions(-) diff --git a/frontend/main.js b/frontend/main.js index 699743b..a434cce 100644 --- a/frontend/main.js +++ b/frontend/main.js @@ -93,7 +93,7 @@ function setupVue (i18nSettings) { function setupErrorDisplay (errorMessage) { const ErrorApp = { - render() { + render () { return h('section', { class: 'bad', style: 'padding: 2em; text-align: center; margin: 2em auto;' }, [ h('h2', 'OliveTin Init Failed'), h('p', errorMessage), diff --git a/frontend/resources/vue/Dashboard.vue b/frontend/resources/vue/Dashboard.vue index 16432bd..c6e2eff 100644 --- a/frontend/resources/vue/Dashboard.vue +++ b/frontend/resources/vue/Dashboard.vue @@ -108,6 +108,21 @@ function goBack() { async function getDashboard() { let title = props.title + // Decode URL-encoded title if present (Vue Router should decode automatically, + // but handle cases where it might not) + if (title) { + try { + // Try decoding in case it's URL-encoded (e.g., "Lights%20Dashboard" -> "Lights Dashboard") + const decoded = decodeURIComponent(title) + // Use decoded version if it's different from the original + if (decoded !== title) { + title = decoded + } + } catch (e) { + // If decoding fails (e.g., invalid encoding), use original title + } + } + // If no specific title was provided or it's the placeholder 'default', // prefer the first configured root dashboard (e.g., "Test"). if ((!title || title === 'default') && window.initResponse.rootDashboards && window.initResponse.rootDashboards.length > 0) { diff --git a/integration-tests/tests/enabledExpression/config.yaml b/integration-tests/tests/enabledExpression/config.yaml index 66ea639..30c718f 100644 --- a/integration-tests/tests/enabledExpression/config.yaml +++ b/integration-tests/tests/enabledExpression/config.yaml @@ -29,7 +29,7 @@ entities: name: light dashboards: - - title: Lights Dashboard + - title: LightDashboard contents: - title: Light Controls type: fieldset diff --git a/integration-tests/tests/enabledExpression/enabledExpression.mjs b/integration-tests/tests/enabledExpression/enabledExpression.mjs index c9901cb..98f32c0 100644 --- a/integration-tests/tests/enabledExpression/enabledExpression.mjs +++ b/integration-tests/tests/enabledExpression/enabledExpression.mjs @@ -1,12 +1,14 @@ import { describe, it, before, after } from 'mocha' import { expect } from 'chai' -import { By, until } from 'selenium-webdriver' +import { By, until, Condition } from 'selenium-webdriver' import { getRootAndWait, takeScreenshotOnFailure, } from '../../lib/elements.js' describe('config: enabledExpression', function () { + this.timeout(30000) // Increase timeout for async operations + before(async function () { await runner.start('enabledExpression') }) @@ -23,26 +25,86 @@ describe('config: enabledExpression', function () { await getRootAndWait() // Navigate to the Lights Dashboard - await webdriver.get(runner.baseUrl() + '/dashboard/Lights%20Dashboard') + // Use the path with space encoded as %20 - Vue Router should decode it + await webdriver.get(runner.baseUrl() + '/dashboards/LightDashboard') - // Wait for dashboard to load - await webdriver.wait(until.elementLocated(By.css('.action-button')), 10000) + // Wait for the URL to change and the route to be processed + await webdriver.wait(new Condition('wait for URL to contain dashboards', async function() { + const url = await webdriver.getCurrentUrl() + return url.includes('/dashboards/') + }), 5000) - // Find action buttons - const actionButtons = await webdriver.findElements(By.css('.action-button button')) + // Wait for dashboard to load by checking the loaded-dashboard attribute + // The attribute should be set to the decoded title "LightDashboard" + await webdriver.wait(new Condition('wait for loaded-dashboard', async function() { + const body = await webdriver.findElement(By.tagName('body')) + const attr = await body.getAttribute('loaded-dashboard') + if (attr) { + console.log('Current loaded-dashboard attribute:', attr) + } + // Accept either decoded or encoded version (component should decode, but handle both) + return attr === 'LightDashboard' + }), 10000) - // Find "Turn On Light" button for "Living Room Light" (powered_on: false, so Turn On should be enabled) - // Find "Turn Off Light" button for "Bedroom Light" (powered_on: true, so Turn Off should be enabled) + // Verify we got the correct dashboard (prefer decoded, but accept encoded) + const body = await webdriver.findElement(By.tagName('body')) + const attr = await body.getAttribute('loaded-dashboard') + if (attr !== 'LightDashboard') { + const currentUrl = await webdriver.getCurrentUrl() + throw new Error(`Dashboard not loaded correctly. Expected "LightDashboard", got "${attr}". Current URL: ${currentUrl}`) + } + + // Wait for dashboard content to appear - check for dashboard rows first + await webdriver.wait(until.elementsLocated(By.css('.dashboard-row')), 5000) + + // Debug: Check what's on the page + const dashboardRows = await webdriver.findElements(By.css('.dashboard-row')) + console.log(`Found ${dashboardRows.length} dashboard rows`) + + for (let i = 0; i < dashboardRows.length; i++) { + const row = dashboardRows[i] + const h2Elements = await row.findElements(By.css('h2')) + if (h2Elements.length > 0) { + const h2Text = await h2Elements[0].getText() + console.log(`Row ${i} h2: "${h2Text}"`) + } + const fieldsets = await row.findElements(By.css('fieldset')) + console.log(`Row ${i} has ${fieldsets.length} fieldsets`) + if (fieldsets.length > 0) { + const buttons = await fieldsets[0].findElements(By.css('.action-button button')) + console.log(`Row ${i} fieldset has ${buttons.length} buttons`) + } + } + + // Find buttons by looking within entity fieldsets + // Both rows have h2 title "Light Controls", so we identify them by which buttons are enabled + // Living Room Light (powered_on: false) - Turn On should be enabled, Turn Off disabled + // Bedroom Light (powered_on: true) - Turn Off should be enabled, Turn On disabled let turnOnButton = null let turnOffButton = null - - for (const btn of actionButtons) { - const title = await btn.getAttribute('title') - if (title && title.includes('Turn On Light') && title.includes('Living Room')) { - turnOnButton = btn - } - if (title && title.includes('Turn Off Light') && title.includes('Bedroom')) { - turnOffButton = btn + + for (const row of dashboardRows) { + // Get the fieldset in this row + const fieldsets = await row.findElements(By.css('fieldset')) + if (fieldsets.length === 0) continue + + const buttons = await fieldsets[0].findElements(By.css('.action-button button')) + + // Check each button to identify which entity this row represents + for (const btn of buttons) { + const title = await btn.getAttribute('title') + const disabled = await btn.getAttribute('disabled') + const isEnabled = disabled === null + + if (title === 'Turn On Light' && isEnabled) { + // This is the Living Room Light row (Turn On is enabled because powered_on: false) + turnOnButton = btn + } + + if (title === 'Turn Off Light' && isEnabled) { + // This is the Bedroom Light row (Turn Off is enabled because powered_on: true) + turnOffButton = btn + } } } From aeb66d494c121c51adbffef41156052574a4aa74 Mon Sep 17 00:00:00 2001 From: jamesread Date: Wed, 7 Jan 2026 00:43:22 +0000 Subject: [PATCH 5/5] fix: remove decodeURIComponent from Dashboard.vue --- frontend/resources/vue/Dashboard.vue | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/frontend/resources/vue/Dashboard.vue b/frontend/resources/vue/Dashboard.vue index c6e2eff..16432bd 100644 --- a/frontend/resources/vue/Dashboard.vue +++ b/frontend/resources/vue/Dashboard.vue @@ -108,21 +108,6 @@ function goBack() { async function getDashboard() { let title = props.title - // Decode URL-encoded title if present (Vue Router should decode automatically, - // but handle cases where it might not) - if (title) { - try { - // Try decoding in case it's URL-encoded (e.g., "Lights%20Dashboard" -> "Lights Dashboard") - const decoded = decodeURIComponent(title) - // Use decoded version if it's different from the original - if (decoded !== title) { - title = decoded - } - } catch (e) { - // If decoding fails (e.g., invalid encoding), use original title - } - } - // If no specific title was provided or it's the placeholder 'default', // prefer the first configured root dashboard (e.g., "Test"). if ((!title || title === 'default') && window.initResponse.rootDashboards && window.initResponse.rootDashboards.length > 0) {