From 9b1b0ca9f80bd48500ffc43c52fc4a446d2420aa Mon Sep 17 00:00:00 2001 From: "copilot-action[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:39:46 +0100 Subject: [PATCH 1/6] docs(sdd): specify issue contract in specs/household-automation.md --- specs/household-automation.md | 214 ++++++++++++++++++++++++++++++++++ 1 file changed, 214 insertions(+) diff --git a/specs/household-automation.md b/specs/household-automation.md index 9c0ac6bf..46340971 100644 --- a/specs/household-automation.md +++ b/specs/household-automation.md @@ -842,3 +842,217 @@ Reuse the rule model, saved revision, authorization boundary, and draft lifecycl ### 20. References and decisions [Domus #120](https://github.com/vypdev/domus/issues/120) supplies the manual-run delta. Retain the existing rule, preview, and draft contract and cases in `specs/household-automation.md`; this update adds manual enablement and execution while preserving that owner's boundaries. [Domus #118](https://github.com/vypdev/domus/issues/118) defines the saved-draft increment on which exact-revision enablement depends. The selected source revision is `54b20736fe41cdc36d0f431edd56ca72234ddd52`. The repository standard is in `specs/README.md`, and the selected root `package.json` declares pnpm 10.34.0 and Node `>=24.20.0 <25`; its scripts do not include the specification validation or generation invocations named by the standard. Their concrete invocation and prerequisite remain unverified. + +## Review previous manual automation runs + +- Status: Draft +- Date: 2026-11-18 +- Catalog capability ID: household-automation +- Owners: Domus maintainers +- Scope: Protected history of the invoking member's explicit manual runs for one saved rule +- Related issue: [Domus #122](https://github.com/vypdev/domus/issues/122) +- Required review gates: product UX, architecture, testing, documentation, security/operations +- Open decisions blocking readiness: none in this increment + +### 1. Executive summary + +A currently authorized member can select a saved automation rule and review the +original outcomes of their manual runs. Each result preserves the committed +time, admitted revision, stock decision and whether a task was created. + +### 2. Problem, current behavior, and evidence + +[Domus #120](https://github.com/vypdev/domus/issues/120) records each explicit run +with its exact rule and control revisions, immutable stock decision and the +ordinary Task receipt when applicable. The original request route recovers a +particular submission, but users cannot find previous runs from Household +settings. The selected owner at `1af12f3f2ecb1c6848f843808569e5ea3ba8da5a` is +`specs/household-automation.md`. The existing qualification is recorded in +`docs/evidence/automation-execution-qualification.md`. + +### 3. Actors, surfaces, and terminology + +| Actor | Goal | Entry point | Visible surface | +| --- | --- | --- | --- | +| Current authorized invoking member | Review their past manual run and find the task when still accessible | Selected saved rule in Household settings | Protected run history | +| Member without current manual access | Continue to other allowed household views | Household settings | Permission feedback without private outcomes | + +A current result belongs to the active database generation. A historical result +is the original evidence for a command retained across restoration. The +original stock decision does not change when the rule or inventory changes. + +### 4. Goals, non-goals, and fixed invariants + +| Requirement | Behavior | +| --- | --- | +| manual-run-history-R01 | List only the currently authorized caller's manual runs for the selected saved rule. Recheck current access on every page and clear displayed details when scope changes. | +| manual-run-history-R02 | Show recent results first from a bounded page. Use the existing signed five-minute cursor bound to installation, channel, household, member, rule and page size. Start again at the latest page after cursor expiry or key rotation. | +| manual-run-history-R03 | Show authoritative committed time, exact admitted revision and original stock and task decision. Editing and disabling the rule leave prior receipts untouched. | +| manual-run-history-R04 | Show retained restored results distinctly. Link the original task only when the result and task are current and the caller has task read access. | +| manual-run-history-R05 | Provide accessible English and Spanish history, empty, failure and recovery states for keyboard and touch. | +| manual-run-history-R06 | Verify the read through both HTTP compositions, both image architectures and an exact separately installed Edge candidate. Preserve existing records and clean disposable evidence. | + +The view performs no run, task, inventory or auxiliary writes. Scheduling, +event triggers, retention policy, additional execution steps and notification +effects have separate acceptance. + +### 5. Current versus proposed product journey + +| Stage | Current | Proposed | User effect | +| --- | --- | --- | --- | +| Reopen | Select the saved rule and view its execution control | Open the history beside the execution controls | Review recent runs by their saved revision | +| Inspect | The last result or original request is required | Read the immutable stock decision and task outcome | See what actually happened in that earlier run | +| Continue | Earlier requests are difficult to locate | Request older results or return to recent runs | Navigate the list without unbounded data | +| Follow up | A current receipt can link to its task | Open that exact task from the corresponding current result | Confirm the resulting work | + +### 6. Functional behavior and state model + +Resolve the installation, channel, household and authenticated member in the +current protected context. Verify automation and task creation permissions as +in the manual run access path, and require the selected saved rule. Query that +member's original receipts only, including retained receipts in chronological +commit order. Return each operation once. Retained projections of live results +do not duplicate the live record. + +Use a default limit of 25 and accept limits from 1 to 100. Use a single +lookahead result to decide whether to issue the next cursor. The next request +checks authority and cursor binding again. Revoked authority or different +household, member or rule never reveals previous entries. Disabled rules retain +their earlier outcomes. + +### 7. User-facing configuration + +Use the current English or Spanish language and the household's existing time +context. There is no additional installation setting. Older results are +requested on demand and the view can return to recent results. + +### 8. Clean Architecture design + +Reuse the application authority for manual automation and the stored receipt +and restoration semantics. SQLite performs bounded, scoped keyset reads in +the current transaction. The application maps stored original facts to the +narrow history contract and resolves current task access. Both HTTP entry +points share the protected route. Frontend adapters validate the history +response and settle requests only for the current application scope. Compose +the localized controls from the already published ha-ui components. + +### 9. UI/UX and content contract + +In Household settings, expose run history for the selected saved rule. Show each +result's recorded time, revision and task outcome. Identify a restored historical +result with readable text. If a current task is available, link to that exact +task. Show explicit empty, loading, temporary failure and expired-page states +with a clear recovery control. Provide readable narrow layout, keyboard focus +and accessible touch controls in English and Spanish. + +### 10. Failure, recovery, and cleanup + +Retain the successfully read page during a temporary pagination failure and allow +the same cursor to retry. After a cursor expires or loses its process signing key, +allow the member to return to the recent page. Retire old details when the +selected scope changes or access is revoked. A failed read cannot change any +record. Remove only the synthetic data, temporary app and source created during +installed qualification. + +### 11. Security, permissions, and privacy + +Both reads and continuations resolve the current member from proven context. +The original receipt must belong to that invoking member and selected rule. +A cursor does not grant authority. No result from another member, household, +installation or channel can be read through the new surface. Authorize the +task link separately with the owning Tasks access and require a current task. + +### 12. Observability and operational UX + +Use a sanitized operation reference for correlation with the original result. +Display authoritative current and historical outcomes in the user's language. +Expose safe status and recovery messages without logging private task names, +receipt payloads or credentials. + +### 13. Compatibility, migration, rollout, and rollback + +Reuse the existing run receipts and retained operation history. Read-only +implementation can remain compatible with the existing schema. If schema +changes become necessary, preserve representative schema 33 and schema 20 +through upgrade and verify rollback. Verify a real restored result, current +task visibility and restart. The installed version is a pinned Edge candidate +recorded with exact source and scoped cleanup. Stable distribution is outside +this validation. + +### 14. Testing strategy and numeric budget + +| Area | Minimum distinct cases | Behaviors/risks covered | +| --- | --- | --- | +| Authorization | 2 | Own member and rule boundaries, current revocation and task access | +| Pagination | 2 | Stable bounded order, stale or invalid cursor recovery | +| Committed evidence | 1 | Immutable outcomes and restart | +| Restored evidence | 1 | Current versus historical task link | +| Browser acceptance | 1 | English and Spanish keyboard and touch | +| Deployment acceptance | 1 | Both pinned images and installed Edge | +| Total | 8 | Independently observable cases | + +| Case ID | Area | Requirements | Scenario | +| --- | --- | --- | --- | +| manual-run-history-C01 | Authorization | manual-run-history-R01 | In a household with two authorized callers and two rules, show only the authenticated caller's previous manual runs for the selected rule. Include the empty case. | +| manual-run-history-C02 | Authorization | manual-run-history-R01, manual-run-history-R04 | Revoke manual automation access during pagination and verify later reads disclose no prior details. With manual access and no task read permission, show original task creation without a link. | +| manual-run-history-C03 | Pagination | manual-run-history-R02 | Start from the latest committed result, walk bounded pages and add a newer result between reads. Verify no duplicate operation and a fixed limit from one to 100. | +| manual-run-history-C04 | Pagination | manual-run-history-R02, manual-run-history-R05 | Reject copied cursors for another query scope, expired cursors and cursors whose signing key changed. Navigate back to the latest page. | +| manual-run-history-C05 | Committed evidence | manual-run-history-R03 | Record matching and nonmatching runs, edit and disable the rule, restart and compare exact results, revisions and original task decisions. | +| manual-run-history-C06 | Restored evidence | manual-run-history-R03, manual-run-history-R04 | Activate a backup with one present run and one later run preserved as history. Verify the later run remains listed once with its original outcome and no link, and that the current entry opens its exact authorized task. | +| manual-run-history-C07 | Browser acceptance | manual-run-history-R01, manual-run-history-R05 | In both HTTP compositions, exercise English keyboard and narrow Spanish touch history, recover a failed older-page request, and clear displayed outcomes after switching rules. | +| manual-run-history-C08 | Deployment acceptance | manual-run-history-R06 | Run the exact CI Check matrix on amd64 and aarch64 and verify the separately installed candidate's version, task and no-task history, link and cleanup in Home Assistant. | + +### 15. Documentation and discoverability + +| Path | Change | +| --- | --- | +| specs/household-automation.md | update | +| docs/roadmap.md | update | +| docs/user-guide.md | update | +| docs/contracts/household-api.openapi.json | update | +| docs/contracts/native-household-api.openapi.json | update | +| docs/evidence/automation-execution-qualification.md | reference | +| docs/evidence/automation-run-history-qualification.md | create | + +Keep the same capability and retain all existing case identities. + +### 16. Acceptance scenarios + +Exercise the eight distinct cases in section 14. Confirm that accessing the +history never creates an automation or task effect. Use the self-hosted CI +Check workflow's actual image matrix and the existing Chromium workspace +fixture with both deployments. Record the exact installed Edge source and +the scoped cleanup in the contributing pull request. + +### 17. Requirements traceability + +| Requirement | Cases | +| --- | --- | +| manual-run-history-R01 | manual-run-history-C01, manual-run-history-C02, manual-run-history-C07 | +| manual-run-history-R02 | manual-run-history-C03, manual-run-history-C04 | +| manual-run-history-R03 | manual-run-history-C05, manual-run-history-C06 | +| manual-run-history-R04 | manual-run-history-C02, manual-run-history-C06 | +| manual-run-history-R05 | manual-run-history-C04, manual-run-history-C07 | +| manual-run-history-R06 | manual-run-history-C08 | + +### 18. Implementation sequence + +Implement the scoped original-result read and current task link check. Add +the shared HTTP contract and localized controller and view. Qualify storage +restoration, boundaries, browser and image matrices. Install and verify the +pinned Edge candidate and record exact evidence. + +### 19. Definition of Done + +All eight acceptance cases and the existing regressions pass. The exact PR +revision passes coverage, architecture and both image jobs. The pinned Edge +candidate passes the real workflow with scoped cleanup. Source, API, +specification mappings and evidence agree. The merge is verified on develop. + +### 20. References and decisions + +The owning specification is `specs/household-automation.md`, including +household-automation-R7. Reuse the existing PageQuery limits and process-scoped +five-minute TaskCursor, as recorded in the maintainer's first clarification +answer. Use `.github/workflows/ci_check.yml` and the contributing PR's installed +version evidence as recorded in the second clarification answer. From eba168e88dedd7ddd6f84ea712094ca464a76f27 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Wed, 18 Nov 2026 09:28:36 +0100 Subject: [PATCH 2/6] feat(automation): show previous manual run results --- .../application/automation_run_history.py | 151 ++++++++++ backend/src/domus/application/ports.py | 10 + backend/src/domus/composition/tasks.py | 2 + .../src/domus/entrypoints/automation_http.py | 9 + backend/src/domus/entrypoints/native_http.py | 5 + backend/src/domus/entrypoints/task_http.py | 2 + .../domus/infrastructure/sqlite_receipts.py | 34 ++- docs/contracts/household-api.openapi.json | 265 ++++++++++++++++++ .../native-household-api.openapi.json | 265 ++++++++++++++++++ .../automation-run-history-qualification.md | 31 ++ docs/roadmap.md | 5 +- docs/user-guide.md | 12 + .../adapters/automation-run-history-http.ts | 48 ++++ .../src/application/automation-run-history.ts | 119 ++++++++ frontend/src/composition/entry-page.ts | 23 +- frontend/src/presentation/domus-app.ts | 8 +- .../domus-automation-run-history.ts | 108 +++++++ frontend/tests/automation-run-history.test.ts | 215 ++++++++++++++ .../tests/e2e/workspace-navigation.spec.ts | 57 +++- frontend/tests/page.test.ts | 17 ++ .../test_automation_execution_storage.py | 27 +- tests/backend/test_automation_run_history.py | 261 +++++++++++++++++ 22 files changed, 1663 insertions(+), 11 deletions(-) create mode 100644 backend/src/domus/application/automation_run_history.py create mode 100644 docs/evidence/automation-run-history-qualification.md create mode 100644 frontend/src/adapters/automation-run-history-http.ts create mode 100644 frontend/src/application/automation-run-history.ts create mode 100644 frontend/src/presentation/domus-automation-run-history.ts create mode 100644 frontend/tests/automation-run-history.test.ts create mode 100644 tests/backend/test_automation_run_history.py diff --git a/backend/src/domus/application/automation_run_history.py b/backend/src/domus/application/automation_run_history.py new file mode 100644 index 00000000..d2e034bd --- /dev/null +++ b/backend/src/domus/application/automation_run_history.py @@ -0,0 +1,151 @@ +"""Read one member's previously committed manual automation outcomes.""" + +import re +from collections.abc import Callable +from dataclasses import dataclass + +from domus.application.automation_execution import RUN_AUTOMATION +from domus.application.automation_preview import AutomationCommandAuthority +from domus.application.fixed_materialization import MaintenanceScope +from domus.application.ports import Transactions, UnitOfWork +from domus.application.task_authorization import TaskAccess +from domus.application.task_ports import TaskCursors +from domus.domain.errors import Forbidden, InvalidInput, NotFound, StorageFailure +from domus.domain.identity import MAX_REVISION, HumanIdentity, Permission, validate_revision +from domus.domain.storage import CommandKey, JsonDocument, Receipt, validate_identifier + + +@dataclass(frozen=True, slots=True) +class AutomationRunSummary: + operation_id: str + created_at: int + rule_revision: str + condition_matched: bool + task_created: bool + historical: bool + task_occurrence_id: str | None + + +@dataclass(frozen=True, slots=True) +class AutomationRunPage: + rule_id: str + items: tuple[AutomationRunSummary, ...] + next_cursor: str | None + + +def _position(marker: str) -> int: + if not re.fullmatch(r"[1-9][0-9]{0,18}", marker) or int(marker) > MAX_REVISION: + raise InvalidInput("invalid_task_cursor") + return int(marker) + + +def _task_access(unit: UnitOfWork, home: str, actor: HumanIdentity) -> bool: + try: + TaskAccess(actor).require(unit, home, Permission.TASKS_READ) + except Forbidden: + return False + return True + + +def _summary( + unit: UnitOfWork, + receipt: Receipt, + *, + task_access: bool, +) -> AutomationRunSummary: + result = receipt.result.decode() + revision = result.get("rule_revision") + matched = result.get("condition_matched") + occurrence_id = result.get("task_occurrence_id") + task_operation_id = result.get("task_operation_id") + try: + if ( + not isinstance(revision, str) + or str(int(revision)) != revision + or type(matched) is not bool + or ( + matched + and not (isinstance(occurrence_id, str) and isinstance(task_operation_id, str)) + ) + or (not matched and (occurrence_id is not None or task_operation_id is not None)) + or type(receipt.created_at) is not int + or not 0 <= receipt.created_at <= MAX_REVISION + ): + raise InvalidInput("invalid_automation_run_receipt") + validate_revision(int(revision)) + if isinstance(occurrence_id, str) and isinstance(task_operation_id, str): + validate_identifier(occurrence_id) + validate_identifier(task_operation_id) + except InvalidInput, ValueError: + raise StorageFailure("invalid_automation_run_receipt") from None + + linked = ( + occurrence_id + if isinstance(occurrence_id, str) + and not receipt.historical + and task_access + and unit.tasks.occurrence(receipt.command.household_id, occurrence_id) is not None + else None + ) + return AutomationRunSummary( + receipt.operation_id, + receipt.created_at, + revision, + matched, + matched, + receipt.historical, + linked, + ) + + +@dataclass(frozen=True, slots=True) +class AutomationRunHistory: + transactions: Transactions + scope: MaintenanceScope + read_actor: Callable[[], HumanIdentity] + cursors: TaskCursors + + def page(self, rule_id: str, *, limit: int, cursor: str | None) -> AutomationRunPage: + validate_identifier(rule_id) + if type(limit) is not int or not 1 <= limit <= 100: + raise InvalidInput("invalid_page_size") + human = self.read_actor() + home = self.scope.household_id + authority = AutomationCommandAuthority( + human, self.scope, CommandKey(home, human.ha_user_id, RUN_AUTOMATION, "history") + ) + with self.transactions.read() as unit: + member = authority.owner(unit) + if unit.automation_drafts.latest(home, rule_id) is None: + raise NotFound("automation_draft_missing") + binding = JsonDocument.from_value( + { + "query": "manual-automation-runs-v1", + "installation": self.scope.installation.instance_id, + "channel": self.scope.installation.channel, + "household": home, + "actor": human.ha_user_id, + "member": member.member_id, + "rule": rule_id, + "limit": limit, + } + ) + through = ( + MAX_REVISION + if cursor is None + else _position(self.cursors.decode(binding, cursor)) - 1 + ) + rows = unit.receipts.automation_run_page( + home, human.ha_user_id, member.member_id, rule_id, limit=limit + 1, through=through + ) + can_read_task = _task_access(unit, home, human) + return AutomationRunPage( + rule_id, + tuple( + _summary(unit, receipt, task_access=can_read_task) + for _, receipt in rows[:limit] + ), + self.cursors.encode(binding, str(rows[limit - 1][0])) + if len(rows) > limit + else None, + ) diff --git a/backend/src/domus/application/ports.py b/backend/src/domus/application/ports.py index b73418e5..ec5fb7f9 100644 --- a/backend/src/domus/application/ports.py +++ b/backend/src/domus/application/ports.py @@ -37,6 +37,16 @@ def get(self, command: CommandKey) -> Receipt | None: ... def get_operation( self, household_id: str, actor_id: str, operation_id: str ) -> Receipt | None: ... + def automation_run_page( + self, + household_id: str, + actor_id: str, + member_id: str, + rule_id: str, + *, + limit: int, + through: int, + ) -> tuple[tuple[int, Receipt], ...]: ... def add(self, receipt: Receipt) -> None: ... diff --git a/backend/src/domus/composition/tasks.py b/backend/src/domus/composition/tasks.py index d58d7c36..8971d908 100644 --- a/backend/src/domus/composition/tasks.py +++ b/backend/src/domus/composition/tasks.py @@ -6,6 +6,7 @@ from domus.application.automation_drafts import AutomationDrafts from domus.application.automation_execution import AutomationExecution from domus.application.automation_preview import AutomationPreview +from domus.application.automation_run_history import AutomationRunHistory from domus.application.calendar_commands import CalendarCommands from domus.application.calendar_queries import CalendarQueries from domus.application.family_queries import FamilyQueries @@ -112,6 +113,7 @@ def family() -> FamilyQueries: lambda: AutomationPreview(store, scope, actor.read()), AutomationDrafts(store, scope, actor, actor.read, clock, identifiers, cursors), AutomationExecution(store, scope, actor, actor.read, clock, identifiers, tasks), + AutomationRunHistory(store, scope, actor.read, cursors), ) return context diff --git a/backend/src/domus/entrypoints/automation_http.py b/backend/src/domus/entrypoints/automation_http.py index 5de48700..b9ca18d9 100644 --- a/backend/src/domus/entrypoints/automation_http.py +++ b/backend/src/domus/entrypoints/automation_http.py @@ -15,6 +15,7 @@ RunAutomation, ) from domus.application.automation_preview import AutomationPreviewAccess +from domus.application.automation_run_history import AutomationRunPage from domus.domain.automation import ( AUTOMATION_RULE_VERSION, MAX_RULE_NODES, @@ -264,6 +265,14 @@ def configure( ) return _receipt(receipt) + @router.get("/drafts/{rule_id}/runs", response_model=AutomationRunPage) + def run_history( + request: Request, rule_id: Identifier, query: Annotated[PageQuery, Query()] + ) -> AutomationRunPage: + return context(request).automation_run_history.page( + rule_id, limit=query.limit, cursor=query.cursor + ) + @router.post( "/drafts/{rule_id}/runs", response_model=ReceiptResponse, diff --git a/backend/src/domus/entrypoints/native_http.py b/backend/src/domus/entrypoints/native_http.py index 74a22cb6..c5280841 100644 --- a/backend/src/domus/entrypoints/native_http.py +++ b/backend/src/domus/entrypoints/native_http.py @@ -1,5 +1,6 @@ """Native HTTP binds HA Ingress to local sessions and the common household API.""" +import re from collections.abc import Callable from dataclasses import dataclass from typing import Annotated, Literal, cast @@ -112,6 +113,10 @@ def _allowed(self, scope: Scope) -> None: "/api/v1/inventory/shopping-list/", ) ) + or re.fullmatch( + r"/api/v1/automation/drafts/[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}/runs", + scope["path"], + ) or scope["path"] in ( "/api/v1/automation/drafts", diff --git a/backend/src/domus/entrypoints/task_http.py b/backend/src/domus/entrypoints/task_http.py index 23e1122b..215b7f19 100644 --- a/backend/src/domus/entrypoints/task_http.py +++ b/backend/src/domus/entrypoints/task_http.py @@ -10,6 +10,7 @@ from domus.application.automation_drafts import AutomationDrafts from domus.application.automation_execution import AutomationExecution from domus.application.automation_preview import AutomationPreview +from domus.application.automation_run_history import AutomationRunHistory from domus.application.calendar_commands import CalendarCommands from domus.application.calendar_queries import CalendarQueries from domus.application.family_queries import FamilyQueries, FamilyWeek @@ -128,6 +129,7 @@ class TaskHTTPContext: automation: Callable[[], AutomationPreview] automation_drafts: AutomationDrafts automation_execution: AutomationExecution + automation_run_history: AutomationRunHistory def create_task_router( diff --git a/backend/src/domus/infrastructure/sqlite_receipts.py b/backend/src/domus/infrastructure/sqlite_receipts.py index db77b20c..d3b6b748 100644 --- a/backend/src/domus/infrastructure/sqlite_receipts.py +++ b/backend/src/domus/infrastructure/sqlite_receipts.py @@ -3,7 +3,7 @@ import sqlite3 from dataclasses import dataclass -from domus.domain.errors import Conflict, InvalidInput +from domus.domain.errors import Conflict, InvalidInput, StorageFailure from domus.domain.storage import CommandKey, JsonDocument, Receipt from domus.infrastructure.sqlite_history import SQLiteHistory @@ -54,6 +54,38 @@ def get_operation(self, household_id: str, actor_id: str, operation_id: str) -> return history.receipt(original.command, original) return history.operation(household_id, actor_id, operation_id) + def automation_run_page( + self, + household_id: str, + actor_id: str, + member_id: str, + rule_id: str, + *, + limit: int, + through: int, + ) -> tuple[tuple[int, Receipt], ...]: + scope = (household_id, actor_id, rule_id, member_id, through) + rows = self.connection.execute( + "SELECT r.operation_id,o.position,0 AS historical FROM receipts r " + "JOIN outbox o ON o.event_id=r.operation_id " + "WHERE r.household_id=? AND r.actor_id=? AND r.action='automation.run' " + "AND json_extract(r.result,'$.rule_id')=? AND json_extract(r.result,'$.member_id')=? " + "AND o.position<=? UNION ALL " + "SELECT operation_id,position,1 AS historical FROM retained_operations " + "WHERE household_id=? AND actor_id=? AND action='automation.run' AND current=0 " + "AND json_extract(document,'$.result.rule_id')=? " + "AND json_extract(document,'$.result.member_id')=? AND position<=? " + "ORDER BY position DESC LIMIT ?", + (*scope, *scope, limit), + ).fetchall() + page = [] + for row in rows: + receipt = self.get_operation(household_id, actor_id, row["operation_id"]) + if receipt is None or receipt.historical != bool(row["historical"]): + raise StorageFailure("invalid_retained_projection") + page.append((row["position"], receipt)) + return tuple(page) + def add(self, receipt: Receipt) -> None: if receipt.restoration is not None: raise InvalidInput("receipt_projection_not_storable") diff --git a/docs/contracts/household-api.openapi.json b/docs/contracts/household-api.openapi.json index 3606061d..e400e319 100644 --- a/docs/contracts/household-api.openapi.json +++ b/docs/contracts/household-api.openapi.json @@ -943,6 +943,89 @@ "title": "AutomationPreviewBody", "type": "object" }, + "AutomationRunPage": { + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/AutomationRunSummary" + }, + "title": "Items", + "type": "array" + }, + "next_cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Next Cursor" + }, + "rule_id": { + "title": "Rule Id", + "type": "string" + } + }, + "required": [ + "rule_id", + "items", + "next_cursor" + ], + "title": "AutomationRunPage", + "type": "object" + }, + "AutomationRunSummary": { + "properties": { + "condition_matched": { + "title": "Condition Matched", + "type": "boolean" + }, + "created_at": { + "title": "Created At", + "type": "integer" + }, + "historical": { + "title": "Historical", + "type": "boolean" + }, + "operation_id": { + "title": "Operation Id", + "type": "string" + }, + "rule_revision": { + "title": "Rule Revision", + "type": "string" + }, + "task_created": { + "title": "Task Created", + "type": "boolean" + }, + "task_occurrence_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Task Occurrence Id" + } + }, + "required": [ + "operation_id", + "created_at", + "rule_revision", + "condition_matched", + "task_created", + "historical", + "task_occurrence_id" + ], + "title": "AutomationRunSummary", + "type": "object" + }, "AutomationSimulation": { "properties": { "conditions": { @@ -13292,6 +13375,188 @@ } }, "/api/v1/automation/drafts/{rule_id}/runs": { + "get": { + "operationId": "run_history_api_v1_automation_drafts__rule_id__runs_get", + "parameters": [ + { + "in": "path", + "name": "rule_id", + "required": true, + "schema": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Rule Id", + "type": "string" + } + }, + { + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 25, + "maximum": 100, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "anyOf": [ + { + "maxLength": 512, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Cursor" + } + }, + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AutomationRunPage" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Method Not Allowed" + }, + "408": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Request Timeout" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Content Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unprocessable Content" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "DomusSession": [] + } + ], + "summary": "Run History" + }, "post": { "operationId": "run_api_v1_automation_drafts__rule_id__runs_post", "parameters": [ diff --git a/docs/contracts/native-household-api.openapi.json b/docs/contracts/native-household-api.openapi.json index 6318968c..1b4102b1 100644 --- a/docs/contracts/native-household-api.openapi.json +++ b/docs/contracts/native-household-api.openapi.json @@ -943,6 +943,89 @@ "title": "AutomationPreviewBody", "type": "object" }, + "AutomationRunPage": { + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/AutomationRunSummary" + }, + "title": "Items", + "type": "array" + }, + "next_cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Next Cursor" + }, + "rule_id": { + "title": "Rule Id", + "type": "string" + } + }, + "required": [ + "rule_id", + "items", + "next_cursor" + ], + "title": "AutomationRunPage", + "type": "object" + }, + "AutomationRunSummary": { + "properties": { + "condition_matched": { + "title": "Condition Matched", + "type": "boolean" + }, + "created_at": { + "title": "Created At", + "type": "integer" + }, + "historical": { + "title": "Historical", + "type": "boolean" + }, + "operation_id": { + "title": "Operation Id", + "type": "string" + }, + "rule_revision": { + "title": "Rule Revision", + "type": "string" + }, + "task_created": { + "title": "Task Created", + "type": "boolean" + }, + "task_occurrence_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Task Occurrence Id" + } + }, + "required": [ + "operation_id", + "created_at", + "rule_revision", + "condition_matched", + "task_created", + "historical", + "task_occurrence_id" + ], + "title": "AutomationRunSummary", + "type": "object" + }, "AutomationSimulation": { "properties": { "conditions": { @@ -12780,6 +12863,188 @@ } }, "/api/v1/automation/drafts/{rule_id}/runs": { + "get": { + "operationId": "run_history_api_v1_automation_drafts__rule_id__runs_get", + "parameters": [ + { + "in": "path", + "name": "rule_id", + "required": true, + "schema": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$", + "title": "Rule Id", + "type": "string" + } + }, + { + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 25, + "maximum": 100, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "anyOf": [ + { + "maxLength": 512, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Cursor" + } + }, + { + "in": "header", + "name": "X-Domus-Context", + "required": true, + "schema": { + "title": "X-Domus-Context", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AutomationRunPage" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Method Not Allowed" + }, + "408": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Request Timeout" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Content Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Unprocessable Content" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "HomeAssistantIngress": [] + } + ], + "summary": "Run History" + }, "post": { "operationId": "run_api_v1_automation_drafts__rule_id__runs_post", "parameters": [ diff --git a/docs/evidence/automation-run-history-qualification.md b/docs/evidence/automation-run-history-qualification.md new file mode 100644 index 00000000..17cda796 --- /dev/null +++ b/docs/evidence/automation-run-history-qualification.md @@ -0,0 +1,31 @@ +# Manual automation run history qualification + +[Domus #122](https://github.com/vypdev/domus/issues/122) lets a member review +their own explicit manual runs for one saved rule. The +[automation specification](../../specs/household-automation.md) defines the +`manual-run-history` requirements and acceptance cases. + +| Case | Verification | +| --- | --- | +| `manual-run-history-C01` | The protected HTTP tests select one rule with two authorized members and a second rule. Each member sees only their own results for the selected rule. An unused rule has an empty history. | +| `manual-run-history-C02` | The same tests revoke manual access between pages. Separate task-read revocation leaves the original task decision visible while the task link disappears. | +| `manual-run-history-C03` | The original receipts remain in descending commit order when a new run arrives between pages. Tests verify the first page, the lookahead cursor, one-row continuations, and the supported page bounds. | +| `manual-run-history-C04` | Cursor checks cover a different rule, member and page size, expiry and signing-key rotation. The browser controller can restart from recent results. | +| `manual-run-history-C05` | The stored time, exact revision, task decision and receipt survive a rule edit, disabled control and restart. A history request leaves receipts, audit and task state untouched. | +| `manual-run-history-C06` | The SQLite activation test restores a snapshot between two runs. One current result remains linked to its original task. The later retained result appears once, keeps its original outcome and has no task link. | +| `manual-run-history-C07` | The compiled workspace journey exercises the English keyboard, Spanish on a narrow touch viewport, a failed older-page read and retry, exact task navigation and clearing the view when switching to a different rule. Both HTTP compositions use the same read. | +| `manual-run-history-C08` | The contributing pull request records the exact candidate's image checks and separately installed Home Assistant Edge acceptance, including cleanup. | + +The [protected HTTP tests](../../tests/backend/test_automation_run_history.py) +and [SQLite activation tests](../../tests/backend/test_automation_execution_storage.py) +exercise the original receipt and retained evidence. The +[frontend tests](../../frontend/tests/automation-run-history.test.ts) and +[workspace browser tests](../../frontend/tests/e2e/workspace-navigation.spec.ts) +qualify the selected rule, user session and recovery states. + +`GET /api/v1/automation/drafts/{rule_id}/runs` uses the current household +context in [Ingress](../contracts/native-household-api.openapi.json) and +[standalone](../contracts/household-api.openapi.json). The default is 25 +results and the maximum is 100. Continuation is bound to the authenticated +member, rule, and page size and expires within five minutes. The read uses +existing current and retained receipts in SQLite schema 33. diff --git a/docs/roadmap.md b/docs/roadmap.md index ebed49d6..7743c537 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -56,7 +56,10 @@ acceptance of the installed recurrence experience remain open. Household settings can simulate one task proposal against current stock and [save and reopen inactive drafts with immutable revisions](evidence/automation-draft-qualification.md). [Manual execution](evidence/automation-execution-qualification.md) pins the enabled draft revision - and records one explicit run with the task it creates. Scheduled and event triggers, multi-step + and records one explicit run with the task it creates. + [Manual run history](evidence/automation-run-history-qualification.md) lets the invoking member + reopen their recorded run outcomes and follow a task that is currently accessible. + Scheduled and event triggers, multi-step execution, the advanced editor and additional Domus-owned HA entities and services remain open. The existing gateway is already integrated. - M5 includes the [assigned and unclaimed task summaries on Overview](evidence/overview-task-qualification.md) diff --git a/docs/user-guide.md b/docs/user-guide.md index 2feed298..aab5afd0 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -398,6 +398,18 @@ original outcome and its operation ID. Disabling continues to preserve committed and their tasks. See the [automation specification](../specs/household-automation.md) for the remaining editor, runtime and Home Assistant work. +### Review previous manual runs + +Open a saved rule in **Household** and choose **Show run history**. The list +shows your latest runs for that rule, with the recorded time, revision and +task outcome. Choose **Older runs** for earlier results or **Recent runs** +to refresh the first page. Use **Try again** if an older page is temporarily +unavailable. Return to **Recent runs** if the page has expired. + +A retained result is marked as being from before restoration. **Open created +task** opens the original task when it belongs to the active household data +and you can still read it. + ## Channels and privacy Stable is production; Edge is experimental and has separate data, credentials and HA identities. diff --git a/frontend/src/adapters/automation-run-history-http.ts b/frontend/src/adapters/automation-run-history-http.ts new file mode 100644 index 00000000..d2638f32 --- /dev/null +++ b/frontend/src/adapters/automation-run-history-http.ts @@ -0,0 +1,48 @@ +import type {DraftScope} from '../application/automation-drafts'; +import type {AutomationRun, AutomationRunHistoryServer, AutomationRunPage} from '../application/automation-run-history'; +import {revisionValue} from '../domain/administration'; +import {BoundedHTTP, readFailure} from './http-transport'; +import type {FetchTransport} from './http-transport'; +import {failure} from './http-values'; +import type {EntryEndpoint} from './http-values'; +import {boolean, check, fields, identifier, integer, text} from './json-values'; + +function run(value: unknown): AutomationRun { + const row = fields(value, ['operation_id', 'created_at', 'rule_revision', 'condition_matched', + 'task_created', 'historical', 'task_occurrence_id'], []); + const taskCreated = boolean(row.task_created), historical = boolean(row.historical); + const taskOccurrenceId = row.task_occurrence_id === null ? null : identifier(row.task_occurrence_id); + const time = integer(row.created_at, 0); + check(time <= 8_640_000_000_000_000 && boolean(row.condition_matched) === taskCreated + && (taskOccurrenceId === null || (taskCreated && !historical))); + return {operationId: identifier(row.operation_id), revision: revisionValue(row.rule_revision), + time, historical, taskCreated, taskOccurrenceId}; +} + +export class HttpAutomationRunHistory implements AutomationRunHistoryServer { + private readonly network: BoundedHTTP; + + constructor(target: EntryEndpoint, transport: FetchTransport) { + this.network = new BoundedHTTP(target, transport); + } + + page(scope: DraftScope, ruleId: string, after: string | null) { + return this.network.owned(async signal => { + const route = 'automation/drafts/' + identifier(ruleId) + '/runs' + + (after === null ? '' : '?cursor=' + encodeURIComponent(after)); + const reply = await this.network.request(route, 'GET', scope.context, null, null, null, signal); + if (reply.status === 422 && after !== null) { + failure(reply.value); + if ((reply.value as {code: string}).code === 'invalid_task_cursor') return 'expired'; + } + if (reply.status !== 200) return readFailure(reply.status, reply.value); + const page = fields(reply.value, ['rule_id', 'items', 'next_cursor'], []); + check(page.rule_id === ruleId && Array.isArray(page.items) && page.items.length <= 25); + const items = page.items.map(run); + const next = page.next_cursor === null ? null : text(page.next_cursor, 512); + check(new Set(items.map(item => item.operationId)).size === items.length + && (next === null || (items.length === 25 && next.length > 0 && next !== after))); + return {items, next}; + }); + } +} diff --git a/frontend/src/application/automation-run-history.ts b/frontend/src/application/automation-run-history.ts new file mode 100644 index 00000000..c7223ac6 --- /dev/null +++ b/frontend/src/application/automation-run-history.ts @@ -0,0 +1,119 @@ +import type {Revision} from '../domain/administration'; +import type {DraftScope} from './automation-drafts'; +import {EntryReadError} from './ports'; +import type {EntryRead} from './ports'; + +export interface AutomationRun { + readonly operationId: string; + readonly time: number; + readonly revision: Revision; + readonly taskCreated: boolean; + readonly historical: boolean; + readonly taskOccurrenceId: string | null; +} +export interface AutomationRunPage { + readonly items: readonly AutomationRun[]; + readonly next: string | null; +} +export interface AutomationRunHistoryServer { + page(scope: DraftScope, ruleId: string, after: string | null): EntryRead; +} +export type AutomationRunHistoryIntent = 'open' | 'close' | 'older' | 'latest' | 'retry'; +export interface AutomationRunHistoryView { + readonly phase: 'closed' | 'loading' | 'ready' | 'unavailable' | 'expired' | 'denied'; + readonly items: readonly AutomationRun[]; + readonly hasOlder: boolean; + readonly timeZone: string; +} + +type Selection = Readonly<{scope: DraftScope; ruleId: string; timeZone: string}>; + +export class AutomationRunHistoryController { + private selection: Selection | null = null; + private request: EntryRead | null = null; + private view: AutomationRunHistoryView | null = null; + private next: string | null = null; + private attempted: string | null = null; + + constructor(private readonly server: AutomationRunHistoryServer, + private readonly publish: (view: AutomationRunHistoryView | null) => void) {} + + bind(scope: DraftScope | null, ruleId: string | null, timeZone: string | null): void { + const previous = this.selection; + if (scope === null || ruleId === null || timeZone === null) { + this.selection = null; + this.clear(null); + } else if (previous?.scope.key !== scope.key || previous.scope.readOnly !== scope.readOnly + || previous.ruleId !== ruleId || previous.timeZone !== timeZone) { + this.selection = {scope, ruleId, timeZone}; + this.clear(timeZone); + } + } + + private clear(timeZone: string | null): void { + this.request?.cancel(); + this.request = null; + this.next = null; + this.attempted = null; + this.view = timeZone === null ? null : {phase: 'closed', items: [], hasOlder: false, timeZone}; + this.publish(this.view); + } + + private show(phase: AutomationRunHistoryView['phase'], items: readonly AutomationRun[], timeZone: string): void { + this.view = {phase, items, hasOlder: this.next !== null, timeZone}; + this.publish(this.view); + } + + async handle(intent: AutomationRunHistoryIntent): Promise { + const selection = this.selection, view = this.view; + if (selection === null || view === null) return; + if (intent === 'close') { + this.clear(selection.timeZone); + return; + } + if (this.request !== null) return; + switch (intent) { + case 'open': + if (view.phase === 'closed') await this.load(selection, null, []); + break; + case 'older': + if (view.phase === 'ready' && this.next !== null) await this.load(selection, this.next, view.items); + break; + case 'latest': + if (view.phase === 'ready' || view.phase === 'expired') await this.load(selection, null, view.items); + break; + case 'retry': + if (view.phase === 'unavailable') await this.load(selection, this.attempted, view.items); + break; + } + } + + private async load({scope, ruleId, timeZone}: Selection, cursor: string | null, + prior: readonly AutomationRun[]): Promise { + this.attempted = cursor; + const request = this.server.page(scope, ruleId, cursor); + this.request = request; + this.show('loading', prior, timeZone); + try { + const page = await request.result; + if (this.request !== request) return; + this.request = null; + if (page === 'expired') { + this.next = null; + this.show('expired', [], timeZone); + } else { + this.next = page.next; + this.show('ready', page.items, timeZone); + } + } catch (error) { + if (this.request !== request) return; + this.request = null; + if (error instanceof EntryReadError && (error.code === 'forbidden' || error.code === 'authentication_required')) { + this.next = null; + this.show('denied', [], timeZone); + } else { + this.show('unavailable', prior, timeZone); + } + } + } +} diff --git a/frontend/src/composition/entry-page.ts b/frontend/src/composition/entry-page.ts index 187f0a62..ed5291cd 100644 --- a/frontend/src/composition/entry-page.ts +++ b/frontend/src/composition/entry-page.ts @@ -8,6 +8,9 @@ import {HttpAutomationDrafts} from '../adapters/automation-draft-http'; import {AUTOMATION_DRAFT_JOURNAL_KEY, AutomationDraftSessionJournal} from '../adapters/automation-draft-journal'; import {AutomationDraftController} from '../application/automation-drafts'; import type {AutomationDraftIntent, AutomationDraftView, DraftScope} from '../application/automation-drafts'; +import {HttpAutomationRunHistory} from '../adapters/automation-run-history-http'; +import {AutomationRunHistoryController} from '../application/automation-run-history'; +import type {AutomationRunHistoryIntent} from '../application/automation-run-history'; import {HttpAutomationExecution} from '../adapters/automation-execution-http'; import {AutomationExecutionSessionJournal} from '../adapters/automation-execution-journal'; import {AutomationExecutionController} from '../application/automation-execution'; @@ -227,6 +230,7 @@ export function mountEntry(page: EntryPage): PageMount { let automationPreview: AutomationPreviewController | null = null; let automationDrafts: AutomationDraftController | null = null; let automationExecution: AutomationExecutionController | null = null; + let automationRunHistory: AutomationRunHistoryController | null = null; let stockAttention: OverviewReadController | null = null; let shoppingAttention: OverviewReadController | null = null; let familyOverview: OverviewReadController | null = null; @@ -236,7 +240,7 @@ export function mountEntry(page: EntryPage): PageMount { let localeOwner:string|null=null,preferenceIdentity:string|null=null,hadPreference=false,temporaryLanguage=false,temporaryContext:string|null=null; const dispose = () => { if (stopped) return; - stopped = true; widget.abort(); lifetime.abort(); runtime?.dispose(); calendar?.bind(null); family?.bind(null); rewards?.bind(null); inventory?.bind(null); allocation?.bind(null); calendarPreference?.bind(null); review?.bind(null); taskOverview?.bind(null); automationPreview?.bind(null); automationDrafts?.bind(null); automationExecution?.bind(null, null); error?.remove(); + stopped = true; widget.abort(); lifetime.abort(); runtime?.dispose(); calendar?.bind(null); family?.bind(null); rewards?.bind(null); inventory?.bind(null); allocation?.bind(null); calendarPreference?.bind(null); review?.bind(null); taskOverview?.bind(null); automationPreview?.bind(null); automationDrafts?.bind(null); automationExecution?.bind(null, null); automationRunHistory?.bind(null, null, null); error?.remove(); stockAttention?.bind(null); shoppingAttention?.bind(null); familyOverview?.bind(null); if (mounts.get(doc) === dispose) mounts.delete(doc); }; @@ -246,7 +250,7 @@ export function mountEntry(page: EntryPage): PageMount { }, {signal: lifetime.signal}); const fail = () => { if (stopped || error !== null) return; - widget.abort(); runtime?.dispose(); calendar?.bind(null); family?.bind(null); rewards?.bind(null); inventory?.bind(null); allocation?.bind(null); calendarPreference?.bind(null); review?.bind(null); taskOverview?.bind(null); automationPreview?.bind(null); automationDrafts?.bind(null); automationExecution?.bind(null, null); app?.remove(); + widget.abort(); runtime?.dispose(); calendar?.bind(null); family?.bind(null); rewards?.bind(null); inventory?.bind(null); allocation?.bind(null); calendarPreference?.bind(null); review?.bind(null); taskOverview?.bind(null); automationPreview?.bind(null); automationDrafts?.bind(null); automationExecution?.bind(null, null); automationRunHistory?.bind(null, null, null); app?.remove(); stockAttention?.bind(null); shoppingAttention?.bind(null); familyOverview?.bind(null); const locale = language(null, page.navigator.language); doc.documentElement.lang = locale; error = doc.createElement('main'); error.id = 'domus-entry-error'; @@ -509,10 +513,14 @@ export function mountEntry(page: EntryPage): PageMount { setItem:(key,value) => browser.storage().setItem(key,value), removeItem:key => browser.storage().removeItem(key)}), new BrowserEntropy(browser.random), view => {element.automationExecution = view;}); automationExecution = execution; + const runHistory = new AutomationRunHistoryController(new HttpAutomationRunHistory(source.target, browser.transport), + view => {element.automationRunHistory = view;}); + automationRunHistory = runHistory; let executionScope: DraftScope | null = null; const syncExecution = (view: AutomationDraftView | null) => { - if (view?.state === 'ready') execution.bind(executionScope, view.selected); - else execution.bind(null, null); + const selected = view?.state === 'ready' ? view.selected : null; + execution.bind(view?.state === 'ready' ? executionScope : null, selected); + runHistory.bind(executionScope, selected?.id ?? null, element.view?.household?.timeZone ?? null); }; const drafts = new AutomationDraftController(new HttpAutomationDrafts(source.target, browser.transport), new AutomationDraftSessionJournal({getItem:key => browser.storage().getItem(key), @@ -536,7 +544,7 @@ export function mountEntry(page: EntryPage): PageMount { syncExecution(element.automationDrafts); } else { executionScope = null; - automation.bind(null); drafts.bind(null); execution.bind(null, null); + automation.bind(null); drafts.bind(null); syncExecution(null); } }; element.addEventListener('domus-automation-preview-intent', event => { @@ -553,6 +561,11 @@ export function mountEntry(page: EntryPage): PageMount { if (['enable', 'disable', 'run', 'confirm', 'cancel', 'recover', 'reload'].includes(intent)) void execution.handle(intent); }, {signal: widget.signal}); + element.addEventListener('domus-automation-run-history-intent', event => { + if (event.target !== element) return; + const intent = (event as CustomEvent).detail; + if (['open', 'close', 'older', 'latest', 'retry'].includes(intent)) void runHistory.handle(intent); + }, {signal: widget.signal}); const syncWorkspace = () => { const fragment = new URL(page.location.href).hash; element.shoppingTarget = /^#inventory-shopping\/((?:product|extra):[A-Za-z0-9][A-Za-z0-9_.:-]{0,127})$/u.exec(fragment)?.[1] ?? null; diff --git a/frontend/src/presentation/domus-app.ts b/frontend/src/presentation/domus-app.ts index ca8e118e..2f1c2148 100644 --- a/frontend/src/presentation/domus-app.ts +++ b/frontend/src/presentation/domus-app.ts @@ -14,6 +14,8 @@ import './domus-automation-preview'; import type {AutomationPreviewView} from '../application/automation-preview'; import './domus-automation-drafts'; import './domus-automation-execution'; +import './domus-automation-run-history'; +import type {AutomationRunHistoryView} from '../application/automation-run-history'; import type {AutomationDraftView} from '../application/automation-drafts'; import type {AutomationExecutionView} from '../application/automation-execution'; import './domus-stock-attention'; @@ -55,7 +57,7 @@ export type EntryIntent = Readonly<{type: 'refresh' | 'request_membership' | 'lo /** Owned rendering only; intents cross a semantic boundary and never grant command authority. */ export class DomusApp extends LitElement { static properties = {inventory: {attribute:false}, rewards: {attribute:false}, allocation: {attribute:false}, family: {attribute:false}, familyScopeKey: {attribute:false}, familyToday: {attribute:false}, recurrenceReview: {attribute:false}, calendar: {attribute:false}, calendarPreference: {attribute:false}, calendarScopeKey: {attribute:false}, calendarToday: {attribute:false}, tasks: {attribute: false}, view: {attribute: false}, administration: {attribute:false}, deployment: {attribute: false}, language: {attribute: false}, - taskOverview: {attribute: false}, automationPreview: {attribute: false}, automationDrafts: {attribute: false}, automationExecution: {attribute: false}, stockAttention: {attribute: false}, shoppingAttention: {attribute: false}, familyOverview: {attribute: false}, + taskOverview: {attribute: false}, automationPreview: {attribute: false}, automationDrafts: {attribute: false}, automationExecution: {attribute: false}, automationRunHistory: {attribute: false}, stockAttention: {attribute: false}, shoppingAttention: {attribute: false}, familyOverview: {attribute: false}, workspaceDestination: {attribute: false}, nameDraft: {state: true}, zoneDraft: {state: true}}; static styles = styles; declare view: EntryView | null; @@ -65,6 +67,7 @@ export class DomusApp extends LitElement { declare automationPreview: AutomationPreviewView | null; declare automationDrafts: AutomationDraftView | null; declare automationExecution: AutomationExecutionView | null; + declare automationRunHistory: AutomationRunHistoryView | null; declare stockAttention: StockAttentionView | null; declare shoppingAttention: ShoppingAttentionView | null; declare familyOverview: FamilyOverviewView | null; @@ -92,7 +95,7 @@ export class DomusApp extends LitElement { this.recurrenceReview = null; this.calendar = null; this.calendarPreference = null; this.calendarScopeKey = null; this.calendarToday = DATE_MIN; this.family = null; this.rewards = null; this.inventory = null; this.allocation = null; this.familyScopeKey = null; this.familyToday = DATE_MIN; this.workspaceDestination = null; this.taskOverview = null; this.automationPreview = null; this.nameDraft = ''; this.zoneDraft = ''; - this.automationDrafts = null; this.automationExecution = null; + this.automationDrafts = null; this.automationExecution = null; this.automationRunHistory = null; this.stockAttention = null; this.shoppingAttention = null; this.familyOverview = null; } disconnectedCallback(): void {super.disconnectedCallback(); this.dispatchEvent(new Event('domus-detached'));} @@ -283,6 +286,7 @@ export class DomusApp extends LitElement { + diff --git a/frontend/src/presentation/domus-automation-run-history.ts b/frontend/src/presentation/domus-automation-run-history.ts new file mode 100644 index 00000000..2d4be330 --- /dev/null +++ b/frontend/src/presentation/domus-automation-run-history.ts @@ -0,0 +1,108 @@ +import {LitElement, css, html, nothing} from 'lit'; +import {repeat} from 'lit/directives/repeat.js'; +import {registerButton} from '@vypdev/ha-ui/button'; +import {buttonState} from '@vypdev/ha-ui/button-contracts'; +import {registerCard} from '@vypdev/ha-ui/card'; +import {cardState} from '@vypdev/ha-ui/card-contracts'; +import {registerFeedback} from '@vypdev/ha-ui/feedback'; +import {feedbackState} from '@vypdev/ha-ui/feedback-contracts'; +import type {AutomationRun, AutomationRunHistoryIntent, AutomationRunHistoryView} from '../application/automation-run-history'; +import type {Language} from './messages'; + +const COPY = { + en: { + heading: 'Manual run history', open: 'Show run history', close: 'Hide run history', + loading: 'Loading manual runs…', empty: 'You have no manual runs for this rule.', + unavailable: 'The run history is temporarily unavailable.', retry: 'Try again', + denied: 'Your current permissions do not allow you to view this history.', + expired: 'This page has expired. Go back to recent runs.', + older: 'Older runs', latest: 'Recent runs', revision: 'Revision', + created: 'Task created.', skipped: 'The stock condition did not match. No task was created.', + historical: 'Result from before restoration.', task: 'Open created task', operation: 'Operation ID', + }, + es: { + heading: 'Historial de ejecuciones manuales', open: 'Mostrar historial', close: 'Ocultar historial', + loading: 'Cargando ejecuciones manuales…', empty: 'No tienes ejecuciones manuales para esta regla.', + unavailable: 'El historial no está disponible en este momento.', retry: 'Volver a intentar', + denied: 'Tus permisos actuales no te permiten consultar el historial.', + expired: 'Esta página ha caducado. Vuelve a las ejecuciones recientes.', + older: 'Ejecuciones anteriores', latest: 'Ejecuciones recientes', revision: 'Revisión', + created: 'Tarea creada.', skipped: 'No se cumplió la condición de existencias. No se creó ninguna tarea.', + historical: 'Resultado anterior a la restauración.', task: 'Abrir tarea creada', operation: 'Identificador de operación', + }, +} as const; + +export class DomusAutomationRunHistory extends LitElement { + static properties = {view: {attribute: false}, language: {attribute: false}}; + static styles = css` + :host {display:block;--vyp-ha-surface:var(--surface);--vyp-ha-text:var(--text);--vyp-ha-text-secondary:var(--muted); + --vyp-ha-border:var(--line);--vyp-ha-primary:var(--accent);--vyp-ha-on-accent:var(--surface); + --vyp-ha-focus-ring:3px solid var(--accent)} + vyp-ha-card {margin-block-end:16px} + section {display:grid;gap:10px;margin-block-start:12px} + .actions {display:flex;flex-wrap:wrap;gap:8px} + ol {display:grid;gap:10px;margin:0;padding-inline-start:24px} + li {padding-block:8px;border-block-start:1px solid var(--line);overflow-wrap:anywhere} + p {margin:0 0 5px} + a {color:var(--accent);display:inline-flex;min-block-size:44px;align-items:center} + a:focus-visible, section:focus-visible {outline:3px solid var(--accent);outline-offset:3px} + small {display:block} + `; + + declare view: AutomationRunHistoryView | null; + declare language: Language; + + constructor() {super(); this.view = null; this.language = 'en';} + + private button(intent: AutomationRunHistoryIntent) { + return html` { + if (intent === 'older' || intent === 'latest' || intent === 'retry') + this.renderRoot.querySelector('section')?.focus(); + this.dispatchEvent(new CustomEvent('domus-automation-run-history-intent', + {detail: intent, bubbles: true, composed: true})); + }}>`; + } + + private run(item: AutomationRun, format: Intl.DateTimeFormat) { + const text = COPY[this.language], date = new Date(item.time), occurrenceId = item.taskOccurrenceId; + return html`
  • +

    · ${text.revision} ${item.revision}

    +

    ${item.taskCreated ? text.created : text.skipped}

    + ${item.historical ? html`

    ${text.historical}

    ` : nothing} + ${occurrenceId === null ? nothing : html` { + event.preventDefault(); + this.dispatchEvent(new CustomEvent('domus-automation-task-intent', + {detail: {type: 'select', occurrenceId}, bubbles: true, composed: true})); + }}>${text.task}`} + ${text.operation} ${item.operationId} +
  • `; + } + + protected render() { + const view = this.view; + if (view === null) return nothing; + const text = COPY[this.language], {phase, items, hasOlder, timeZone} = view; + const format = new Intl.DateTimeFormat(this.language, {dateStyle: 'medium', timeStyle: 'short', timeZone}); + return html` + ${this.button(phase === 'closed' ? 'open' : 'close')} + ${phase === 'closed' ? nothing : html`
    + ${items.length === 0 ? nothing : html`
      ${repeat(items, item => item.operationId, + item => this.run(item, format))}
    `} + ${phase === 'loading' ? html`` : nothing} + ${phase === 'ready' && items.length === 0 ? html`

    ${text.empty}

    ` : nothing} + ${phase === 'unavailable' || phase === 'expired' || phase === 'denied' + ? html`` : nothing} +
    + ${phase === 'ready' && hasOlder ? this.button('older') : nothing} + ${phase === 'ready' || phase === 'expired' ? this.button('latest') : nothing} + ${phase === 'unavailable' ? this.button('retry') : nothing} +
    +
    `} +
    `; + } +} + +registerButton(); registerCard(); registerFeedback(); +customElements.define('domus-automation-run-history', DomusAutomationRunHistory); +declare global {interface HTMLElementTagNameMap {'domus-automation-run-history': DomusAutomationRunHistory;}} diff --git a/frontend/tests/automation-run-history.test.ts b/frontend/tests/automation-run-history.test.ts new file mode 100644 index 00000000..7202059c --- /dev/null +++ b/frontend/tests/automation-run-history.test.ts @@ -0,0 +1,215 @@ +import {afterEach, expect, test, vi} from 'vitest'; +import {HttpAutomationRunHistory} from '../src/adapters/automation-run-history-http'; +import type {DraftScope} from '../src/application/automation-drafts'; +import {AutomationRunHistoryController} from '../src/application/automation-run-history'; +import type {AutomationRun, AutomationRunHistoryServer, AutomationRunHistoryView, AutomationRunPage} + from '../src/application/automation-run-history'; +import {EntryReadError} from '../src/application/ports'; +import type {EntryRead} from '../src/application/ports'; +import {revisionValue} from '../src/domain/administration'; +import '../src/presentation/domus-automation-run-history'; + +const scope: DraftScope = {key: 'home-owner', memberId: 'member', readOnly: false, + context: {installationId: '01234567-89ab-cdef-0123-456789abcdef', channel: 'edge', subject: 'a'.repeat(32)}}; +const made: AutomationRun = {operationId: 'made', revision: revisionValue('1'), time: 1000, + taskCreated: true, historical: false, taskOccurrenceId: 'task'}; +const skipped: AutomationRun = {operationId: 'skipped', revision: revisionValue('2'), time: 2000, + taskCreated: false, historical: false, taskOccurrenceId: null}; +const retained = {...made, operationId: 'retained', historical: true, taskOccurrenceId: null}; +const current = {items: [made], next: 'cursor'}; +const older = {items: [skipped], next: null}; + +const settled = (value: T): EntryRead => ({result: Promise.resolve(value), cancel: vi.fn()}); +const failed = (error: unknown = new EntryReadError('unavailable')): EntryRead => + ({result: Promise.reject(error), cancel: vi.fn()}); + +function fixture() { + const page = vi.fn(() => settled(current)); + const publish = vi.fn(); + const history = new AutomationRunHistoryController({page}, publish); + const last = () => publish.mock.lastCall?.[0] as AutomationRunHistoryView | null; + return {page, publish, history, last}; +} + +test('history retries the same older request and can restart from recent results', async () => { + const f = fixture(); + await f.history.handle('open'); + f.history.bind(scope, 'rule', 'UTC'); + expect(f.last()?.phase).toBe('closed'); + await f.history.handle('retry'); + await f.history.handle('latest'); + await f.history.handle('older'); + expect(f.page).not.toHaveBeenCalled(); + + const reading = f.history.handle('open'); + expect(f.last()?.phase).toBe('loading'); + await f.history.handle('open'); + await reading; + await f.history.handle('open'); + expect(f.page).toHaveBeenCalledTimes(1); + expect(f.last()).toEqual({phase: 'ready', items: [made], hasOlder: true, timeZone: 'UTC'}); + f.history.bind({...scope}, 'rule', 'UTC'); + expect(f.last()?.phase).toBe('ready'); + + f.page.mockReturnValueOnce(failed(new Error('offline'))); + await f.history.handle('older'); + expect(f.last()).toMatchObject({phase: 'unavailable', items: [made]}); + f.page.mockReturnValueOnce(settled(older)); + await f.history.handle('retry'); + expect(f.page.mock.calls.slice(-2)).toEqual([[scope, 'rule', 'cursor'], [scope, 'rule', 'cursor']]); + expect(f.last()).toMatchObject({phase: 'ready', items: [skipped], hasOlder: false}); + await f.history.handle('older'); + expect(f.page).toHaveBeenCalledTimes(3); + await f.history.handle('latest'); + expect(f.page).toHaveBeenLastCalledWith(scope, 'rule', null); + f.page.mockReturnValueOnce(settled('expired')); + await f.history.handle('older'); + expect(f.last()).toMatchObject({phase: 'expired', items: [], hasOlder: false}); + await f.history.handle('latest'); + expect(f.page).toHaveBeenLastCalledWith(scope, 'rule', null); + expect(f.last()?.items).toEqual([made]); +}); + +test('scope and rule changes cancel stale results and current access denial clears details', async () => { + const f = fixture(); + f.history.bind(scope, 'rule', 'UTC'); + await f.history.handle('open'); + const pending = Promise.withResolvers(); + const cancel = vi.fn(); + f.page.mockReturnValueOnce({result: pending.promise, cancel}); + const oldRule = f.history.handle('older'); + f.history.bind(scope, 'different-rule', 'UTC'); + pending.resolve(older); + await oldRule; + expect(cancel).toHaveBeenCalledOnce(); + expect(f.last()).toMatchObject({phase: 'closed', items: []}); + await f.history.handle('open'); + f.page.mockReturnValueOnce(failed(new EntryReadError('forbidden'))); + await f.history.handle('older'); + expect(f.last()).toMatchObject({phase: 'denied', items: [], hasOlder: false}); + await f.history.handle('close'); + f.page.mockReturnValueOnce(failed(new EntryReadError('authentication_required'))); + await f.history.handle('open'); + expect(f.last()?.phase).toBe('denied'); + + f.history.bind({...scope, readOnly: true}, 'different-rule', 'UTC'); + expect(f.last()?.phase).toBe('closed'); + f.history.bind({...scope, readOnly: true}, 'different-rule', 'Europe/Madrid'); + expect(f.last()?.timeZone).toBe('Europe/Madrid'); + + const other = Promise.withResolvers(); + f.page.mockReturnValueOnce({result: other.promise, cancel: vi.fn()}); + const inFlight = f.history.handle('open'); + f.history.bind({...scope, key: 'new-member'}, 'different-rule', 'Europe/Madrid'); + other.reject(new EntryReadError('unavailable')); + await inFlight; + expect(f.last()).toMatchObject({phase: 'closed', items: []}); + f.history.bind(scope, null, 'UTC'); + expect(f.last()).toBeNull(); + f.history.bind(scope, 'rule', null); + f.history.bind(null, null, null); +}); + +const target = {origin: 'https://domus.local', applicationBase: '/', deployment: 'standalone'} as const; +const wire = {operation_id: 'made', created_at: 1000, rule_revision: '1', + condition_matched: true, task_created: true, historical: false, task_occurrence_id: 'task'}; +const envelope = (items: readonly unknown[], next: string | null = null) => + ({rule_id: 'rule', items, next_cursor: next}); +const errorBody = (code: string) => + ({state: 'blocked', code, message: 'Unable to read.', action_required: 'Try again.', correlation_id: 'cor_history'}); + +test('transport validates the selected rule, bounded page, date, historical link and expiry', async () => { + let payload: unknown = envelope([wire]), status = 200; + const transport = vi.fn(async (route: string, _init: RequestInit) => { + const response = new Response(JSON.stringify(payload), {status, + headers: {'Content-Type': 'application/json', 'Cache-Control': 'no-store'}}); + Object.defineProperty(response, 'url', {value: target.origin + route}); + return response; + }); + const server = new HttpAutomationRunHistory(target, transport); + await expect(server.page(scope, 'rule', null).result).resolves.toEqual({items: [made], next: null}); + expect(transport.mock.lastCall?.[0]).toBe('/api/v1/automation/drafts/rule/runs'); + expect(transport.mock.lastCall?.[1].method).toBe('GET'); + const sizes = Array.from({length: 25}, (_, i) => ({...wire, operation_id: 'operation-' + i})); + payload = envelope(sizes, 'more'); + await expect(server.page(scope, 'rule', 'signed+=cursor').result).resolves.toMatchObject({next: 'more'}); + expect(transport.mock.lastCall?.[0]).toBe('/api/v1/automation/drafts/rule/runs?cursor=signed%2B%3Dcursor'); + for (const invalid of [ + {...envelope([wire]), rule_id: 'other'}, {...envelope([wire]), items: {}}, + envelope([...sizes, wire]), envelope([wire, wire]), envelope([wire], 'too-early'), + envelope(sizes, ''), envelope(sizes, 'same'), + envelope([{...wire, historical: true}]), envelope([{...wire, created_at: 8_700_000_000_000_000}]), + envelope([{...wire, condition_matched: false}]), + envelope([{...wire, task_created: false, condition_matched: false}]), + ]) { + payload = invalid; + await expect(server.page(scope, 'rule', 'same').result).rejects.toMatchObject({code: 'invalid_response'}); + } + payload = envelope([{...wire, task_occurrence_id: null, historical: true}]); + await expect(server.page(scope, 'rule', null).result).resolves.toMatchObject({ + items: [{...made, historical: true, taskOccurrenceId: null}], + }); + status = 422; payload = errorBody('invalid_task_cursor'); + await expect(server.page(scope, 'rule', 'stale').result).resolves.toBe('expired'); + await expect(server.page(scope, 'rule', null).result).rejects.toMatchObject({code: 'invalid_response'}); + payload = errorBody('invalid_request'); + await expect(server.page(scope, 'rule', 'stale').result).rejects.toMatchObject({code: 'invalid_response'}); + status = 403; payload = errorBody('permission_denied'); + await expect(server.page(scope, 'rule', 'stale').result).rejects.toMatchObject({code: 'forbidden'}); +}); + +afterEach(() => document.querySelectorAll('domus-automation-run-history').forEach(node => node.remove())); + +test('the history panel localizes empty, unavailable, expired, denied and exact retained outcomes', async () => { + const element = document.createElement('domus-automation-run-history'); + document.body.append(element); + await element.updateComplete; + const root = element.shadowRoot!; + expect(root.querySelector('vyp-ha-card')).toBeNull(); + const intents = vi.fn(), task = vi.fn(); + element.addEventListener('domus-automation-run-history-intent', intents); + element.addEventListener('domus-automation-task-intent', task); + const view = async (phase: AutomationRunHistoryView['phase'], items: readonly AutomationRun[] = [], hasOlder = false) => { + element.view = {phase, items, hasOlder, timeZone: 'UTC'}; + await element.updateComplete; + }; + const press = (label: string) => { + const button = [...root.querySelectorAll('vyp-ha-button')].find(node => node.state?.label === label); + expect(button).toBeDefined(); + button!.dispatchEvent(new CustomEvent('ha-press-request')); + }; + + await view('closed'); + press('Show run history'); + expect(intents.mock.lastCall?.[0].detail).toBe('open'); + expect(root.querySelector('section')).toBeNull(); + await view('loading'); + expect(root.querySelector('section')?.getAttribute('aria-busy')).toBe('true'); + expect(root.querySelector('vyp-ha-feedback')?.state?.message).toContain('Loading manual runs'); + await view('ready'); + expect(root.textContent).toContain('You have no manual runs'); + await view('ready', [skipped, made, retained], true); + expect(root.querySelectorAll('li')).toHaveLength(3); + expect(root.querySelectorAll('a')).toHaveLength(1); + expect(root.querySelector('time')?.dateTime).toBe('1970-01-01T00:00:02.000Z'); + expect(root.textContent).toContain('Result from before restoration.'); + root.querySelector('a')!.click(); + expect(task.mock.lastCall?.[0].detail).toEqual({type: 'select', occurrenceId: 'task'}); + press('Older runs'); + expect(root.activeElement?.tagName).toBe('SECTION'); + + element.language = 'es'; + await view('unavailable', [made]); + expect(root.querySelector('vyp-ha-feedback')?.state?.message).toContain('no está disponible'); + expect(root.textContent).toContain('Tarea creada.'); + press('Volver a intentar'); + expect(intents.mock.lastCall?.[0].detail).toBe('retry'); + await view('expired'); + expect(root.querySelector('vyp-ha-feedback')?.state?.message).toContain('ha caducado'); + press('Ejecuciones recientes'); + expect(intents.mock.lastCall?.[0].detail).toBe('latest'); + await view('denied'); + expect(root.querySelector('vyp-ha-feedback')?.state?.message).toContain('Tus permisos actuales'); + press('Ocultar historial'); + expect(intents.mock.lastCall?.[0].detail).toBe('close'); +}); diff --git a/frontend/tests/e2e/workspace-navigation.spec.ts b/frontend/tests/e2e/workspace-navigation.spec.ts index 7a5f4504..e4b49342 100644 --- a/frontend/tests/e2e/workspace-navigation.spec.ts +++ b/frontend/tests/e2e/workspace-navigation.spec.ts @@ -1361,7 +1361,7 @@ for (const mode of ['native', 'standalone'] as const) { for (const mode of ['native', 'standalone'] as const) { test(`manual automation confirmation and original receipt in ${mode}`, async ({page, context, request}, info) => { - test.setTimeout(70_000); + test.setTimeout(90_000); const origin = `http://127.0.0.1:${mode === 'native' ? 56174 : 56175}`; const base = origin + (mode === 'native' ? ingress : '') + '/'; if (process.env.DOMUS_BROWSER_IMAGE) { @@ -1431,6 +1431,12 @@ for (const mode of ['native', 'standalone'] as const) { if (item.url() === runsURL && item.method() === 'POST') requestedRuns++; }); + const history = page.locator('domus-automation-run-history'); + await history.getByRole('button',{name:'Show run history',exact:true}).press('Enter'); + await expect(history.getByText('You have no manual runs for this rule.',{exact:true})).toBeVisible(); + await history.getByRole('button',{name:'Hide run history',exact:true}).press('Enter'); + await expect(history.getByRole('list')).toHaveCount(0); + await expect(execution.getByText('Disabled',{exact:true})).toBeVisible(); await execution.getByRole('button',{name:'Enable saved revision',exact:true}).press('Enter'); const confirmation = execution.getByRole('region',{name:'Confirm automation action',exact:true}); @@ -1482,11 +1488,60 @@ for (const mode of ['native', 'standalone'] as const) { await tabs.getByRole('link',{name:'Hogar',exact:true}).tap(); await drafts.getByRole('button',{name:'Abrir ' + draftTitle,exact:true}).tap(); + await stockWrite('refill-for-later-no-task-runs',{action:'inventory.adjust',product_id:product, + quantity:'2',reason:'Replenished for history test'}); + const token = await page.request.get(base + 'api/v1/auth/csrf', {headers:{'X-Domus-Context':contextHeader}}); + expect(token.ok()).toBe(true); + const csrf = (await token.json()).csrf_token; + const writeHeaders = {Origin:origin, 'X-Domus-Context':contextHeader, 'X-CSRF-Token':csrf}; + const secondDraft = await page.request.post(draftsURL, {data:{ + version:1, trigger:{kind:'manual'}, condition:null, + action:{kind:'task.create',title:'Inspect the fixture shelf'}, rule_id:null, expected_revision:'0', + }, headers:{...writeHeaders, 'Idempotency-Key':'separate-history-rule'}}); + expect(secondDraft.ok(), await secondDraft.text()).toBe(true); + for (let index = 0; index < 25; index++) { + const newer = await page.request.post(runsURL, {data:{rule_revision:'1',control_revision:'1'}, + headers:{...writeHeaders, 'Idempotency-Key':'additional-history-run-' + index}}); + expect(newer.ok(), await newer.text()).toBe(true); + expect((await newer.json()).result.condition_matched).toBe(false); + } + const disable = execution.getByRole('button',{name:'Deshabilitar futuras ejecuciones',exact:true}); await disable.tap(); await execution.getByRole('region',{name:'Confirmar acción de automatización',exact:true}) .getByRole('button',{name:'Deshabilitar futuras ejecuciones',exact:true}).tap(); await expect(execution.getByText('Futuras ejecuciones deshabilitadas.',{exact:true})).toBeVisible(); await expect(execution.getByRole('button',{name:'Ejecutar manualmente',exact:true})).toHaveCount(0); + + await history.getByRole('button',{name:'Mostrar historial',exact:true}).tap(); + await expect(history.getByRole('listitem')).toHaveCount(25); + await expect(history.getByRole('link',{name:'Abrir tarea creada',exact:true})).toHaveCount(0); + const olderPage = (url: URL) => url.origin + url.pathname === runsURL && url.searchParams.has('cursor'); + await page.route(olderPage, route => route.abort('failed'), {times:1}); + await history.getByRole('button',{name:'Ejecuciones anteriores',exact:true}).tap(); + await expect(history.getByText('El historial no está disponible en este momento.',{exact:true})).toBeVisible(); + await expect(history.getByRole('listitem')).toHaveCount(25); + + const retry = page.waitForResponse(reply => olderPage(new URL(reply.url())) && reply.request().method() === 'GET'); + await history.getByRole('button',{name:'Volver a intentar',exact:true}).tap(); + expect((await retry).ok()).toBe(true); + await expect(history.getByRole('listitem')).toHaveCount(2); + await expect(history.getByText('Tarea creada.',{exact:true})).toBeVisible(); + await expect(history.getByText('No se cumplió la condición de existencias. No se creó ninguna tarea.',{exact:true})).toBeVisible(); + await expect(history.locator('time').first()).toHaveAttribute('datetime', /^\d{4}-\d{2}-\d{2}T/u); + await history.screenshot({path:info.outputPath('manual-history-es-narrow.png')}); + const originalTask = page.waitForResponse(base + 'api/v1/tasks/occurrences/' + taskId); + await history.getByRole('link',{name:'Abrir tarea creada',exact:true}).tap(); + expect((await originalTask).ok()).toBe(true); + await expect(page.locator('domus-tasks').getByRole('heading',{name:draftTitle,exact:true})).toBeVisible(); + await tabs.getByRole('link',{name:'Hogar',exact:true}).tap(); + await expect(history.getByRole('listitem')).toHaveCount(0); + await drafts.getByRole('button',{name:'Abrir ' + draftTitle,exact:true}).tap(); + await history.getByRole('button',{name:'Mostrar historial',exact:true}).tap(); + await expect(history.getByRole('listitem')).toHaveCount(25); + await drafts.getByRole('button',{name:'Abrir Inspect the fixture shelf',exact:true}).tap(); + await expect(history.getByRole('listitem')).toHaveCount(0); + await history.getByRole('button',{name:'Mostrar historial',exact:true}).tap(); + await expect(history.getByText('No tienes ejecuciones manuales para esta regla.',{exact:true})).toBeVisible(); }); } diff --git a/frontend/tests/page.test.ts b/frontend/tests/page.test.ts index 2644e32b..8fed6267 100644 --- a/frontend/tests/page.test.ts +++ b/frontend/tests/page.test.ts @@ -75,6 +75,10 @@ function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'e rule_id:'saved-draft', latest_revision:'1', latest_title:automationTitle, control: manualEnabled ? {rule_revision:'1',control_revision:'1',enabled:true,title:automationTitle} : null, }); + else if (route === 'automation/drafts/saved-draft/runs' && init.method === 'GET') raw = JSON.stringify({ + rule_id:'saved-draft',next_cursor:null,items:[{operation_id:'run-operation',created_at:100, + rule_revision:'1',condition_matched:true,task_created:true,historical:false,task_occurrence_id:'work-1'}], + }); else if (route === 'automation/drafts/saved-draft/runs') raw = JSON.stringify({ state:'committed',archived_by:null,operation_id:'run-operation',created_at:100, result:{rule_id:'saved-draft',rule_revision:'1',control_revision:'1',member_id:memberId, @@ -885,7 +889,9 @@ test('Household manual execution binds drafts, original outcomes and task naviga const preview = app.shadowRoot!.querySelector('domus-automation-preview')!; const drafts = app.shadowRoot!.querySelector('domus-automation-drafts')!; const execution = app.shadowRoot!.querySelector('domus-automation-execution')!; + const history = app.shadowRoot!.querySelector('domus-automation-run-history')!; const command = 'domus-automation-execution-intent'; + const historyIntent = 'domus-automation-run-history-intent'; const openTask = 'domus-automation-task-intent'; dispatch(preview, 'domus-automation-preview-intent', {type:'title',value:'Check filters'}); dispatch(drafts, 'domus-automation-draft-intent', {type:'save'}); @@ -909,6 +915,16 @@ test('Household manual execution binds drafts, original outcomes and task naviga result:{action:'run',taskOccurrenceId:'work-1'},busy:false, })); + const historyReads = () => f.fetch.mock.calls.filter(([path, init]) => + path.endsWith('/automation/drafts/saved-draft/runs') && init.method === 'GET'); + dispatch(other, historyIntent, 'open'); + dispatch(history, historyIntent, 'invalid'); + expect(historyReads()).toHaveLength(0); + dispatch(history, historyIntent, 'open'); + await vi.waitFor(() => expect(app.automationRunHistory).toMatchObject({ + phase:'ready',items:[{operationId:'run-operation',taskOccurrenceId:'work-1'}], + })); + expect(historyReads()).toHaveLength(1); dispatch(other, openTask, {type:'select',occurrenceId:'work-1'}); dispatch(execution, openTask, {type:'refresh'}); expect(f.navigation).toHaveLength(0); @@ -918,6 +934,7 @@ test('Household manual execution binds drafts, original outcomes and task naviga path.endsWith('/tasks/occurrences/work-1'))).toBe(true)); navigate('#tasks'); expect(app.automationExecution).toBeNull(); + expect(app.automationRunHistory).toBeNull(); }); test('Overview stock is independently available and retires with the verified household context', async () => { diff --git a/tests/backend/test_automation_execution_storage.py b/tests/backend/test_automation_execution_storage.py index 8a2e4f81..5775c1b6 100644 --- a/tests/backend/test_automation_execution_storage.py +++ b/tests/backend/test_automation_execution_storage.py @@ -2,6 +2,7 @@ import sqlite3 from contextlib import closing +from dataclasses import replace from pathlib import Path import pytest @@ -19,6 +20,7 @@ ConfigureAutomation, RunAutomation, ) +from domus.application.automation_run_history import AutomationRunHistory from domus.application.fixed_materialization import MaintenanceScope from domus.application.task_commands import TaskCommands from domus.domain.automation import AutomationControl, AutomationRule @@ -32,6 +34,7 @@ from domus.infrastructure.sqlite_activation import SQLiteActivation from domus.infrastructure.sqlite_restoration import SQLiteRestorations from domus.infrastructure.sqlite_snapshots import SQLiteSnapshots, _verify_database +from domus.infrastructure.task_cursor import TaskCursor FIXTURES = Path(__file__).parents[1] / "fixtures/sqlite" @@ -113,17 +116,30 @@ def test_runtime_migration_restoration_and_rollback_preserve_exact_outcomes( draft = drafts.save("execution-draft", SaveDraft(None, 0, rule)) rule_id = draft.result.decode()["rule_id"] execution.configure("execution-enable", ConfigureAutomation(rule_id, 1, 0, True)) + request = RunAutomation(rule_id, 1, 1) + current_run = execution.run("before-restore", request) archive, target = tmp_path / "checkpoint", tmp_path / "prepared" snapshotter = SQLiteSnapshots(store, archive, installation, Clock()) checkpoint = snapshotter.create("before-run") assert checkpoint.schema_version == 33 and snapshotter.inspect() == checkpoint - request = RunAutomation(rule_id, 1, 1) complete = execution.run("record-run", request) occurrence_id = complete.result.decode()["task_occurrence_id"] restarted = execution_service(SQLiteDatabase(path, installation)) assert restarted.state(rule_id).control.enabled assert restarted.original(RUN_AUTOMATION, "record-run") == complete assert restarted.run("record-run", request) == complete + history = AutomationRunHistory( + restarted.transactions, + restarted.scope, + restarted.read_actor, + TaskCursor(Clock(), b"s" * 32), + ) + live = history.page(rule_id, limit=25, cursor=None) + assert [run.operation_id for run in live.items] == [ + complete.operation_id, + current_run.operation_id, + ] + assert live.items[0].task_occurrence_id == occurrence_id SQLiteRestorations(store, archive, target, installation, Clock(), checkpoint).prepare( "restore-execution" @@ -138,6 +154,15 @@ def test_runtime_migration_restoration_and_rollback_preserve_exact_outcomes( assert historical == restored.original(RUN_AUTOMATION, "record-run") assert historical.historical and historical.operation_id == complete.operation_id assert historical.result == complete.result + history = AutomationRunHistory( + selected.database, restored.scope, restored.read_actor, TaskCursor(Clock(), b"r" * 32) + ) + selected_head = history.page(rule_id, limit=1, cursor=None) + assert selected_head.items == ( + replace(live.items[0], historical=True, task_occurrence_id=None), + ) + selected_tail = history.page(rule_id, limit=1, cursor=selected_head.next_cursor) + assert selected_tail.items == (live.items[1],) and selected_tail.next_cursor is None with selected.database.read() as unit: assert unit.tasks.occurrence("home", occurrence_id) is None assert all(event.event_id != complete.operation_id for event in unit.outbox.pending()) diff --git a/tests/backend/test_automation_run_history.py b/tests/backend/test_automation_run_history.py new file mode 100644 index 00000000..a864b1f8 --- /dev/null +++ b/tests/backend/test_automation_run_history.py @@ -0,0 +1,261 @@ +"""Protected history reads exact, member-scoped manual automation receipts.""" + +from dataclasses import replace + +import pytest +from test_automation_drafts import DRAFTS, read, save +from test_automation_execution import configure, denied, initial_draft, result, run +from test_automation_preview import USER, leaf, snapshot +from test_inventory_catalog_http import register +from test_rewards_http import member_context +from test_task_runtime import api as api + +from domus.application.automation_run_history import AutomationRunHistory +from domus.application.fixed_materialization import MaintenanceScope +from domus.domain.errors import InvalidInput +from domus.domain.identity import ( + HumanIdentity, + Member, + MemberStatus, + Permission, + PermissionRule, + Role, +) +from domus.domain.storage import JsonDocument, RestorationProvenance +from domus.infrastructure.sqlite_receipts import SQLiteReceipts +from domus.infrastructure.task_cursor import TaskCursor + +OTHER = "b" * 32 + + +def path(rule_id): + return f"{DRAFTS}/{rule_id}/runs" + + +def page(api, rule_id, **query): + response = read(api, path(rule_id), params=query) + assert response.status_code == 200, response.text + return response.json() + + +def operation_ids(payload): + return [item["operation_id"] for item in payload["items"]] + + +def test_pages_are_scoped_to_rule_and_current_invoking_member(api): + rule_id = initial_draft(api) + assert page(api, rule_id) == {"rule_id": rule_id, "items": [], "next_cursor": None} + denied(read(api, path("missing-rule")), 404, "automation_draft_missing") + alternate = result(save(api, "other-draft"))["rule_id"] + result(configure(api, rule_id, "on")) + result(configure(api, alternate, "other-on")) + first = run(api, rule_id, "first").json() + second = run(api, rule_id, "second").json() + other_rule = run(api, alternate, "other-rule").json() + head = page(api, rule_id, limit=1) + assert operation_ids(head) == [second["operation_id"]] + cursor = head["next_cursor"] + denied( + read(api, path(alternate), params={"limit": 1, "cursor": cursor}), + 422, + "invalid_task_cursor", + ) + denied( + read(api, path(rule_id), params={"limit": 2, "cursor": cursor}), 422, "invalid_task_cursor" + ) + denied(read(api, path(rule_id), params={"limit": 0}), 422, "invalid_request") + denied(read(api, path(rule_id), params={"limit": 101}), 422, "invalid_request") + third = run(api, rule_id, "third").json() + next_page = page(api, rule_id, limit=1, cursor=cursor) + assert operation_ids(next_page) == [first["operation_id"]] + assert next_page["next_cursor"] is None + assert operation_ids(page(api, rule_id, limit=100)) == [ + third["operation_id"], + second["operation_id"], + first["operation_id"], + ] + assert operation_ids(page(api, alternate)) == [other_rule["operation_id"]] + + with api.store.write() as unit: + unit.members.save( + Member("second-admin", "home", OTHER, Role.ADMINISTRATOR, MemberStatus.ACTIVE, 1), 0 + ) + api.user(OTHER, True) + context = member_context(OTHER) + assert api.client.get(path(rule_id), headers=context).json()["items"] == [] + unrelated = api.client.post( + path(rule_id), + json={"rule_revision": "1", "control_revision": "1"}, + headers=api.headers("second-admin-run") | context, + ) + result(unrelated) + assert operation_ids(api.client.get(path(rule_id), headers=context).json()) == [ + unrelated.json()["operation_id"] + ] + denied( + api.client.get(path(rule_id), params={"limit": 1, "cursor": cursor}, headers=context), + 422, + "invalid_task_cursor", + ) + + api.user(USER, True) + before = snapshot(api) + assert operation_ids(page(api, rule_id)) == [ + third["operation_id"], + second["operation_id"], + first["operation_id"], + ] + assert snapshot(api) == before + api.user(USER, False) + denied( + read(api, path(rule_id), params={"limit": 1, "cursor": cursor}), 403, "permission_denied" + ) + denied(read(api, path(rule_id)), 403, "permission_denied") + + +def test_original_stock_decisions_and_task_privacy_survive_edits_and_disable(api): + rule_id = initial_draft(api) + result(configure(api, rule_id, "enable")) + matched = run(api, rule_id, "matched").json() + old_task = matched["result"]["task_occurrence_id"] + product = register(api, "product", "Tea", "piece") + stock = leaf(product) + condition = {"kind": "all", "children": [stock, {"kind": "not", "child": stock}]} + result(save(api, "change", rule_id=rule_id, revision="1", condition=condition)) + result(configure(api, rule_id, "activate-change", revision="2", expected="1")) + unmatched = run(api, rule_id, "unmatched", revision="2", control="2").json() + result(configure(api, rule_id, "turn-off", revision="2", expected="2", enabled=False)) + rows = page(api, rule_id)["items"] + assert rows == [ + { + "operation_id": unmatched["operation_id"], + "created_at": unmatched["created_at"], + "rule_revision": "2", + "condition_matched": False, + "task_created": False, + "historical": False, + "task_occurrence_id": None, + }, + { + "operation_id": matched["operation_id"], + "created_at": matched["created_at"], + "rule_revision": "1", + "condition_matched": True, + "task_created": True, + "historical": False, + "task_occurrence_id": old_task, + }, + ] + assert read(api, f"/api/v1/tasks/occurrences/{old_task}").status_code == 200 + with api.store.write() as unit: + member = unit.members.by_user("home", USER) + unit.members.save( + replace( + member, + exceptions=(PermissionRule(Permission.TASKS_READ, False),), + revision=member.revision + 1, + ), + member.revision, + ) + assert page(api, rule_id)["items"] == [rows[0], rows[1] | {"task_occurrence_id": None}] + denied(read(api, f"/api/v1/tasks/occurrences/{old_task}"), 403, "permission_denied") + + +class AdjustableClock: + now_ms = 100 + + def now(self): + return self.now_ms + + +def service(api, clock, key=b"s" * 32, household_id="home"): + return AutomationRunHistory( + api.store, + MaintenanceScope(api.store.installation, household_id), + lambda: HumanIdentity(USER, True, True, False), + TaskCursor(clock, key), + ) + + +def test_cursor_expiry_restart_and_marker_validation(api): + rule_id = initial_draft(api) + result(configure(api, rule_id, "enable")) + result(run(api, rule_id, "first")) + result(run(api, rule_id, "second")) + clock = AdjustableClock() + history = service(api, clock) + first = history.page(rule_id, limit=1, cursor=None) + with pytest.raises(InvalidInput, match="invalid_task_cursor"): + service(api, clock, b"r" * 32).page(rule_id, limit=1, cursor=first.next_cursor) + invalid_markers = ("1x", "0", "01", str(2**63)) + binding = JsonDocument.from_value( + { + "query": "manual-automation-runs-v1", + "installation": api.store.installation.instance_id, + "channel": "edge", + "household": "home", + "actor": USER, + "member": result(run(api, rule_id, "first"))["member_id"], + "rule": rule_id, + "limit": 1, + } + ) + for marker in invalid_markers: + token = history.cursors.encode(binding, marker) + with pytest.raises(InvalidInput, match="invalid_task_cursor"): + history.page(rule_id, limit=1, cursor=token) + for size in (True, 0, 101): + with pytest.raises(InvalidInput, match="invalid_page_size"): + history.page(rule_id, limit=size, cursor=None) + clock.now_ms += 300_000 + with pytest.raises(InvalidInput, match="invalid_task_cursor"): + history.page(rule_id, limit=1, cursor=first.next_cursor) + assert history.page(rule_id, limit=1, cursor=None).items == first.items + + +@pytest.mark.parametrize( + "changes", + ( + {"rule_revision": None}, + {"rule_revision": "01"}, + {"rule_revision": "unexpected"}, + {"rule_revision": "0"}, + {"condition_matched": None}, + {"condition_matched": False}, + {"task_occurrence_id": None}, + {"task_operation_id": None}, + {"task_occurrence_id": "bad id"}, + {"task_operation_id": "bad id"}, + ), +) +def test_corrupt_receipt_cannot_publish_an_invented_outcome(api, monkeypatch, changes): + rule_id = initial_draft(api) + result(configure(api, rule_id, "enable")) + result(run(api, rule_id, "manual")) + load = SQLiteReceipts.get_operation + + def corrupt(self, *args): + receipt = load(self, *args) + return replace(receipt, result=JsonDocument.from_value(receipt.result.decode() | changes)) + + monkeypatch.setattr(SQLiteReceipts, "get_operation", corrupt) + response = read(api, path(rule_id)) + denied(response, 500, "internal_error") + assert "bad id" not in response.text + + +@pytest.mark.parametrize("missing", [True, False]) +def test_mismatched_current_or_retained_projection_fails_closed(api, monkeypatch, missing): + rule_id = initial_draft(api) + result(configure(api, rule_id, "enable")) + result(run(api, rule_id, "manual")) + load = SQLiteReceipts.get_operation + + def corrupt(self, *args): + if missing: + return None + receipt = load(self, *args) + return replace(receipt, restoration=RestorationProvenance("restore", False)) + + monkeypatch.setattr(SQLiteReceipts, "get_operation", corrupt) + denied(read(api, path(rule_id)), 500, "internal_error") From fbe731bcccdcf2c0d20532bd999779330b1aa596 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Wed, 18 Nov 2026 09:32:04 +0100 Subject: [PATCH 3/6] build(edge): pin manual run history preview --- addon-edge/CHANGELOG.md | 4 ++++ addon-edge/DOCS.md | 7 ++++--- addon-edge/Dockerfile | 8 ++++---- addon-edge/artifact.json | 27 ++++++++++++++------------- addon-edge/config.yaml | 2 +- tests/backend/test_app_package.py | 16 ++++++++-------- 6 files changed, 35 insertions(+), 29 deletions(-) diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md index 135cba03..e30eeec6 100644 --- a/addon-edge/CHANGELOG.md +++ b/addon-edge/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.0.0-edge.39 + +- Review your previous manual automation runs from the saved rule, including the original task outcome and retained results from before restoration. + ## 0.0.0-edge.38 - Enable a saved manual automation revision, run it with an original receipt, and disable future runs. diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md index 3b05bebd..622d7f68 100644 --- a/addon-edge/DOCS.md +++ b/addon-edge/DOCS.md @@ -1,6 +1,6 @@ # Installation and operation -Edge 0.0.0-edge.38 packages the immutable runtime declared in +Edge 0.0.0-edge.39 packages the immutable runtime declared in [artifact.json](artifact.json). Overview shows the signed-in member's completed tasks and posted earned points for the current Family week. Open Family for the full report. In Household settings, authorized members can preview a manual task proposal and @@ -20,8 +20,9 @@ the optional `ha_deadline_digest` setting. The calendar uses its own `ha_calendar_digest` setting. Both share the private app port `8100` when enabled. Enable a saved revision in Manual automation and confirm it before running. The run receipt links to its task when the stock condition matches. Check -the original request after an interrupted response. -Edge.38 introduces SQLite schema 33 and is listed in `breaking_versions`. +the original request after an interrupted response. Show run history lists +your own previous runs of the selected rule, with older pages on demand. +Edge.39 uses SQLite schema 33. Edge.38 introduced SQLite schema 33 and is listed in `breaking_versions`. Keep a compatible image and stopped-app backup before upgrading from an earlier schema. A binary that expects the earlier schema requires its compatible data backup. diff --git a/addon-edge/Dockerfile b/addon-edge/Dockerfile index 8c1d67fa..6d14cdbd 100644 --- a/addon-edge/Dockerfile +++ b/addon-edge/Dockerfile @@ -1,8 +1,8 @@ # The Supervisor builds this folder. Fetch only the reviewed immutable runtime and UI. FROM ghcr.io/astral-sh/uv:0.11.29@sha256:eb2843a1e56fd9e30c7276ce1a52cba86e64c7b385f5e3279a0e08e02dd058fc AS uv FROM python:3.14.6-slim-trixie@sha256:7bec7ddcddeff7975d6ba9b4be7dd6f6b2f55e7491539145e2978f7f97ce9144 AS source -ARG DOMUS_SOURCE_COMMIT=fee2e9695b5f7b648c38dbb550038614f30095d4 -ARG DOMUS_SOURCE_SHA256=32920033aef3f2efb021b82dbbc5abb04475952628eb5d0ff794f791945f5a71 +ARG DOMUS_SOURCE_COMMIT=eba168e88dedd7ddd6f84ea712094ca464a76f27 +ARG DOMUS_SOURCE_SHA256=b6164754b7c63e05ca4880974537f66d0ab4d86180b7a5c8cc88938c5ba247d6 ADD https://codeload.github.com/vypdev/domus/tar.gz/${DOMUS_SOURCE_COMMIT} /tmp/source.tar.gz RUN printf '%s /tmp/source.tar.gz\n' "$DOMUS_SOURCE_SHA256" | sha256sum --check - \ && mkdir /app \ @@ -24,9 +24,9 @@ RUN uv sync --frozen --no-dev --package domus-server --no-editable RUN .venv/bin/python -c "from pathlib import Path; import domus; from domus.entrypoints.ui_bundle import load_bundle; assert load_bundle(Path(domus.__file__).parent / 'ui') is not None" FROM python:3.14.6-slim-trixie@sha256:7bec7ddcddeff7975d6ba9b4be7dd6f6b2f55e7491539145e2978f7f97ce9144 -ARG BUILD_VERSION=0.0.0-edge.38 +ARG BUILD_VERSION=0.0.0-edge.39 ARG BUILD_ARCH -ARG DOMUS_SOURCE_COMMIT=fee2e9695b5f7b648c38dbb550038614f30095d4 +ARG DOMUS_SOURCE_COMMIT=eba168e88dedd7ddd6f84ea712094ca464a76f27 LABEL io.hass.type="app" \ io.hass.version="${BUILD_VERSION}" \ io.hass.arch="${BUILD_ARCH}" \ diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json index 5da3fb51..1ece28cf 100644 --- a/addon-edge/artifact.json +++ b/addon-edge/artifact.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, - "version": "0.0.0-edge.38", - "sourceCommit": "fee2e9695b5f7b648c38dbb550038614f30095d4", - "sourceArchiveSHA256": "32920033aef3f2efb021b82dbbc5abb04475952628eb5d0ff794f791945f5a71", + "version": "0.0.0-edge.39", + "sourceCommit": "eba168e88dedd7ddd6f84ea712094ca464a76f27", + "sourceArchiveSHA256": "b6164754b7c63e05ca4880974537f66d0ab4d86180b7a5c8cc88938c5ba247d6", "storageSchema": 33, - "wheelSHA256": "0c900758ed64a861cdd7a398d526a1012612233699f1921782ee77d503662a9f", + "wheelSHA256": "e6e7a89e7845bcaeb1a6d7994e6041084343d7dc7fb765a60d8f6430c4df8bbb", "pythonFiles": { "domus/__init__.py": "7182c88b92234b4328f94497f4e70222d4390d8093e4b62893dfa78ac5530ac6", "domus/application/__init__.py": "1e8c0c87bf2a8ca947112543070583c0cc55d9d40b56eab0d86ed59a4ec1e82c", @@ -16,6 +16,7 @@ "domus/application/automation_drafts.py": "4dd7a3f4225c91580fc2ac8deb8831238b5bb2e9a32af5de71bbdaa5376b117b", "domus/application/automation_execution.py": "7e14ea9afa73a8ce3f3fb1ac373e9c13140eb1a08f6d7f3b1999d5fb036cb471", "domus/application/automation_preview.py": "94289b9a6a5deb42ca4e82b430724e27d1bf53239b1d60b48c332a6ed854707f", + "domus/application/automation_run_history.py": "8b1b5de75b97920874a23e3df8b08483ea3a19cc6971163b61eb829b13280ac8", "domus/application/calendar_commands.py": "bec257c2b7ba07166e69b1dd7ed0016541cd30ab6cb26f18f4fc4dce11017001", "domus/application/calendar_queries.py": "37b9b8f1d43d9a21cc73c2533a908570783116ff7e5b6db47d6591dfbe2393d9", "domus/application/commands.py": "b41069d5db23e594f135bc742f2479e25fce537dc0966052546d95409dc7bc05", @@ -49,7 +50,7 @@ "domus/application/points.py": "a2a660198151d5b65a62b57cb90b35a82a28f38a9a3b7b214b49d6cf6cf0294e", "domus/application/points_ports.py": "8392b778007d4c55bc55498d38c959d6dc1d4eeaa1dc501cf4d4928ce09f4ac0", "domus/application/policy_commands.py": "bc588b5b5feb72fd5cb57d7b4a10ef5a05ae48da5ec042fd569142ce50fedeb6", - "domus/application/ports.py": "e73f85562b7c86b4692797415c1bfa5d00c19510d0fed9f9b41f8c227ceae287", + "domus/application/ports.py": "f8ab345f3acd5cd8d95c9787d237221c63d45a011a632f4f6246f368c37c80e6", "domus/application/recovery_commands.py": "2b8c198cde97f0213ec1612ea32bce5e00637aab99862fe08b59418d3c64af49", "domus/application/recurrence_commands.py": "4d91c498ced40c335b8a081719a33dde97ab081a050ab352c3f1fac83e6f1447", "domus/application/recurrence_ports.py": "651d86417a20810c198aba0cd48129de6396db185278c01836366575027d6c24", @@ -100,7 +101,7 @@ "domus/composition/recurrence.py": "62adda116cec8667e9142b03f422a138818575cf5814a79e219a65999dbed1e6", "domus/composition/restore.py": "fe4f5040a99db1404938e402eefa54fc93139055a5bc92abdfb7bf35d0c87297", "domus/composition/server.py": "f857338e254477cd7b1d452fc85434e75fd7a25781ed237bb0d5658ac13ad719", - "domus/composition/tasks.py": "5869ad675ef3c49a4c9d63780e6d667d09b76c69b4fbd6047b61e545713fb0e9", + "domus/composition/tasks.py": "1aeddf554d8b25182df653fcf7b4e6ffe5cf5bda5512cc9ad9578abdf7c8b4d8", "domus/domain/__init__.py": "0aac8a2ba41471d7a174ef7baca6073c95009a9db96df3e032392aa4f80bd079", "domus/domain/activation.py": "fcb2e47e939127d5e254e2136fb7f1459b40fa8c8561100579fced49666ad0fe", "domus/domain/automation.py": "6ba1e359240ed89115fbb0499160c3e1931d5e451ea18624bf15dad08b5036aa", @@ -144,7 +145,7 @@ "domus/entrypoints/__init__.py": "d46875cbfef7220c7244bf1b89112ece8122ecb0d66cd908f08f098f0f3c419f", "domus/entrypoints/administration_dto.py": "aefac6648dd8fefae9d2366abed1c9d595c24a356f7caf945b742043b2c39777", "domus/entrypoints/administration_http.py": "9ab62ee9759a4b31c5e994354562b48b947bd3428a5866dd9faeb0545ae37afe", - "domus/entrypoints/automation_http.py": "0b32b23adcb174723d736178d447243807b9ca574e9577f938f4e3d6e2188af4", + "domus/entrypoints/automation_http.py": "95a9e6cc02c30c8f658fea1fb6ff8c6ecb71869003156e412c7f9a51604b93cc", "domus/entrypoints/bounded_http.py": "d8047746eddb7193f1aa9f16007958c79cc6ae7ac1c30ab93909883e3aa97b54", "domus/entrypoints/calendar_http.py": "5a7359ac2a876296a13bfe4bc63ac69bd36aec48e55c536a20470a789a6fef13", "domus/entrypoints/console_recovery.py": "854a3f8d7a2e74f301ac5bd4b54682e409e2669a3bb7e05546e479c113c09026", @@ -160,7 +161,7 @@ "domus/entrypoints/ingress_boundary.py": "1aa1d684b8625464b5d36d272f71d94b4cd32b84819ff8765a821c9a722f8f28", "domus/entrypoints/ingress_http.py": "f6557eb5481d132131f66ad7691e30c223c63a66a6f0ae5754c9fba3bc7f3626", "domus/entrypoints/inventory_http.py": "a58e114de6ff684f6d7d1a93f7f4cb316b8ffa60b0c662733df2c1fd70c2ab6e", - "domus/entrypoints/native_http.py": "68aa8a19bc303345dec44cb67dfc3855cc4d4be9cbe8143b6c63859b8f9f2def", + "domus/entrypoints/native_http.py": "d6d8c06095b9128ea316a2dcb2f7cb0ac1559c29ef28dad8d9d70150a69aac15", "domus/entrypoints/openapi.py": "01a3fab9e5890ebcc1fb9c70bce9ced43d45b9190afd134db7dd45e0c5eb28f1", "domus/entrypoints/point_allocation_http.py": "7339c88c083206c0778885b55793c80af219b15af7004c5a51d34dbc28f4da5c", "domus/entrypoints/recurrence_dto.py": "094e6f64e1f963bfb053e830b214eed1189258e4f0eb8ff15ddba1f059649a1a", @@ -169,7 +170,7 @@ "domus/entrypoints/schedule_creation_http.py": "2a3c3ea682f978eb2767dc8808a218c312861f31079cc2c76dbc3847ddec3197", "domus/entrypoints/task_category_http.py": "e5443015f5e5cb2684eb6807e0a3bac5116703b5611508281afd7d1addee9672", "domus/entrypoints/task_dto.py": "10657d1df0180bf05e71d1f38ac3214d2cea34c8822f50ea25ab331b9c014049", - "domus/entrypoints/task_http.py": "4ae65072cbeb4b4e060ac9b8c6a6c04a018b501b2ddef2c6f9aabb1d65390b96", + "domus/entrypoints/task_http.py": "a1182b29378346fb9822113f1296e497c5a90985045d0f7c577506235f827bf8", "domus/entrypoints/task_response.py": "d2f4c0795aee429fc318b32495601031c559fa38af1d7da63b4735f7e6eb5d13", "domus/entrypoints/ui_bundle.py": "beae3d4a7a57375ee195cca81efccdbc899d9db4286029d53eabaf30de6e14f7", "domus/entrypoints/ui_http.py": "b6c47baa742f3862173a93e4121dc9914fd972eb6287ffffb9ffccecbf2ebe4a", @@ -204,7 +205,7 @@ "domus/infrastructure/sqlite_member_profiles.py": "db7be5e4209d408f2fd780f684ba3a0a76267347fd2cbc0521a33c06e5453ec5", "domus/infrastructure/sqlite_point_allocations.py": "e1aa5075544bf5faf16dac92fc0655c82fc65a3b5495fc916dc33769168c8bd5", "domus/infrastructure/sqlite_points.py": "5ca24ac9c135e676968e15ab8d7a17e5f2cd12bf9cd0b4fee53a3542d2da0236", - "domus/infrastructure/sqlite_receipts.py": "0c7abbc6bcce8b1550e97da54c42701bc2dc5c6280cf61e3370a53ce6839745c", + "domus/infrastructure/sqlite_receipts.py": "0e972eda2076e71226bd3387b77c1bd63626f85800ec4ea6e2f2abfea849916d", "domus/infrastructure/sqlite_recovery.py": "01fa6b8896674ce8203073c468eccb7033a9824052d7db3a853c80a2df6e2650", "domus/infrastructure/sqlite_recurrence.py": "5f74818f6f711b9bd4c02ff1661b536e7e87af202bf711e32a50a200c7d297a4", "domus/infrastructure/sqlite_recurrence_integrity.py": "b69d15222964e9d6e44d6cfb22501de47f1efd12383ff4a7a141c206ffcd3752", @@ -233,9 +234,9 @@ "domus/infrastructure/task_materials.py": "d5d2934e36f290c7bf44b473392f014eab8749f1f3b3d26a3402079e65d2818f" }, "uiFiles": { - ".vite/manifest.json": "0668970d07960016c3d9d24807f6ffdbd3e9aad8fedf67b0e46745316e0d2982", - "assets/index-Bq58zfmH.js": "e662150cb70518dd642a80be62c0ad15bc8ef3fd54c9b12ba138ffbc9fb44356", + ".vite/manifest.json": "1b8638ee43b130fa6079e26eef3500cc09ba55b12fc59b6249ed6f989672729b", + "assets/index-Cg8YDLuZ.js": "d26b6cbf67e74ebcfb0480902a547cb44f77c5ef667286ecb1b40352ba1ca364", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "be33a29f23894572c40532edb4128495f808ac8fb5b79b99f3a68a231a2949dc" + "index.html": "3f9c12f5ab3b63c8c395905b0dac7f1d9e9004a5a73263238c97f4e05f0ebfe1" } } diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml index 7492b631..97aaad14 100644 --- a/addon-edge/config.yaml +++ b/addon-edge/config.yaml @@ -1,5 +1,5 @@ name: Domus Edge -version: "0.0.0-edge.38" +version: "0.0.0-edge.39" slug: domus_edge description: Development preview of the local Domus household application url: https://github.com/vypdev/domus diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py index 6b1e4c6c..f148a497 100644 --- a/tests/backend/test_app_package.py +++ b/tests/backend/test_app_package.py @@ -15,7 +15,7 @@ def test_repository_and_edge_manifest_offer_native_ha_entry_without_user_credent manifest = yaml.safe_load((ROOT / "addon-edge/config.yaml").read_text()) assert repository["url"] == "https://github.com/vypdev/domus" assert manifest["slug"] == "domus_edge" and manifest["stage"] == "experimental" - assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.38" + assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.39" assert manifest["ingress"] is True and manifest["ingress_port"] == 8099 assert manifest["panel_admin"] is False and manifest["homeassistant_api"] is True assert manifest["options"] == {"public_origins": []} @@ -60,15 +60,15 @@ def test_build_pins_source_checksum_bases_lock_and_nonroot_native_entrypoint() - commits = re.findall(r"^ARG DOMUS_SOURCE_COMMIT=(\w+)$", source, re.MULTILINE) assert len(commits) == 2 and len(set(commits)) == 1 assert re.fullmatch(r"[a-f0-9]{40}", commits[0]) - assert commits[0] == "fee2e9695b5f7b648c38dbb550038614f30095d4" + assert commits[0] == "eba168e88dedd7ddd6f84ea712094ca464a76f27" assert ( - "DOMUS_SOURCE_SHA256=32920033aef3f2efb021b82dbbc5abb04475952628eb5d0ff794f791945f5a71" + "DOMUS_SOURCE_SHA256=b6164754b7c63e05ca4880974537f66d0ab4d86180b7a5c8cc88938c5ba247d6" in source ) - assert "ARG BUILD_VERSION=0.0.0-edge.38" in source + assert "ARG BUILD_VERSION=0.0.0-edge.39" in source candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text()) assert candidate["sourceCommit"] == commits[0] - assert candidate["version"] == "0.0.0-edge.38" + assert candidate["version"] == "0.0.0-edge.39" assert "DOMUS_SOURCE_SHA256=" + candidate["sourceArchiveSHA256"] in source assert re.search(r"^ARG DOMUS_SOURCE_SHA256=[a-f0-9]{64}$", source, re.MULTILINE) assert "sha256sum --check" in source @@ -142,12 +142,12 @@ def test_edge_artifact_declares_exact_reviewed_runtime_without_rebinding_histori "pythonFiles", "uiFiles", } - assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.38" - assert artifact["sourceCommit"] == "fee2e9695b5f7b648c38dbb550038614f30095d4" + assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.39" + assert artifact["sourceCommit"] == "eba168e88dedd7ddd6f84ea712094ca464a76f27" assert artifact["storageSchema"] == 33 for field in ["sourceArchiveSHA256", "wheelSHA256"]: assert re.fullmatch("[a-f0-9]{64}", artifact[field]) - assert len(artifact["pythonFiles"]) == 225 and len(artifact["uiFiles"]) == 4 + assert len(artifact["pythonFiles"]) == 226 and len(artifact["uiFiles"]) == 4 for name, digest in artifact["pythonFiles"].items(): assert re.fullmatch(r"domus/(?:[A-Za-z0-9_]+/)*[A-Za-z0-9_]+\.py", name) assert re.fullmatch("[a-f0-9]{64}", digest) From e68c1735c77fcec9d7195d50943908a048042d17 Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Wed, 18 Nov 2026 09:41:26 +0100 Subject: [PATCH 4/6] test(automation): verify the current run history assets --- .../evidence/task-navigation-integration.json | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json index d4ba5100..dee0b4f5 100644 --- a/docs/evidence/task-navigation-integration.json +++ b/docs/evidence/task-navigation-integration.json @@ -3,12 +3,12 @@ "historicalTaskHead": "8c0a36c0b9804bdaf33a301a4dc85ae3dc12ee21", "developParent": "5b7bdcdee3a9e98d6669bfd34ce750ae30a8c775", "command": "pnpm build:frontend", - "scope": "Compiled household workspace with a protected manual task automation preview and inactive saved revisions, upcoming maintenance, due today, overdue, assigned and unclaimed task summaries, products below their replenishment minimum, outstanding shopping items, weekly Family participation, optional task base points, native deadline sensor integration, protected Pantry, shared Shopping, purchase sessions with an optional store, receipt corrections, physical returns, stock locations, transfers and original operation recovery in English and Spanish.", + "scope": "Compiled household workspace with protected manual automation preview, saved revisions, explicit runs and scoped run history, upcoming maintenance, due today, overdue, assigned and unclaimed task summaries, products below their replenishment minimum, outstanding shopping items, weekly Family participation, optional task base points, native deadline sensor integration, protected Pantry, shared Shopping, purchase sessions with an optional store, receipt corrections, physical returns, stock locations, transfers and original operation recovery in English and Spanish.", "actualProductFiles": { - ".vite/manifest.json": "0668970d07960016c3d9d24807f6ffdbd3e9aad8fedf67b0e46745316e0d2982", - "assets/index-Bq58zfmH.js": "e662150cb70518dd642a80be62c0ad15bc8ef3fd54c9b12ba138ffbc9fb44356", + ".vite/manifest.json": "1b8638ee43b130fa6079e26eef3500cc09ba55b12fc59b6249ed6f989672729b", + "assets/index-Cg8YDLuZ.js": "d26b6cbf67e74ebcfb0480902a547cb44f77c5ef667286ecb1b40352ba1ca364", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "be33a29f23894572c40532edb4128495f808ac8fb5b79b99f3a68a231a2949dc" + "index.html": "3f9c12f5ab3b63c8c395905b0dac7f1d9e9004a5a73263238c97f4e05f0ebfe1" }, "localValidation": { "commit": "9a10d8114869be754962953903e773fe8e12c723", @@ -272,5 +272,16 @@ }, "requirements": "SDD-I120-U1-R1 through SDD-I120-U1-R6", "evidence": "automation-execution-qualification.md" + }, + "manualAutomationRunHistory": { + "sourceCommit": "eba168e88dedd7ddd6f84ea712094ca464a76f27", + "actualProductFiles": { + ".vite/manifest.json": "1b8638ee43b130fa6079e26eef3500cc09ba55b12fc59b6249ed6f989672729b", + "assets/index-Cg8YDLuZ.js": "d26b6cbf67e74ebcfb0480902a547cb44f77c5ef667286ecb1b40352ba1ca364", + "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", + "index.html": "3f9c12f5ab3b63c8c395905b0dac7f1d9e9004a5a73263238c97f4e05f0ebfe1" + }, + "requirements": "manual-run-history-R01 through manual-run-history-R06", + "evidence": "automation-run-history-qualification.md" } } From 50aa7190e4d910c8bea5e35658314279db284e3b Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Wed, 18 Nov 2026 10:04:24 +0100 Subject: [PATCH 5/6] fix(automation): retire history after authorization changes --- .../src/application/automation-run-history.ts | 10 ++++--- frontend/src/composition/entry-page.ts | 15 +++++++---- frontend/tests/automation-run-history.test.ts | 26 ++++++++++++++++--- frontend/tests/page.test.ts | 10 ++++++- 4 files changed, 49 insertions(+), 12 deletions(-) diff --git a/frontend/src/application/automation-run-history.ts b/frontend/src/application/automation-run-history.ts index c7223ac6..46e8b70d 100644 --- a/frontend/src/application/automation-run-history.ts +++ b/frontend/src/application/automation-run-history.ts @@ -26,7 +26,11 @@ export interface AutomationRunHistoryView { readonly timeZone: string; } -type Selection = Readonly<{scope: DraftScope; ruleId: string; timeZone: string}>; +export interface AutomationRunHistoryScope extends DraftScope { + readonly authorization: string; +} + +type Selection = Readonly<{scope: AutomationRunHistoryScope; ruleId: string; timeZone: string}>; export class AutomationRunHistoryController { private selection: Selection | null = null; @@ -38,13 +42,13 @@ export class AutomationRunHistoryController { constructor(private readonly server: AutomationRunHistoryServer, private readonly publish: (view: AutomationRunHistoryView | null) => void) {} - bind(scope: DraftScope | null, ruleId: string | null, timeZone: string | null): void { + bind(scope: AutomationRunHistoryScope | null, ruleId: string | null, timeZone: string | null): void { const previous = this.selection; if (scope === null || ruleId === null || timeZone === null) { this.selection = null; this.clear(null); } else if (previous?.scope.key !== scope.key || previous.scope.readOnly !== scope.readOnly - || previous.ruleId !== ruleId || previous.timeZone !== timeZone) { + || previous.scope.authorization !== scope.authorization || previous.ruleId !== ruleId || previous.timeZone !== timeZone) { this.selection = {scope, ruleId, timeZone}; this.clear(timeZone); } diff --git a/frontend/src/composition/entry-page.ts b/frontend/src/composition/entry-page.ts index ed5291cd..6ba6bb6b 100644 --- a/frontend/src/composition/entry-page.ts +++ b/frontend/src/composition/entry-page.ts @@ -10,7 +10,7 @@ import {AutomationDraftController} from '../application/automation-drafts'; import type {AutomationDraftIntent, AutomationDraftView, DraftScope} from '../application/automation-drafts'; import {HttpAutomationRunHistory} from '../adapters/automation-run-history-http'; import {AutomationRunHistoryController} from '../application/automation-run-history'; -import type {AutomationRunHistoryIntent} from '../application/automation-run-history'; +import type {AutomationRunHistoryIntent, AutomationRunHistoryScope} from '../application/automation-run-history'; import {HttpAutomationExecution} from '../adapters/automation-execution-http'; import {AutomationExecutionSessionJournal} from '../adapters/automation-execution-journal'; import {AutomationExecutionController} from '../application/automation-execution'; @@ -517,10 +517,11 @@ export function mountEntry(page: EntryPage): PageMount { view => {element.automationRunHistory = view;}); automationRunHistory = runHistory; let executionScope: DraftScope | null = null; + let historyScope: AutomationRunHistoryScope | null = null; const syncExecution = (view: AutomationDraftView | null) => { const selected = view?.state === 'ready' ? view.selected : null; execution.bind(view?.state === 'ready' ? executionScope : null, selected); - runHistory.bind(executionScope, selected?.id ?? null, element.view?.household?.timeZone ?? null); + runHistory.bind(historyScope, selected?.id ?? null, element.view?.household?.timeZone ?? null); }; const drafts = new AutomationDraftController(new HttpAutomationDrafts(source.target, browser.transport), new AutomationDraftSessionJournal({getItem:key => browser.storage().getItem(key), @@ -531,19 +532,23 @@ export function mountEntry(page: EntryPage): PageMount { }); automationDrafts = drafts; const syncAutomation = () => { - const entry = element.view, member = element.administration?.access?.member; + const entry = element.view, access = element.administration?.access, member = access?.member; if (entry?.phase === 'ready' && entry.notice !== 'context_changed' && entry.decision?.householdReadable - && entry.session && entry.household && member) { + && entry.session && entry.household && access && member) { const {context} = entry.session, {householdId} = entry.household; const key = JSON.stringify([context.installationId, context.channel, context.subject, householdId, member.memberId]); const visible = element.workspaceDestination === 'household', readOnly = entry.decision.readOnly; const draftScope = {key, context, memberId: member.memberId, readOnly}; executionScope = visible ? draftScope : null; + const automationGrants = ['automations.configure', 'tasks.create', 'tasks.read'] + .map(permission => access.permissions.includes(permission)); + const authorization = JSON.stringify([member.revision, access.policyRevision, access.effectiveRole, ...automationGrants]); + historyScope = visible ? {...draftScope, authorization} : null; automation.bind({key, context, householdId, readOnly}, visible); drafts.bind(draftScope, visible); syncExecution(element.automationDrafts); } else { - executionScope = null; + executionScope = null; historyScope = null; automation.bind(null); drafts.bind(null); syncExecution(null); } }; diff --git a/frontend/tests/automation-run-history.test.ts b/frontend/tests/automation-run-history.test.ts index 7202059c..ff5eaf14 100644 --- a/frontend/tests/automation-run-history.test.ts +++ b/frontend/tests/automation-run-history.test.ts @@ -1,15 +1,14 @@ import {afterEach, expect, test, vi} from 'vitest'; import {HttpAutomationRunHistory} from '../src/adapters/automation-run-history-http'; -import type {DraftScope} from '../src/application/automation-drafts'; import {AutomationRunHistoryController} from '../src/application/automation-run-history'; -import type {AutomationRun, AutomationRunHistoryServer, AutomationRunHistoryView, AutomationRunPage} +import type {AutomationRun, AutomationRunHistoryScope, AutomationRunHistoryServer, AutomationRunHistoryView, AutomationRunPage} from '../src/application/automation-run-history'; import {EntryReadError} from '../src/application/ports'; import type {EntryRead} from '../src/application/ports'; import {revisionValue} from '../src/domain/administration'; import '../src/presentation/domus-automation-run-history'; -const scope: DraftScope = {key: 'home-owner', memberId: 'member', readOnly: false, +const scope: AutomationRunHistoryScope = {key: 'home-owner', memberId: 'member', readOnly: false, authorization: 'member-1-policy-1', context: {installationId: '01234567-89ab-cdef-0123-456789abcdef', channel: 'edge', subject: 'a'.repeat(32)}}; const made: AutomationRun = {operationId: 'made', revision: revisionValue('1'), time: 1000, taskCreated: true, historical: false, taskOccurrenceId: 'task'}; @@ -110,6 +109,27 @@ test('scope and rule changes cancel stale results and current access denial clea f.history.bind(null, null, null); }); +test('a verified access change retires an open history with the same member and rule', async () => { + const f = fixture(); + f.history.bind(scope, 'rule', 'UTC'); + await f.history.handle('open'); + const pending = Promise.withResolvers(); + const cancel = vi.fn(); + f.page.mockReturnValueOnce({result: pending.promise, cancel}); + const read = f.history.handle('older'); + const updated = {...scope, authorization: 'member-2-policy-1'}; + f.history.bind(updated, 'rule', 'UTC'); + expect(f.last()).toMatchObject({phase: 'closed', items: []}); + pending.resolve(older); + await read; + expect(cancel).toHaveBeenCalledOnce(); + expect(f.last()?.items).toEqual([]); + f.page.mockReturnValueOnce(failed(new EntryReadError('forbidden'))); + await f.history.handle('open'); + expect(f.page).toHaveBeenLastCalledWith(updated, 'rule', null); + expect(f.last()).toMatchObject({phase: 'denied', items: []}); +}); + const target = {origin: 'https://domus.local', applicationBase: '/', deployment: 'standalone'} as const; const wire = {operation_id: 'made', created_at: 1000, rule_revision: '1', condition_matched: true, task_created: true, historical: false, task_occurrence_id: 'task'}; diff --git a/frontend/tests/page.test.ts b/frontend/tests/page.test.ts index 8fed6267..c8e9dcb3 100644 --- a/frontend/tests/page.test.ts +++ b/frontend/tests/page.test.ts @@ -37,6 +37,7 @@ function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'e let automationTitle: string | null = null; const automationDraft = {rule_id:'saved-draft',revision:'1',state:'draft',enabled:false}; let manualEnabled = false; + let memberRevision = 1, policyRevision = 1; const shoppingItem = {product_id:'product',extra_id:null,name:'Salt',base_unit:'gram',total:'1.000001'}; const originalAccess=JSON.parse(wire.active); let preferenceReceipt:Record|null=null; @@ -48,7 +49,8 @@ function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'e const route = path.slice(wire.endpoint.applicationBase.length + 'api/v1/'.length); let raw: string, status = 200; if (route === 'session') raw = phase === 'eligible' || phase === 'pending' ? wire.participantSession : sessionBody; - else if (route === 'authorization') raw = phase === 'active' ? JSON.stringify({...originalAccess,member:{...originalAccess.member,member_id:memberId}, + else if (route === 'authorization') raw = phase === 'active' ? JSON.stringify({...originalAccess,policy_revision:policyRevision, + member:{...originalAccess.member,member_id:memberId,revision:memberRevision}, permissions:originalAccess.permissions.filter((permission:string)=>preferencesReadable||permission!=='preferences.read')}) : phase === 'eligible' ? wire.eligible : phase === 'pending' ? wire.pending : wire.unconfigured; else if (route === 'auth/csrf') raw = JSON.stringify({csrf_token: 'c'.repeat(64)}); @@ -219,6 +221,7 @@ function fixture(deployment: 'native' | 'standalone' = 'standalone', locale = 'e denyTaskOverview: () => {taskOverviewDenied = true;}, shoppingItem: (present: boolean) => {shoppingItemPresent = present;}, putRequests:()=>putRequests,preferences:(locale:'en'|'es'|null,revision=1)=>{preferenceLocale=locale;preferenceRevision=revision;}, + accessRevisions:(member: number, policy: number) => {memberRevision=member; policyRevision=policy;}, member:(value:string)=>{memberId=value;},preferencesReadable:(value:boolean)=>{preferencesReadable=value;}, phase: (value: string) => {phase = value;}}; } @@ -925,6 +928,11 @@ test('Household manual execution binds drafts, original outcomes and task naviga phase:'ready',items:[{operationId:'run-operation',taskOccurrenceId:'work-1'}], })); expect(historyReads()).toHaveLength(1); + f.accessRevisions(2, 1); + administrationIntent(app,{type:'refresh'}); + await vi.waitFor(() => expect(app.administration?.access?.member?.revision).toBe('2')); + expect(app.automationRunHistory?.items ?? []).toEqual([]); + expect(historyReads()).toHaveLength(1); dispatch(other, openTask, {type:'select',occurrenceId:'work-1'}); dispatch(execution, openTask, {type:'refresh'}); expect(f.navigation).toHaveLength(0); From b3f143459e07a0291008100fc788ac0872d45c7e Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Wed, 18 Nov 2026 10:12:44 +0100 Subject: [PATCH 6/6] build(edge): pin authorization refresh preview --- addon-edge/CHANGELOG.md | 4 ++++ addon-edge/DOCS.md | 4 ++-- addon-edge/Dockerfile | 8 ++++---- addon-edge/artifact.json | 14 +++++++------- addon-edge/config.yaml | 2 +- .../automation-run-history-qualification.md | 2 +- docs/evidence/task-navigation-integration.json | 14 +++++++------- tests/backend/test_app_package.py | 14 +++++++------- 8 files changed, 33 insertions(+), 29 deletions(-) diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md index e30eeec6..6e372f64 100644 --- a/addon-edge/CHANGELOG.md +++ b/addon-edge/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.0.0-edge.40 + +- Clear open manual run history when Domus observes a change to the member's current access. + ## 0.0.0-edge.39 - Review your previous manual automation runs from the saved rule, including the original task outcome and retained results from before restoration. diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md index 622d7f68..9d97549a 100644 --- a/addon-edge/DOCS.md +++ b/addon-edge/DOCS.md @@ -1,6 +1,6 @@ # Installation and operation -Edge 0.0.0-edge.39 packages the immutable runtime declared in +Edge 0.0.0-edge.40 packages the immutable runtime declared in [artifact.json](artifact.json). Overview shows the signed-in member's completed tasks and posted earned points for the current Family week. Open Family for the full report. In Household settings, authorized members can preview a manual task proposal and @@ -22,7 +22,7 @@ Enable a saved revision in Manual automation and confirm it before running. The run receipt links to its task when the stock condition matches. Check the original request after an interrupted response. Show run history lists your own previous runs of the selected rule, with older pages on demand. -Edge.39 uses SQLite schema 33. Edge.38 introduced SQLite schema 33 and is listed in `breaking_versions`. +Edge.40 uses SQLite schema 33. Edge.38 introduced SQLite schema 33 and is listed in `breaking_versions`. Keep a compatible image and stopped-app backup before upgrading from an earlier schema. A binary that expects the earlier schema requires its compatible data backup. diff --git a/addon-edge/Dockerfile b/addon-edge/Dockerfile index 6d14cdbd..869a8a2c 100644 --- a/addon-edge/Dockerfile +++ b/addon-edge/Dockerfile @@ -1,8 +1,8 @@ # The Supervisor builds this folder. Fetch only the reviewed immutable runtime and UI. FROM ghcr.io/astral-sh/uv:0.11.29@sha256:eb2843a1e56fd9e30c7276ce1a52cba86e64c7b385f5e3279a0e08e02dd058fc AS uv FROM python:3.14.6-slim-trixie@sha256:7bec7ddcddeff7975d6ba9b4be7dd6f6b2f55e7491539145e2978f7f97ce9144 AS source -ARG DOMUS_SOURCE_COMMIT=eba168e88dedd7ddd6f84ea712094ca464a76f27 -ARG DOMUS_SOURCE_SHA256=b6164754b7c63e05ca4880974537f66d0ab4d86180b7a5c8cc88938c5ba247d6 +ARG DOMUS_SOURCE_COMMIT=50aa7190e4d910c8bea5e35658314279db284e3b +ARG DOMUS_SOURCE_SHA256=3959dde1479d90d3d6ddcb1489742ed998d6b47fcccc7daeba1fe1a3f324b987 ADD https://codeload.github.com/vypdev/domus/tar.gz/${DOMUS_SOURCE_COMMIT} /tmp/source.tar.gz RUN printf '%s /tmp/source.tar.gz\n' "$DOMUS_SOURCE_SHA256" | sha256sum --check - \ && mkdir /app \ @@ -24,9 +24,9 @@ RUN uv sync --frozen --no-dev --package domus-server --no-editable RUN .venv/bin/python -c "from pathlib import Path; import domus; from domus.entrypoints.ui_bundle import load_bundle; assert load_bundle(Path(domus.__file__).parent / 'ui') is not None" FROM python:3.14.6-slim-trixie@sha256:7bec7ddcddeff7975d6ba9b4be7dd6f6b2f55e7491539145e2978f7f97ce9144 -ARG BUILD_VERSION=0.0.0-edge.39 +ARG BUILD_VERSION=0.0.0-edge.40 ARG BUILD_ARCH -ARG DOMUS_SOURCE_COMMIT=eba168e88dedd7ddd6f84ea712094ca464a76f27 +ARG DOMUS_SOURCE_COMMIT=50aa7190e4d910c8bea5e35658314279db284e3b LABEL io.hass.type="app" \ io.hass.version="${BUILD_VERSION}" \ io.hass.arch="${BUILD_ARCH}" \ diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json index 1ece28cf..d2f8c745 100644 --- a/addon-edge/artifact.json +++ b/addon-edge/artifact.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, - "version": "0.0.0-edge.39", - "sourceCommit": "eba168e88dedd7ddd6f84ea712094ca464a76f27", - "sourceArchiveSHA256": "b6164754b7c63e05ca4880974537f66d0ab4d86180b7a5c8cc88938c5ba247d6", + "version": "0.0.0-edge.40", + "sourceCommit": "50aa7190e4d910c8bea5e35658314279db284e3b", + "sourceArchiveSHA256": "3959dde1479d90d3d6ddcb1489742ed998d6b47fcccc7daeba1fe1a3f324b987", "storageSchema": 33, - "wheelSHA256": "e6e7a89e7845bcaeb1a6d7994e6041084343d7dc7fb765a60d8f6430c4df8bbb", + "wheelSHA256": "a75cb57fd5e309a11bc26aeb33446b4ee5e78b63bdcc569423176cb6ebd1f716", "pythonFiles": { "domus/__init__.py": "7182c88b92234b4328f94497f4e70222d4390d8093e4b62893dfa78ac5530ac6", "domus/application/__init__.py": "1e8c0c87bf2a8ca947112543070583c0cc55d9d40b56eab0d86ed59a4ec1e82c", @@ -234,9 +234,9 @@ "domus/infrastructure/task_materials.py": "d5d2934e36f290c7bf44b473392f014eab8749f1f3b3d26a3402079e65d2818f" }, "uiFiles": { - ".vite/manifest.json": "1b8638ee43b130fa6079e26eef3500cc09ba55b12fc59b6249ed6f989672729b", - "assets/index-Cg8YDLuZ.js": "d26b6cbf67e74ebcfb0480902a547cb44f77c5ef667286ecb1b40352ba1ca364", + ".vite/manifest.json": "6b7306c5c8bf00ef6645af1c42382d115bd1f2fb8f2543fef4d4d8e24a42b447", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "3f9c12f5ab3b63c8c395905b0dac7f1d9e9004a5a73263238c97f4e05f0ebfe1" + "assets/index-yveh722F.js": "adb93e081a9db030ffdb6d4f827284a8a4932a9eca3ae66fa650d2a8f554781c", + "index.html": "421ae444b7598e39be8b6f552c76a258d3d643c4685fd4b94470c538898c8583" } } diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml index 97aaad14..509f3302 100644 --- a/addon-edge/config.yaml +++ b/addon-edge/config.yaml @@ -1,5 +1,5 @@ name: Domus Edge -version: "0.0.0-edge.39" +version: "0.0.0-edge.40" slug: domus_edge description: Development preview of the local Domus household application url: https://github.com/vypdev/domus diff --git a/docs/evidence/automation-run-history-qualification.md b/docs/evidence/automation-run-history-qualification.md index 17cda796..81551f84 100644 --- a/docs/evidence/automation-run-history-qualification.md +++ b/docs/evidence/automation-run-history-qualification.md @@ -8,7 +8,7 @@ their own explicit manual runs for one saved rule. The | Case | Verification | | --- | --- | | `manual-run-history-C01` | The protected HTTP tests select one rule with two authorized members and a second rule. Each member sees only their own results for the selected rule. An unused rule has an empty history. | -| `manual-run-history-C02` | The same tests revoke manual access between pages. Separate task-read revocation leaves the original task decision visible while the task link disappears. | +| `manual-run-history-C02` | The same tests revoke manual access between pages. Separate task-read revocation leaves the original task decision visible while the task link disappears. The browser tests also retire an open page and its pending read when the same member's verified authorization changes. | | `manual-run-history-C03` | The original receipts remain in descending commit order when a new run arrives between pages. Tests verify the first page, the lookahead cursor, one-row continuations, and the supported page bounds. | | `manual-run-history-C04` | Cursor checks cover a different rule, member and page size, expiry and signing-key rotation. The browser controller can restart from recent results. | | `manual-run-history-C05` | The stored time, exact revision, task decision and receipt survive a rule edit, disabled control and restart. A history request leaves receipts, audit and task state untouched. | diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json index dee0b4f5..e6f69be2 100644 --- a/docs/evidence/task-navigation-integration.json +++ b/docs/evidence/task-navigation-integration.json @@ -5,10 +5,10 @@ "command": "pnpm build:frontend", "scope": "Compiled household workspace with protected manual automation preview, saved revisions, explicit runs and scoped run history, upcoming maintenance, due today, overdue, assigned and unclaimed task summaries, products below their replenishment minimum, outstanding shopping items, weekly Family participation, optional task base points, native deadline sensor integration, protected Pantry, shared Shopping, purchase sessions with an optional store, receipt corrections, physical returns, stock locations, transfers and original operation recovery in English and Spanish.", "actualProductFiles": { - ".vite/manifest.json": "1b8638ee43b130fa6079e26eef3500cc09ba55b12fc59b6249ed6f989672729b", - "assets/index-Cg8YDLuZ.js": "d26b6cbf67e74ebcfb0480902a547cb44f77c5ef667286ecb1b40352ba1ca364", + ".vite/manifest.json": "6b7306c5c8bf00ef6645af1c42382d115bd1f2fb8f2543fef4d4d8e24a42b447", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "3f9c12f5ab3b63c8c395905b0dac7f1d9e9004a5a73263238c97f4e05f0ebfe1" + "assets/index-yveh722F.js": "adb93e081a9db030ffdb6d4f827284a8a4932a9eca3ae66fa650d2a8f554781c", + "index.html": "421ae444b7598e39be8b6f552c76a258d3d643c4685fd4b94470c538898c8583" }, "localValidation": { "commit": "9a10d8114869be754962953903e773fe8e12c723", @@ -274,12 +274,12 @@ "evidence": "automation-execution-qualification.md" }, "manualAutomationRunHistory": { - "sourceCommit": "eba168e88dedd7ddd6f84ea712094ca464a76f27", + "sourceCommit": "50aa7190e4d910c8bea5e35658314279db284e3b", "actualProductFiles": { - ".vite/manifest.json": "1b8638ee43b130fa6079e26eef3500cc09ba55b12fc59b6249ed6f989672729b", - "assets/index-Cg8YDLuZ.js": "d26b6cbf67e74ebcfb0480902a547cb44f77c5ef667286ecb1b40352ba1ca364", + ".vite/manifest.json": "6b7306c5c8bf00ef6645af1c42382d115bd1f2fb8f2543fef4d4d8e24a42b447", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "3f9c12f5ab3b63c8c395905b0dac7f1d9e9004a5a73263238c97f4e05f0ebfe1" + "assets/index-yveh722F.js": "adb93e081a9db030ffdb6d4f827284a8a4932a9eca3ae66fa650d2a8f554781c", + "index.html": "421ae444b7598e39be8b6f552c76a258d3d643c4685fd4b94470c538898c8583" }, "requirements": "manual-run-history-R01 through manual-run-history-R06", "evidence": "automation-run-history-qualification.md" diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py index f148a497..5702f990 100644 --- a/tests/backend/test_app_package.py +++ b/tests/backend/test_app_package.py @@ -15,7 +15,7 @@ def test_repository_and_edge_manifest_offer_native_ha_entry_without_user_credent manifest = yaml.safe_load((ROOT / "addon-edge/config.yaml").read_text()) assert repository["url"] == "https://github.com/vypdev/domus" assert manifest["slug"] == "domus_edge" and manifest["stage"] == "experimental" - assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.39" + assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.40" assert manifest["ingress"] is True and manifest["ingress_port"] == 8099 assert manifest["panel_admin"] is False and manifest["homeassistant_api"] is True assert manifest["options"] == {"public_origins": []} @@ -60,15 +60,15 @@ def test_build_pins_source_checksum_bases_lock_and_nonroot_native_entrypoint() - commits = re.findall(r"^ARG DOMUS_SOURCE_COMMIT=(\w+)$", source, re.MULTILINE) assert len(commits) == 2 and len(set(commits)) == 1 assert re.fullmatch(r"[a-f0-9]{40}", commits[0]) - assert commits[0] == "eba168e88dedd7ddd6f84ea712094ca464a76f27" + assert commits[0] == "50aa7190e4d910c8bea5e35658314279db284e3b" assert ( - "DOMUS_SOURCE_SHA256=b6164754b7c63e05ca4880974537f66d0ab4d86180b7a5c8cc88938c5ba247d6" + "DOMUS_SOURCE_SHA256=3959dde1479d90d3d6ddcb1489742ed998d6b47fcccc7daeba1fe1a3f324b987" in source ) - assert "ARG BUILD_VERSION=0.0.0-edge.39" in source + assert "ARG BUILD_VERSION=0.0.0-edge.40" in source candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text()) assert candidate["sourceCommit"] == commits[0] - assert candidate["version"] == "0.0.0-edge.39" + assert candidate["version"] == "0.0.0-edge.40" assert "DOMUS_SOURCE_SHA256=" + candidate["sourceArchiveSHA256"] in source assert re.search(r"^ARG DOMUS_SOURCE_SHA256=[a-f0-9]{64}$", source, re.MULTILINE) assert "sha256sum --check" in source @@ -142,8 +142,8 @@ def test_edge_artifact_declares_exact_reviewed_runtime_without_rebinding_histori "pythonFiles", "uiFiles", } - assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.39" - assert artifact["sourceCommit"] == "eba168e88dedd7ddd6f84ea712094ca464a76f27" + assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.40" + assert artifact["sourceCommit"] == "50aa7190e4d910c8bea5e35658314279db284e3b" assert artifact["storageSchema"] == 33 for field in ["sourceArchiveSHA256", "wheelSHA256"]: assert re.fullmatch("[a-f0-9]{64}", artifact[field])