diff --git a/.github/workflows/ci_check.yml b/.github/workflows/ci_check.yml
index a65b4dae..92f39b10 100644
--- a/.github/workflows/ci_check.yml
+++ b/.github/workflows/ci_check.yml
@@ -401,11 +401,11 @@ jobs:
run: >-
lockf -k -t 600 /tmp/domus-ci-entry-browser.lock pnpm --filter @domus/frontend exec playwright test
-c playwright.entry.config.ts tests/e2e/administration.spec.ts tests/e2e/tasks.spec.ts tests/e2e/workspace-navigation.spec.ts
- - name: Require all sixty actual-image household journeys
+ - name: Require all sixty-four actual-image household journeys
run: >-
uv run python -c "import json; from pathlib import Path;
result=json.loads(Path('frontend/test-results/entry-results.json').read_text());
- assert result['stats']['expected']==60 and result['stats']['unexpected']==0
+ assert result['stats']['expected']==64 and result['stats']['unexpected']==0
and result['stats']['skipped']==0 and result['stats']['flaky']==0"
- name: Retain actual-image browser evidence
diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md
index cf2edadb..5f205545 100644
--- a/addon-edge/CHANGELOG.md
+++ b/addon-edge/CHANGELOG.md
@@ -1,5 +1,17 @@
# Changelog
+## 0.0.0-edge.51
+
+- Refresh the task list and selected detail together after a competing progress update.
+- Preserve the proposed blocking reason while reviewing current facts.
+- Keep the mobile task layout within the available width across system fonts.
+
+## 0.0.0-edge.50
+
+- Start, block and unblock eligible work from Tasks with an explicit confirmation.
+- Preserve blocking reasons through conflicts and interrupted responses, with original-request recovery.
+- Keep task primary actions readable in light and dark themes.
+
## 0.0.0-edge.49
- Enable assignment saving after the selected household members change.
diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md
index 09fcf8a6..fb0649e4 100644
--- a/addon-edge/DOCS.md
+++ b/addon-edge/DOCS.md
@@ -1,6 +1,6 @@
# Installation and operation
-Edge 0.0.0-edge.49 packages the immutable runtime declared in
+Edge 0.0.0-edge.51 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
@@ -31,6 +31,13 @@ explains when the chosen members already match the current assignment. Clearing
prepares a state-permitted release. A competing update retains the draft for
explicit review. **Check saved request** recovers an interrupted assignment.
+In Tasks, **Start task**, **Block task** and **Unblock task** confirm the currently
+permitted progress change before **Save progress**. Blocking requires a reason
+within 1000 characters and shows that saved reason beside the blocked task.
+A competing update retains your proposal for **Review current task** and a
+separate save. The list and selected detail refresh together after a competing
+progress update. **Check saved request** recovers an interrupted progress change.
+
Edge.47 completes explicit runtime cleanup when Home Assistant requests Stop.
Workers finish before identity disposal and installation-lease release. Standalone
shutdown reports its bounded delegated-grant cleanup result in the server log.
diff --git a/addon-edge/Dockerfile b/addon-edge/Dockerfile
index 00bbccf9..b48cd433 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=0a95702a5f53911cc12c645bf7f6f2e8dcd626cd
-ARG DOMUS_SOURCE_SHA256=0fcb5041bdb95712545b0deb6aec3ed2d8f545289cd034537f0d70ae78a71989
+ARG DOMUS_SOURCE_COMMIT=4f79b75d65835037a51b51e3742cd372bc45edfe
+ARG DOMUS_SOURCE_SHA256=b57247ac5e62686f8ff42b1ac71cbcde5e47ea54ff873b543077db0102e865dc
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.49
+ARG BUILD_VERSION=0.0.0-edge.51
ARG BUILD_ARCH
-ARG DOMUS_SOURCE_COMMIT=0a95702a5f53911cc12c645bf7f6f2e8dcd626cd
+ARG DOMUS_SOURCE_COMMIT=4f79b75d65835037a51b51e3742cd372bc45edfe
LABEL io.hass.type="app" \
io.hass.version="${BUILD_VERSION}" \
io.hass.arch="${BUILD_ARCH}" \
diff --git a/addon-edge/README.md b/addon-edge/README.md
index 963e3cde..ea2e0d9f 100644
--- a/addon-edge/README.md
+++ b/addon-edge/README.md
@@ -23,7 +23,12 @@ for explicit review. Saved requests recover an interrupted assignment response.
Edge.49 enables assignment saving after the selected members change and explains
when the current selection already matches the task.
+Edge.50 adds Start, Block and Unblock to Tasks, with a required blocking reason,
+explicit conflict review and recovery of the original progress request.
+Edge.51 refreshes both the list and detail after a competing progress update and
+keeps the mobile task layout within the available width.
+
This candidate uses SQLite schema 34. Keep a
compatible image and cold data backup before upgrading a previous preview.
-See [installation and operation](DOCS.md) for the source pin and rollback
+See [installation and operation](https://github.com/vypdev/domus/blob/ac843a9a5c23d411ff11dcbd83d32256af2f5daa/addon-edge/DOCS.md) for the source pin and rollback
instructions.
diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json
index 7ae9e912..7bb84af4 100644
--- a/addon-edge/artifact.json
+++ b/addon-edge/artifact.json
@@ -1,10 +1,10 @@
{
"schemaVersion": 1,
- "version": "0.0.0-edge.49",
- "sourceCommit": "0a95702a5f53911cc12c645bf7f6f2e8dcd626cd",
- "sourceArchiveSHA256": "0fcb5041bdb95712545b0deb6aec3ed2d8f545289cd034537f0d70ae78a71989",
+ "version": "0.0.0-edge.51",
+ "sourceCommit": "4f79b75d65835037a51b51e3742cd372bc45edfe",
+ "sourceArchiveSHA256": "b57247ac5e62686f8ff42b1ac71cbcde5e47ea54ff873b543077db0102e865dc",
"storageSchema": 34,
- "wheelSHA256": "b8141fd740b17282129a072802782182ff14971827514e427be87546c20ce469",
+ "wheelSHA256": "3fe64c5c5d4d21d6c65538f276bf18805c44d04d084db57d964599b36d48ff0f",
"pythonFiles": {
"domus/__init__.py": "7182c88b92234b4328f94497f4e70222d4390d8093e4b62893dfa78ac5530ac6",
"domus/application/__init__.py": "1e8c0c87bf2a8ca947112543070583c0cc55d9d40b56eab0d86ed59a4ec1e82c",
@@ -88,7 +88,7 @@
"domus/application/task_material_views.py": "1f4e1b52c17064b73e3c6502b38fc578a7589d68044279312c783b656e5aa5bf",
"domus/application/task_materials.py": "caa132a7b16fca293770deba3da149cf9bda2e24d4719abe9de39470d686698e",
"domus/application/task_ports.py": "165f04fc639310da0b742c8c2d58b2eadd459142720fdc138df384f34e53e35a",
- "domus/application/task_queries.py": "f5cf1da6bbb86386b05844d24a021ff8935fa92882c1261c650da2e3b3ee7347",
+ "domus/application/task_queries.py": "a9606243d425085600f278a118cb9a1315a9c3bc878f3e88531f6b208c15baf6",
"domus/application/task_requests.py": "2e9ead8f5458d45335ec55bad50f5f7e12b42ee9b00ff54634f3ff681b320897",
"domus/application/task_reviews.py": "dcc288cda6cdcf5073bad4f24133b9d3496c0b0cf1272e8328e6df38129f3328",
"domus/composition/__init__.py": "a902d8faf7dd19da6829fb730d81e32d34ec38ee6cfafd676966a95d0ad31366",
@@ -175,7 +175,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": "fffefb1542eb545b45efe0e14467015e61babed51a6bc09a5978fc9c2673ab51",
+ "domus/entrypoints/task_http.py": "cb0171a9fd70efef48b9ecc53a7b3762870c6896325354787d84782681397a8e",
"domus/entrypoints/task_response.py": "d2f4c0795aee429fc318b32495601031c559fa38af1d7da63b4735f7e6eb5d13",
"domus/entrypoints/ui_bundle.py": "beae3d4a7a57375ee195cca81efccdbc899d9db4286029d53eabaf30de6e14f7",
"domus/entrypoints/ui_http.py": "b6c47baa742f3862173a93e4121dc9914fd972eb6287ffffb9ffccecbf2ebe4a",
@@ -239,9 +239,9 @@
"domus/infrastructure/task_materials.py": "d5d2934e36f290c7bf44b473392f014eab8749f1f3b3d26a3402079e65d2818f"
},
"uiFiles": {
- ".vite/manifest.json": "f4fdf822c622f2e96f1b01bf5c1cdbec895eb99b7fc118f8d4df54e4fd7d87b0",
- "assets/index-BYTTreHd.js": "2eb864558eeff849ff8abb5aaab2409a1c6589ba3dc4d7cb09385ab9175fc001",
+ ".vite/manifest.json": "5cc6cb5d72390640c8e281eba20c9ff8c782c7f5c6e103ff39a6257fde28b74b",
"assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48",
- "index.html": "eb9cf14a75ac42e824649a406b7d388978547a14d2d712251b92663b6954532b"
+ "assets/index-lAPOs-kN.js": "1696cc56f023da1760f9147d175e64caa65baa08be89024a85761776b88b38ff",
+ "index.html": "c9110bf2ef5b3294a64e67513f27b7f5baee3a999344590d479c5b15ff95ac33"
}
}
diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml
index 2abca5e4..70d57f31 100644
--- a/addon-edge/config.yaml
+++ b/addon-edge/config.yaml
@@ -1,5 +1,5 @@
name: Domus Edge
-version: "0.0.0-edge.49"
+version: "0.0.0-edge.51"
slug: domus_edge
description: Development preview of the local Domus household application
url: https://github.com/vypdev/domus
diff --git a/backend/src/domus/application/task_queries.py b/backend/src/domus/application/task_queries.py
index 371734c0..60ef6b49 100644
--- a/backend/src/domus/application/task_queries.py
+++ b/backend/src/domus/application/task_queries.py
@@ -843,6 +843,7 @@ def original(self, action: str, key: str) -> OperationView:
"task.create",
"task.claim",
"task.assign",
+ "task.transition",
"task.complete",
"task.verify",
"task.reopen",
diff --git a/backend/src/domus/entrypoints/task_http.py b/backend/src/domus/entrypoints/task_http.py
index 88666290..7102a65c 100644
--- a/backend/src/domus/entrypoints/task_http.py
+++ b/backend/src/domus/entrypoints/task_http.py
@@ -97,7 +97,13 @@
)
TaskWorkspaceAction = Literal[
- "task.create", "task.claim", "task.assign", "task.complete", "task.verify", "task.reopen"
+ "task.create",
+ "task.claim",
+ "task.assign",
+ "task.transition",
+ "task.complete",
+ "task.verify",
+ "task.reopen",
]
diff --git a/docs/contracts/household-api.openapi.json b/docs/contracts/household-api.openapi.json
index 54fd3c2d..907fc92d 100644
--- a/docs/contracts/household-api.openapi.json
+++ b/docs/contracts/household-api.openapi.json
@@ -9571,6 +9571,7 @@
"task.create",
"task.claim",
"task.assign",
+ "task.transition",
"task.complete",
"task.verify",
"task.reopen"
@@ -31830,6 +31831,7 @@
"task.create",
"task.claim",
"task.assign",
+ "task.transition",
"task.complete",
"task.verify",
"task.reopen"
diff --git a/docs/contracts/native-household-api.openapi.json b/docs/contracts/native-household-api.openapi.json
index c73bd1af..7ad56614 100644
--- a/docs/contracts/native-household-api.openapi.json
+++ b/docs/contracts/native-household-api.openapi.json
@@ -9533,6 +9533,7 @@
"task.create",
"task.claim",
"task.assign",
+ "task.transition",
"task.complete",
"task.verify",
"task.reopen"
@@ -31471,6 +31472,7 @@
"task.create",
"task.claim",
"task.assign",
+ "task.transition",
"task.complete",
"task.verify",
"task.reopen"
diff --git a/docs/evidence/task-assignment-qualification.md b/docs/evidence/task-assignment-qualification.md
index 98ac128d..ad7fb8cb 100644
--- a/docs/evidence/task-assignment-qualification.md
+++ b/docs/evidence/task-assignment-qualification.md
@@ -52,7 +52,7 @@ The measured Linux wheel SHA-256 is
`b8141fd740b17282129a072802782182ff14971827514e427be87546c20ce469`.
All 231 Python modules match Git and the installed Linux builder. Its four
compiled UI files also match the independently built local bundle.
-The [artifact declaration](../../addon-edge/artifact.json) records those exact bytes.
+The [artifact declaration](https://github.com/vypdev/domus/blob/960431df0b682be6d97292837f11f9daf08faf12/addon-edge/artifact.json) records those exact bytes.
The ARM64 image is
`sha256:8d22fdce04f46fbd2567635e3f3d5a968f3788dc2d79efc8af1c0fd57aa78baf`.
diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json
index 9d9b281d..5e8a8fd3 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 protected manual automation preview, saved revisions, explicit runs and scoped run history, daily schedule previews and inactive daily drafts, 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. Points-allocation cards inherit the shared raised surface in both color schemes. The Tasks workspace supports planned task assignment, state-permitted release, retained conflict selections and original assignment-request recovery.",
+ "scope": "Compiled household workspace with protected manual automation preview, saved revisions, explicit runs and scoped run history, daily schedule previews and inactive daily drafts, 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. Points-allocation cards inherit the shared raised surface in both color schemes. The Tasks workspace supports planned task assignment, state-permitted release, retained conflict selections and original assignment-request recovery. The Tasks workspace also confirms Start, Block and Unblock, retains a bounded blocking reason through explicit current-task review and recovers the original progress request.",
"actualProductFiles": {
- ".vite/manifest.json": "f4fdf822c622f2e96f1b01bf5c1cdbec895eb99b7fc118f8d4df54e4fd7d87b0",
- "assets/index-BYTTreHd.js": "2eb864558eeff849ff8abb5aaab2409a1c6589ba3dc4d7cb09385ab9175fc001",
+ ".vite/manifest.json": "5cc6cb5d72390640c8e281eba20c9ff8c782c7f5c6e103ff39a6257fde28b74b",
"assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48",
- "index.html": "eb9cf14a75ac42e824649a406b7d388978547a14d2d712251b92663b6954532b"
+ "assets/index-lAPOs-kN.js": "1696cc56f023da1760f9147d175e64caa65baa08be89024a85761776b88b38ff",
+ "index.html": "c9110bf2ef5b3294a64e67513f27b7f5baee3a999344590d479c5b15ff95ac33"
},
"localValidation": {
"commit": "9a10d8114869be754962953903e773fe8e12c723",
diff --git a/docs/evidence/task-progress-qualification.md b/docs/evidence/task-progress-qualification.md
new file mode 100644
index 00000000..fba929e2
--- /dev/null
+++ b/docs/evidence/task-progress-qualification.md
@@ -0,0 +1,89 @@
+# Task progress interface qualification
+
+Issue #143 connects the existing task transition command to the Tasks workspace.
+The owning companion is [task progress interface](../../specs/task-progress-interface.md).
+The retained household task, execution, category and assignment owners keep their
+published case identities and behavior.
+
+Start confirms the assigned-to-in-progress transition. Block confirms a meaningful
+multiline reason. Unblock confirms Assigned when assignees remain and Available
+when the assignee set is empty. Current server hints determine discovery. The
+command transaction enforces current target-specific grants, household scope and
+the exact reviewed revision. Assignee identities remain unchanged.
+
+The editor uses released ha-ui buttons, cards and feedback from `0.1.0-next.2`.
+It preserves the existing multiline text validator and 1,000-code-point bound.
+A competing update retains the proposed target and reason. A separate review
+accepts current facts before a deliberate save. An unavailable target offers
+refresh and cancellation. Opening progress confirmation preserves other task
+form drafts and hides their competing actions until the confirmation closes.
+
+The existing workspace original-request allowlist now includes `task.transition`
+through recorded authorization. Both OpenAPI projections include the action.
+Original receipt decoding binds the task, revision, target and exact reason to
+the frozen journal request. Existing creation and assignment entries remain
+readable. Storage schema 34 and the persisted transition format are retained.
+
+| Published case | Executable evidence |
+| --- | --- |
+| task-progress-interface-C01 | The [compiled progress journeys](../../frontend/tests/e2e/tasks.spec.ts) start assigned work, block it and unblock it while checking revisions and assignees. The [component tests](../../frontend/tests/task-component.test.ts) require confirmation before each command. |
+| task-progress-interface-C02 | The compiled journeys block available work, return it to available and verify an empty assignee set. The retained [execution command tests](../../tests/backend/test_task_execution_commands.py) cover current target-specific grants. |
+| task-progress-interface-C03 | The [HTTP recovery regression](../../tests/backend/test_task_http.py) exercises both compositions and denies original disclosure after role revocation. The retained [query tests](../../tests/backend/test_task_queries.py) verify recorded authority, scope and transition target. |
+| task-progress-interface-C04 | The [domain tests](../../frontend/tests/tasks.test.ts), component tests and [normal page decoder tests](../../frontend/tests/page.test.ts) reject blank, invalid Unicode, controls and over-bound reasons. The compiled journey checks correction and exact saved multiline text. The retained backend validators enforce the same bound. |
+| task-progress-interface-C05 | Two browser tabs compete at one revision. The losing editor retains its reason. A still-permitted target requires explicit current review and a separate save. An unavailable target requires refresh or cancellation. The [controller tests](../../frontend/tests/task-controller.test.ts) include a conflict after preflight, refreshed list and selected facts after refused admission, and truthful retirement of stale list facts when the refresh fails. |
+| task-progress-interface-C06 | The compiled journey commits a transition and drops its response. Reload recovers the same original operation. Exact replay preserves counts and changed key payload conflicts. [Transport tests](../../frontend/tests/task-http.test.ts) reject mismatched receipts. [Journal tests](../../frontend/tests/task-journal.test.ts) retain progress alongside older entries. |
+| task-progress-interface-C07 | Four execution command tests inject failure after an actual occurrence write, verify rollback of state and evidence, and retry the same original key successfully. Controller and component tests preserve correctable input across unavailable, denied and uncertain outcomes. |
+| task-progress-interface-C08 | Four compiled journeys cover Ingress and standalone with English desktop keyboard and Spanish 390 px native touch. Component tests assert reason, review, cancellation and recovery focus, public ha-ui controls and inert text. |
+| task-progress-interface-C09 | The compiled journey restarts the composed runtime, checks its saved reason and original operation, completes work, then restores an earlier checkpoint. Original replay returns the historical operation and leaves the restored current task and evidence counts unchanged. |
+
+The local frontend campaign passes 1,917 tests with all four coverage metrics at
+100% globally and per authored runtime file. The independent specification SDK
+accepts all nine supplied cases, reciprocal requirements and retained owners.
+The complete backend campaign passes 5,515 tests with 100% statement and branch
+coverage globally and per authored module, followed by an independent source
+audit. Four subsequently added late-write rollback cases and ten normal-HTTP
+Unicode-bound cases pass separately. Final CI collects their combined inventory.
+
+All four compiled progress journeys pass. They check readable card text and
+primary actions in both themes. An observed dark-theme primary-button ratio of
+1.72 failed the regression before the public on-accent token was supplied by the
+Tasks host. The same host tokens also reach the nested policy controls. The
+tests wait for the theme transition's final contrast before measuring it.
+
+The longer journey uses the existing Saved requests interface to dismiss a
+resolved creation request before reaching the fixed eight-record journal
+capacity. It retains the original transition receipt for restart and restoration.
+The complete source campaign passes all 119 compiled browser journeys without
+skips, unexpected results or flaky outcomes. The rebuilt catalog passes all
+45 journeys. The CPU image campaigns and immutable installed-owner acceptance
+are tracked in [PR #144](https://github.com/vypdev/domus/pull/144).
+
+## Immutable candidate
+
+Edge.51 packages runtime source `4f79b75d65835037a51b51e3742cd372bc45edfe`.
+The source archive SHA-256 is
+`b57247ac5e62686f8ff42b1ac71cbcde5e47ea54ff873b543077db0102e865dc`.
+The independently measured Linux wheel SHA-256 is
+`3fe64c5c5d4d21d6c65538f276bf18805c44d04d084db57d964599b36d48ff0f`.
+All 231 Python modules match Git, the wheel and the installed Linux builder.
+The four compiled UI files match the local and Linux builds, and the normal
+local wheel matches the Linux wheel exactly. The
+[artifact declaration](../../addon-edge/artifact.json) records those exact bytes.
+Actual-image cases, installed-owner acceptance and final same-head CI and review
+are recorded in [PR #144](https://github.com/vypdev/domus/pull/144).
+
+The installed Edge.50 two-tab journey exposed a stale list after refused progress
+admission while the selected detail already reflected the competing update.
+Five controller regressions and four compiled journeys reproduced that behavior.
+Edge.51 refreshes the list and selected detail through the existing facts query.
+A failed list read clears stale rows and preserves the truthful failure state.
+The immutable Edge.50 archive, wheel and image retain their measured bytes.
+
+The first package-head CI caught a stale current-bundle fingerprint in the
+navigation evidence manifest. The normal wheel acceptance reproduced the
+failure. The current-file declaration now matches the measured Edge.51 bundle,
+and the wheel, asset and license acceptance passes. The Linux mobile campaign
+also exposed an intrinsic grid width exceeding the narrow viewport. The task
+columns now use a zero-minimum track. Reload journeys wait for the composed
+workspace before choosing the test language, including the standalone sign-in
+return through Overview.
diff --git a/docs/installation-home-assistant.md b/docs/installation-home-assistant.md
index cac75a6b..8bb0cef3 100644
--- a/docs/installation-home-assistant.md
+++ b/docs/installation-home-assistant.md
@@ -7,6 +7,11 @@ Install Domus Edge through the durable Supervisor repository source
offered by Supervisor to the artifact declaration. It records the preview version,
source commit, source archive and installed file hashes. [Edge artifact](../addon-edge/artifact.json)
+Edge.51 lets members start, block and unblock eligible work from Tasks. It keeps
+the blocking reason through conflict review and original-request recovery.
+A competing progress update refreshes both the list and selected detail.
+[Qualification](evidence/task-progress-qualification.md)
+
Edge.45 adds the [native open-task list](tasks/ha-open-tasks.md) with its own optional
`ha_tasks_digest` grant. Home Assistant entity viewers can see the titles and
current states of all open household occurrences. The companion preserves
diff --git a/docs/tasks/execution.md b/docs/tasks/execution.md
index 85b4528e..39661124 100644
--- a/docs/tasks/execution.md
+++ b/docs/tasks/execution.md
@@ -223,7 +223,7 @@ actor. Explicit HA rejection removes access instead of opening an outage grace p
GET `/api/v1/tasks/access` requires current task-read authority and returns only the canonical `household_id`, current `member_id` and server-derived `can_create` affordance. It does not widen the separate household-administration permission scope and never accepts a client-selected principal. Task detail continues to supply current `allowed_actions`.
-GET `/api/v1/tasks/requests/{action}/{key}` recovers the caller's original workspace request when its response and operation ID were lost. Supported actions are `task.create`, `task.claim`, `task.complete`, `task.verify` and `task.reopen`. Current task-read, exact own actor/action/key scope and recorded original command authority are checked before disclosure. This task-specific recovery does not require the separate operations.read browsing grant; the operation-by-ID query retains that grant. The response binds `action`, `command_key` and `operation_id`, and distinguishes pending/delivered current event evidence from suppressed historical evidence. A historical receipt does not recreate an absent task effect.
+GET `/api/v1/tasks/requests/{action}/{key}` recovers the caller's original workspace request when its response and operation ID were lost. Supported actions are `task.create`, `task.claim`, `task.assign`, `task.transition`, `task.complete`, `task.verify` and `task.reopen`. Current task-read, exact own actor/action/key scope and recorded original command authority are checked before disclosure. This task-specific recovery does not require the separate operations.read browsing grant; the operation-by-ID query retains that grant. The response binds `action`, `command_key` and `operation_id`, and distinguishes pending/delivered current event evidence from suppressed historical evidence. A historical receipt does not recreate an absent task effect.
The UI retains at most eight originals and 65,536 UTF-8 bytes for one hour in its own `tasks` journal namespace, separated by installation, channel, HA subject, household and canonical membership. It stores no credentials. A write is prepared only after storage is confirmed. Lost replies are recovered by GET; the UI does not automatically resend a POST, mint a replacement key or evict unresolved work. Clock rollback, corrupt storage, an unconfirmed write or an external storage change blocks new effects while preserving the original bytes. Expired records are pruned without refreshing identity or renewing the session deadline.
diff --git a/docs/user-guide.md b/docs/user-guide.md
index 777bc99f..5139c6ab 100644
--- a/docs/user-guide.md
+++ b/docs/user-guide.md
@@ -61,6 +61,13 @@ actions your role allows. Use **Retry inventory summary** if the summary could n
If someone else changes the task, your selection remains available. Use
**Review current assignment**, then save deliberately. **Refresh assignment
and members** reloads the current task and available people after a read failure.
+- **Start task** moves eligible assigned work into progress. **Block task** requires
+ a meaningful reason of up to 1000 characters. **Unblock task** returns work to
+ its existing assignees, or makes unassigned work available. Review the proposed
+ state and choose **Save progress**. **Cancel** closes the confirmation.
+ The saved reason remains visible while blocked. If the task changes, your
+ proposed action and reason remain available for **Review current task** and a
+ separate save. An unavailable action offers refresh and cancellation.
- Restricted performers require adult approval by default. An authorized adult can approve or reject the current cycle; rejection and reopening require a reason. Reopening preserves the previous cycle and its verification evidence.
- If a task already has linked materials, review its quantities before completion. Decimal input is converted exactly, including a comma separator, and the linked unit's precision is enforced. Zero means unused. Separate-recording tasks do not silently submit planned consumption.
- A lost reply leaves a visible saved request. **Check saved request** reads its original result without sending another change. New changes remain blocked while an earlier request is unconfirmed. Resolved browser records can be dismissed without deleting server history.
diff --git a/frontend/src/adapters/task-values.ts b/frontend/src/adapters/task-values.ts
index 13d740cb..93a944e0 100644
--- a/frontend/src/adapters/task-values.ts
+++ b/frontend/src/adapters/task-values.ts
@@ -1,7 +1,7 @@
/** Project the task wire contract into immutable UI facts, preserving exact integers. */
import {nextRevision} from '../domain/administration';
import {civilDate} from '../domain/civil-date';
-import {categoryLabel, isCategoryCommand, taskCommand, taskIdentifier, taskQuantity, taskText, TASK_PRIORITIES, TASK_STATES} from '../domain/tasks';
+import {categoryLabel, isCategoryCommand, taskCommand, taskIdentifier, taskQuantity, taskText, TASK_PRIORITIES, TASK_STATES, TASK_TEXT_LIMITS} from '../domain/tasks';
import type {TaskCategoryCatalog, TaskCommand, TaskCycleSummary, TaskDetail, TaskPage, TaskReceipt, TaskSummary} from '../domain/tasks';
import type {TaskOriginal, TaskRequest} from '../application/task-ports';
import {boolean, check, choice, fields, identifier, invalid, responseInteger, responseRevision, text} from './json-values';
@@ -88,6 +88,7 @@ export function taskDetail(value: unknown, occurrenceId: string, householdId: st
const current = item.cycle === null ? null : cycle(item.cycle, occurrenceId, householdId);
check(base.currentCycleId === null || current?.cycleId === base.currentCycleId);
return Object.freeze({...base, description: literal(content.description, 4000, false, true), priority: choice(content.priority, TASK_PRIORITIES),
+ ...base.state === 'blocked' ? {stateReason: literal(work.state_reason, TASK_TEXT_LIMITS.reason, true, true)} : {},
allowedActions: Object.freeze(allowedActions), cycle: current, materials: Object.freeze(materials),
...item.completion_points === undefined ? {} : {completionPoints: choice(item.completion_points, ['automatic','manual','manager_required'] as const)},
materialRecording: choice(rules.material_recording, ['review_on_completion', 'separate_recording']),
@@ -163,6 +164,9 @@ export function taskReceipt(value: unknown, request: TaskRequest | TaskOriginal,
if (command.action !== 'task.create') check(command.occurrenceId === occurrenceId);
if (command.action === 'task.assign')
check(JSON.stringify([...assigneeIds].sort()) === JSON.stringify([...command.payload.assignee_ids].sort()));
+ if (command.action === 'task.transition')
+ check(state === command.payload.target
+ && literal(result.state_reason, TASK_TEXT_LIMITS.reason, state === 'blocked', true) === command.payload.reason);
const savedCycle = Object.hasOwn(result, 'cycle') ? cycle(result.cycle, occurrenceId) : null;
if (command.action === 'task.complete') {
check(state === 'completed' && savedCycle !== null && savedCycle.performedAt === command.payload.performed_at
@@ -175,6 +179,7 @@ export function taskReceipt(value: unknown, request: TaskRequest | TaskOriginal,
}
return Object.freeze({kind: 'receipt', stage, action: command.action, operationId, occurrenceId, revision, state, cycle: savedCycle, archivedBy,
...command.action === 'task.assign' ? {assigneeIds} : {},
+ ...command.action === 'task.transition' ? {stateReason: command.payload.reason} : {},
...originalBasePoints(result.point_value_minor, basePoints)});
}
/** Only validated decimal lexemes bypass JSON's string quoting; arbitrary text always uses JSON.stringify. */
diff --git a/frontend/src/application/task-controller.ts b/frontend/src/application/task-controller.ts
index 25a66f88..351c5259 100644
--- a/frontend/src/application/task-controller.ts
+++ b/frontend/src/application/task-controller.ts
@@ -1,7 +1,7 @@
/** Task workflows coordinate current identity, durable original intents and server-owned actions. */
import {JournalError} from '../domain/journal';
import {isCategoryCommand, taskCommand, taskIdentifier} from '../domain/tasks';
-import type {TaskAccess, TaskCommand, TaskDetail, TaskMaterialUsage, TaskPage, TaskPriority, TaskScheduleDraft} from '../domain/tasks';
+import type {TaskAccess, TaskCommand, TaskDetail, TaskMaterialUsage, TaskPage, TaskPriority, TaskProgressTarget, TaskScheduleDraft} from '../domain/tasks';
import {EntryReadError} from './ports';
import type {Revision} from '../domain/administration';
import type {ReviewedAllocation} from '../domain/point-allocation';
@@ -131,6 +131,7 @@ export class TaskController {
const detail = this.state.detail!;
if (detail.occurrenceId !== command.occurrenceId) return false;
if (detail.revision !== command.payload.expected_revision) {this.update({notice: 'conflict'}); return false;}
+ if (command.action === 'task.transition') return detail.allowedActions.includes('transition:' + command.payload.target);
const action = command.action === 'task.verify' ? command.payload.decision === 'approved' ? 'approve' : 'reject' : command.action.slice(5);
return detail.allowedActions.includes(action);
}
@@ -149,7 +150,14 @@ export class TaskController {
this.update({page: prior.page});
if (this.state.readOnly) {this.update({notice: 'read_only'}); return;}
if ('occurrenceId' in command) this.update({detail: await this.read(this.server.detail(command.occurrenceId, this.state.access!.householdId, this.state.session!.context), generation)});
- if (!this.accepted(command)) {if (this.state.notice !== 'conflict' && this.state.notice !== 'category_unavailable') this.update({notice: 'action_not_allowed'}); return;}
+ if (!this.accepted(command)) {
+ if (this.state.notice !== 'conflict' && this.state.notice !== 'category_unavailable') this.update({notice: 'action_not_allowed'});
+ if (command.action === 'task.transition') {
+ this.update({page: null});
+ await this.facts(generation, command.occurrenceId);
+ }
+ return;
+ }
if (this.state.records === null) {this.update({notice: 'journal_unavailable'}); return;}
if (this.state.records.some(item => item.stage === 'prepared' || item.stage === 'uncertain')) {this.update({notice: 'previous_request_unresolved'}); return;}
let key: string;
@@ -164,7 +172,8 @@ export class TaskController {
}
if (this.clock.now() >= this.state.session!.expiresAt) throw new EntryReadError('authentication_required');
if (outcome.kind === 'receipt') await this.receiptFacts(command, outcome.occurrenceId, prior, generation);
- if (command.action === 'task.assign' && outcome.kind === 'rejected' && outcome.reason === 'conflict')
+ if ((command.action === 'task.assign' || command.action === 'task.transition')
+ && outcome.kind === 'rejected' && outcome.reason === 'conflict')
await this.facts(generation, command.occurrenceId);
});
}
@@ -205,6 +214,13 @@ export class TaskController {
if (work.occurrenceId !== occurrenceId) {this.update({notice: 'conflict'}); return Promise.resolve();}
return this.execute({action: 'task.assign', occurrenceId, payload: {expected_revision: revision, assignee_ids: assigneeIds}});
}
+ transition(occurrenceId: string, revision: Revision, target: TaskProgressTarget, reason: string): Promise {
+ const work = this.state.detail;
+ if (work === null) return Promise.resolve();
+ if (work.occurrenceId !== occurrenceId) {this.update({notice: 'conflict'}); return Promise.resolve();}
+ return this.execute({action: 'task.transition', occurrenceId,
+ payload: {expected_revision: revision, target, reason}});
+ }
complete(materialUsages: readonly TaskMaterialUsage[] | null, reviewed?: ReviewedAllocation): Promise {
const work = this.state.detail, member = this.state.access?.memberId;
if (work === null || member === undefined) return Promise.resolve();
diff --git a/frontend/src/composition/entry-page.ts b/frontend/src/composition/entry-page.ts
index 597dfcb4..266bab8c 100644
--- a/frontend/src/composition/entry-page.ts
+++ b/frontend/src/composition/entry-page.ts
@@ -65,7 +65,7 @@ import {language, message} from '../presentation/messages';
import type {DomusApp, EntryIntent} from '../presentation/domus-app';
import {revisionValue} from '../domain/administration';
import type {TaskIntent} from '../presentation/domus-tasks';
-import {taskAssignees, taskBasePointAmount, taskQuantity, taskScheduleDraft, TASK_PRIORITIES} from '../domain/tasks';
+import {taskAssignees, taskBasePointAmount, taskCommand, taskQuantity, taskScheduleDraft, TASK_PRIORITIES} from '../domain/tasks';
import type {TaskPriority} from '../domain/tasks';
import type {AdministrationIntent} from '../presentation/domus-administration';
import {administrationCommand} from '../domain/administration-commands';
@@ -134,12 +134,20 @@ function reviewedAllocation(value: unknown): ReviewedAllocation {
export function decodeTaskIntent(value: unknown): TaskIntent | null {
try {
- const item = fields(value, ['type'], ['title', 'description', 'priority', 'schedule', 'occurrenceId', 'materialUsages', 'decision', 'reason', 'key', 'categoryId', 'label', 'revision', 'reviewed', 'basePointsMinor', 'assigneeIds']);
+ const item = fields(value, ['type'], ['title', 'description', 'priority', 'schedule', 'occurrenceId', 'materialUsages', 'decision', 'reason', 'key', 'categoryId', 'label', 'revision', 'reviewed', 'basePointsMinor', 'assigneeIds', 'target']);
const type = item.type;
if (type === 'assign') {
fields(value, ['type', 'occurrenceId', 'revision', 'assigneeIds'], []);
return {type, occurrenceId: identifier(item.occurrenceId), revision: revisionValue(item.revision), assigneeIds: taskAssignees(item.assigneeIds)};
}
+ if (type === 'transition') {
+ fields(value, ['type', 'occurrenceId', 'revision', 'target', 'reason'], []);
+ const command = taskCommand({action: 'task.transition', occurrenceId: item.occurrenceId,
+ payload: {expected_revision: item.revision, target: item.target, reason: item.reason}});
+ check(command?.action === 'task.transition');
+ return {type, occurrenceId: command.occurrenceId, revision: command.payload.expected_revision,
+ target: command.payload.target, reason: command.payload.reason};
+ }
if (type === 'create') {
fields(value, ['type', 'title', 'description', 'priority'], ['schedule', 'categoryId', 'basePointsMinor']);
check(typeof item.title === 'string' && typeof item.description === 'string' && typeof item.priority === 'string'
@@ -711,6 +719,8 @@ export function mountEntry(page: EntryPage): PageMount {
case 'archiveCategory': await active.taskWork(controller => controller.archiveCategory(intent.categoryId, intent.revision)); break;
case 'claim': await active.taskWork(controller => controller.claim()); break;
case 'assign': await active.taskWork(controller => controller.assign(intent.occurrenceId, intent.revision, intent.assigneeIds)); break;
+ case 'transition': await active.taskWork(controller => controller.transition(
+ intent.occurrenceId, intent.revision, intent.target, intent.reason)); break;
case 'complete':
await active.taskWork(controller => controller.complete(intent.materialUsages, ...intent.reviewed === undefined ? [] : [intent.reviewed]));
break;
diff --git a/frontend/src/domain/tasks.ts b/frontend/src/domain/tasks.ts
index f2a1b5fd..0a6e6e65 100644
--- a/frontend/src/domain/tasks.ts
+++ b/frontend/src/domain/tasks.ts
@@ -44,6 +44,8 @@ export function taskAssignees(value: unknown): readonly string[] {
}
export const TASK_STATES = ['draft', 'available', 'assigned', 'in_progress', 'blocked', 'completed', 'cancelled', 'skipped'] as const;
export type TaskState = typeof TASK_STATES[number];
+export const TASK_PROGRESS_TARGETS = ['in_progress', 'blocked', 'assigned', 'available'] as const;
+export type TaskProgressTarget = typeof TASK_PROGRESS_TARGETS[number];
export const TASK_PRIORITIES = ['low', 'normal', 'high', 'urgent'] as const;
export type TaskPriority = typeof TASK_PRIORITIES[number];
type ScheduledStart = Readonly<{kind: 'date' | 'time'; local: string}>;
@@ -77,6 +79,8 @@ export type TaskCommand = CategoryCommand |
category_id?: string; schedule?: TaskSchedule; overrides?: TaskCreationOverrides}>}>
| Readonly<{action: 'task.claim'; occurrenceId: string; payload: Readonly<{expected_revision: Revision}>}>
| Readonly<{action: 'task.assign'; occurrenceId: string; payload: Readonly<{expected_revision: Revision; assignee_ids: readonly string[]}>}>
+ | Readonly<{action: 'task.transition'; occurrenceId: string; payload: Readonly<{
+ expected_revision: Revision; target: TaskProgressTarget; reason: string}>}>
| Readonly<{action: 'task.complete'; occurrenceId: string; payload: Readonly<{expected_revision: Revision;
performer_ids: readonly string[]; performed_at: string; material_usages: readonly TaskMaterialUsage[] | null;
allocation_fingerprint?: string; manual_shares?: readonly ManualShare[]}>}>
@@ -171,6 +175,14 @@ export function taskCommand(value: unknown): TaskCommand | undefined {
return Object.freeze({action, occurrenceId, payload: Object.freeze({expected_revision: revisionValue(body.expected_revision),
assignee_ids: taskAssignees(body.assignee_ids)})});
}
+ if (action === 'task.transition') {
+ const body = fields(item.payload, ['expected_revision', 'target', 'reason']);
+ const target = choice(body.target, TASK_PROGRESS_TARGETS);
+ const reason = taskText(body.reason, TASK_TEXT_LIMITS.reason, target === 'blocked', true);
+ requireValue(target === 'blocked' || reason === '');
+ return Object.freeze({action, occurrenceId, payload: Object.freeze({
+ expected_revision: revisionValue(body.expected_revision), target, reason})});
+ }
if (action === 'task.claim') {
const body = fields(item.payload, ['expected_revision']);
return Object.freeze({action, occurrenceId, payload: Object.freeze({expected_revision: revisionValue(body.expected_revision)})});
@@ -215,6 +227,7 @@ export interface TaskCycleSummary {
}
export interface TaskDetail extends TaskSummary {
readonly description: string; readonly priority: TaskPriority; readonly allowedActions: readonly string[];
+ readonly stateReason?: string;
readonly completionPoints?: 'automatic' | 'manual' | 'manager_required';
readonly cycle: TaskCycleSummary | null; readonly materials: readonly TaskMaterial[];
readonly materialRecording: 'review_on_completion' | 'separate_recording';
@@ -236,4 +249,5 @@ export interface TaskReceipt {
readonly archivedBy: string | null;
readonly basePointsMinor?: number;
readonly assigneeIds?: readonly string[];
+ readonly stateReason?: string;
}
diff --git a/frontend/src/presentation/domus-tasks.ts b/frontend/src/presentation/domus-tasks.ts
index bc457aa4..bb6e42e3 100644
--- a/frontend/src/presentation/domus-tasks.ts
+++ b/frontend/src/presentation/domus-tasks.ts
@@ -7,12 +7,18 @@ import {textFieldState} from '@vypdev/ha-ui/field-contracts';
import {registerCheckbox} from '@vypdev/ha-ui/checkbox';
import type {CheckboxChangeEvent} from '@vypdev/ha-ui/checkbox';
import {checkboxChangeDetail, checkboxState} from '@vypdev/ha-ui/checkbox-contracts';
+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 {AdministrationView} from '../application/administration-controller';
import type {TaskView} from '../application/task-controller';
import type {TaskRecord} from '../application/task-ports';
-import {categoryLabel, hasTaskText, taskAssignees, taskQuantity, taskScheduleDraft, TASK_PRIORITIES, TASK_TEXT_LIMITS} from '../domain/tasks';
+import {categoryLabel, hasTaskText, taskAssignees, taskQuantity, taskScheduleDraft, taskText, TASK_PRIORITIES, TASK_TEXT_LIMITS} from '../domain/tasks';
import type {Revision} from '../domain/administration';
-import type {TaskCategory, TaskDetail, TaskMaterialUsage, TaskPriority, TaskScheduleDraft} from '../domain/tasks';
+import type {TaskCategory, TaskDetail, TaskMaterialUsage, TaskPriority, TaskProgressTarget, TaskScheduleDraft} from '../domain/tasks';
import {language} from './messages';
import type {Language} from './messages';
import {taskDeadline, taskInstant, taskMessage} from './task-messages';
@@ -27,6 +33,7 @@ import './domus-allocation-settings';
export type TaskIntent = Readonly<{type: 'refresh' | 'more' | 'claim'}>
| Readonly<{type: 'select'; occurrenceId: string}>
| Readonly<{type: 'assign'; occurrenceId: string; revision: Revision; assigneeIds: readonly string[]}>
+ | Readonly<{type: 'transition'; occurrenceId: string; revision: Revision; target: TaskProgressTarget; reason: string}>
| Readonly<{type: 'create'; title: string; description: string; priority: TaskPriority;
categoryId?: string; schedule?: TaskScheduleDraft; basePointsMinor?: number}>
| Readonly<{type: 'createCategory'; label: string}>
@@ -39,9 +46,13 @@ export type TaskIntent = Readonly<{type: 'refresh' | 'more' | 'claim'}>
const EMPTY_SCHEDULE_FIELDS = Object.freeze({date: '', time: '', rule: '', interval: '30', visibility: 'at_completion'});
type ScheduleFields = {[Field in keyof typeof EMPTY_SCHEDULE_FIELDS]: string};
type AssignmentDraft = Readonly<{occurrenceId: string; revision: Revision; assigneeIds: readonly string[]}>;
+type ProgressDraft = Readonly<{occurrenceId: string; revision: Revision; target: TaskProgressTarget; reason: string}>;
function validCategoryLabel(value: string): boolean {
try {categoryLabel(value); return true;} catch {return false;}
}
+function validBlockingReason(value: string): boolean {
+ try {taskText(value, TASK_TEXT_LIMITS.reason, true, true); return true;} catch {return false;}
+}
function quantityInput(value: string, precision: number): string | null {
const trimmed = value.trim();
if (trimmed.length > 64 || !/^[0-9]+(?:[.,][0-9]+)?$/u.test(trimmed)) return null;
@@ -53,14 +64,15 @@ function quantityInput(value: string, precision: number): string | null {
/** Render only verified task facts; emitted intents never select an actor or grant a permission. */
export class DomusTasks extends LitElement {
static properties = {administration: {attribute: false}, assignmentDraft: {state: true}, assignmentError: {state: true},
+ progressDraft: {state: true}, progressError: {state: true},
allocation: {attribute: false}, participantNames: {attribute: false}, view: {attribute: false}, retired: {attribute: false}, language: {attribute: false}, titleDraft: {state: true}, descriptionDraft: {state: true},
categoryDraft: {state: true}, categoryName: {state: true}, categoryEdit: {state: true}, manageOpen: {state: true},
basePointsDraft: {state: true}, basePointsError: {state: true},
titleRequired: {state: true}, priorityDraft: {state: true}, reasonDraft: {state: true}, quantities: {state: true}, quantityError: {state: true}, createOpen: {state: true},
scheduleKind: {state: true}, scheduleError: {state: true}, scheduleInput: {state: true}};
static styles = [styles, css`:host {min-height:0;background:transparent;overflow-wrap:anywhere}.task-header {display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap}
- .task-header h2 {font-size:1.6rem;margin:0} .task-layout {display:grid;gap:20px}.task-layout .card {margin:0}
- .task-layout>div {display:grid;gap:20px;align-content:start} .new-task summary h3 {display:inline} .new-task form {margin-top:20px}
+ .task-header h2 {font-size:1.6rem;margin:0} .task-layout {display:grid;grid-template-columns:minmax(0,1fr);gap:20px}.task-layout .card {margin:0}
+ .task-layout>div {display:grid;grid-template-columns:minmax(0,1fr);gap:20px;align-content:start} .new-task summary h3 {display:inline} .new-task form {margin-top:20px}
h3 {font-size:1.1rem;margin:0 0 16px} textarea {font:inherit;resize:vertical;width:100%;min-height:90px;border:1px solid var(--line);border-radius:10px;
padding:10px 12px;background:var(--surface);color:var(--text)} .task-list {list-style:none;padding:0;margin:0}.task-list li {padding:14px 0;border-bottom:1px solid var(--line)}
.task-link {border:0;border-radius:8px;padding:4px 0;text-align:start;font-weight:700}.task-meta {display:flex;flex-wrap:wrap;gap:8px;color:var(--muted);font-size:.875rem}
@@ -74,7 +86,13 @@ export class DomusTasks extends LitElement {
--vyp-ha-text:var(--text);--vyp-ha-font-family:inherit;--ha-checkbox-border-color:var(--muted);
--ha-checkbox-background-color-hover:var(--canvas);--ha-checkbox-checked-background-color:var(--accent);
--ha-checkbox-checked-background-color-hover:var(--accent);--wa-focus-ring:solid 2px var(--accent)}
- @media(min-width:800px) {.task-layout {grid-template-columns:minmax(0,1fr) minmax(0,1fr)}.task-layout.single {grid-template-columns:1fr}}`];
+ :host {--vyp-ha-surface:var(--surface);--vyp-ha-surface-raised: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-button {--vyp-ha-button-height:44px}
+ .progress {margin-block:24px}.progress h4 {margin-block:0 8px}.progress .field {margin-block:16px}
+ .progress vyp-ha-feedback {margin-block:12px}.task-work-actions[hidden] {display:none}
+ @media(min-width:800px) {.task-layout {grid-template-columns:minmax(0,1fr) minmax(0,1fr)}.task-layout.single {grid-template-columns:minmax(0,1fr)}}`];
declare allocation: AllocationView | null;
declare administration: Pick | null;
declare participantNames: readonly ParticipantName[];
@@ -106,13 +124,18 @@ export class DomusTasks extends LitElement {
private declare assignmentError: boolean;
private submittedAssignment: AssignmentDraft | null = null;
private assignmentFocus: string | null = null;
- private lastForm: 'create' | 'review' | 'category' | 'assignment' = 'create';
+ private declare progressDraft: ProgressDraft | null;
+ private declare progressError: boolean;
+ private submittedProgress: ProgressDraft | null = null;
+ private progressFocus: string | null = null;
+ private lastForm: 'create' | 'review' | 'category' | 'assignment' | 'progress' = 'create';
private focusDetail = false;
constructor() {super(); this.allocation = null; this.participantNames = []; this.view = null; this.retired = false; this.language = 'en'; this.titleDraft = ''; this.titleRequired = false; this.descriptionDraft = '';
this.priorityDraft = 'normal'; this.scheduleKind = 'manual'; this.scheduleError = false; this.scheduleInput = EMPTY_SCHEDULE_FIELDS;
this.createOpen = false; this.reasonDraft = ''; this.quantities = {}; this.quantityError = null;
this.basePointsDraft = ''; this.basePointsError = null;
this.administration = null; this.assignmentDraft = null; this.assignmentError = false;
+ this.progressDraft = null; this.progressError = false;
this.categoryDraft = ''; this.categoryName = ''; this.categoryEdit = null; this.manageOpen = false;}
private text(key: TaskMessageKey): string {return taskMessage(key, this.language);}
private get blocked(): boolean {return this.view?.busy !== false || this.view.readOnly || this.view.records === null
@@ -125,6 +148,7 @@ export class DomusTasks extends LitElement {
this.basePointsDraft, this.scheduleKind, this.scheduleInput]);
}
private reset(): void {
+ this.resetProgress();
this.assignmentDraft = null; this.submittedAssignment = null; this.assignmentFocus = null; this.assignmentError = false;
this.categoryDraft = ''; this.categoryName = ''; this.categoryEdit = null; this.submittedCategory = null; this.manageOpen = false;
this.createOpen = false; this.titleDraft = ''; this.titleRequired = false; this.descriptionDraft = ''; this.priorityDraft = 'normal'; this.reasonDraft = '';
@@ -140,14 +164,30 @@ export class DomusTasks extends LitElement {
|| next != null && this.draftScope !== null && next !== this.draftScope) this.reset();
if (next != null) this.draftScope = next;
const detail = this.view?.detail, key = detail ? JSON.stringify([next, detail.occurrenceId, detail.revision]) : null;
+ const outcome = this.view?.outcome;
if (detail && this.assignmentDraft && (detail.occurrenceId !== this.assignmentDraft.occurrenceId || !detail.allowedActions.includes('assign'))) {
this.assignmentDraft = null; this.submittedAssignment = null; this.assignmentFocus = null;
}
if (detail && this.assignmentDraft && key !== this.detailKey && this.assignmentNeedsReview(detail))
this.assignmentFocus = '#assignment-review';
+ if (detail && this.progressDraft && detail.occurrenceId !== this.progressDraft.occurrenceId) this.resetProgress();
+ if (detail && this.progressDraft) {
+ const newConflict = outcome?.kind === 'rejected' && outcome.reason === 'conflict'
+ && outcome !== changed.get('view')?.outcome;
+ if (this.progressNeedsReview(detail, this.progressDraft) && (key !== this.detailKey || newConflict))
+ this.progressFocus = this.progressTargets(detail).includes(this.progressDraft.target)
+ ? '#task-progress-review' : '#task-progress-editor';
+ else if (changed.get('view')?.detail === null)
+ this.progressFocus = this.progressDraft.target === 'blocked' ? '#task-progress-reason' : '#task-progress-save';
+ }
if (key !== null && key !== this.detailKey) {this.focusDetail = this.view?.phase === 'ready'; this.detailKey = key; this.reasonDraft = ''; this.quantityError = null;
this.quantities = Object.fromEntries(detail!.materials.map(item => [item.lineId, item.plannedQuantity]));}
- const outcome = this.view?.outcome;
+ if (outcome?.kind === 'receipt' && outcome.stage === 'committed' && outcome.action === 'task.transition'
+ && this.progressDraft !== null && this.progressDraft === this.submittedProgress
+ && outcome.occurrenceId === this.progressDraft.occurrenceId && outcome.state === this.progressDraft.target
+ && outcome.stateReason === this.progressDraft.reason
+ && BigInt(outcome.revision) === BigInt(this.progressDraft.revision) + 1n
+ && outcome !== changed.get('view')?.outcome) this.resetProgress('#task-progress-actions vyp-ha-button');
if (outcome?.kind === 'receipt' && outcome.stage === 'committed' && outcome.action === 'task.assign'
&& outcome.occurrenceId === this.assignmentDraft?.occurrenceId && this.assignmentDraft === this.submittedAssignment
&& outcome.assigneeIds !== undefined
@@ -171,14 +211,25 @@ export class DomusTasks extends LitElement {
protected updated(changed: PropertyValues): void {
this.lang = language(this.language, 'en');
if (this.focusDetail) {this.focusDetail = false; this.shadowRoot?.querySelector('#selected-task-title')?.focus();}
- if (changed.has('view') && this.view?.notice === 'invalid_input')
- this.shadowRoot?.querySelector(this.lastForm === 'create' ? '#task-title' : this.lastForm === 'category' ? '#task-category-label'
- : this.lastForm === 'assignment' ? '#assignment-editor' : '#task-reason')?.focus();
+ if (changed.has('view') && this.view?.notice === 'invalid_input') {
+ const field = {create: '#task-title', category: '#task-category-label', assignment: '#assignment-editor',
+ review: '#task-reason', progress: '#task-progress-editor'}[this.lastForm];
+ this.shadowRoot?.querySelector(field)?.focus();
+ }
if (this.assignmentFocus !== null) {
const target = this.renderRoot.querySelector(this.assignmentFocus)
?? this.renderRoot.querySelector('#assignment-editor');
if (target) {this.assignmentFocus = null; queueMicrotask(() => target.focus());}
}
+ if (this.progressFocus !== null && this.view?.phase === 'ready') {
+ const target = this.renderRoot.querySelector(this.progressFocus)
+ ?? this.renderRoot.querySelector('#task-progress-actions vyp-ha-button')
+ ?? this.renderRoot.querySelector('#selected-task-title');
+ if (target) {
+ this.progressFocus = null;
+ requestAnimationFrame(() => {if (target.isConnected) target.focus();});
+ }
+ }
if (changed.has('view') && this.view?.notice === 'category_unavailable')
this.renderRoot.querySelector('#task-category')?.focus();
const outcome = this.view?.outcome;
@@ -189,7 +240,7 @@ export class DomusTasks extends LitElement {
disconnectedCallback(): void {super.disconnectedCallback(); this.reset();}
private intent(detail: TaskIntent): void {
if (this.retired || this.view?.phase !== 'ready' || this.view.busy) return;
- if (['create', 'createCategory', 'renameCategory', 'archiveCategory', 'claim', 'assign', 'complete', 'verify', 'reopen'].includes(detail.type) && this.blocked) return;
+ if (['create', 'createCategory', 'renameCategory', 'archiveCategory', 'claim', 'assign', 'transition', 'complete', 'verify', 'reopen'].includes(detail.type) && this.blocked) return;
this.dispatchEvent(new CustomEvent('domus-task-intent', {detail: Object.freeze(detail), bubbles: true, composed: true}));
}
private scheduleDraft(form: HTMLFormElement): TaskScheduleDraft | undefined {
@@ -371,6 +422,120 @@ export class DomusTasks extends LitElement {
}
this.quantityError = null; this.intent({type: 'complete', materialUsages, ...reviewed === undefined ? {} : {reviewed}});
}
+ private resetProgress(focus: string | null = null): void {
+ this.progressDraft = null;
+ this.submittedProgress = null;
+ this.progressError = false;
+ this.progressFocus = focus;
+ }
+ private progressLabel(target: TaskProgressTarget): TaskMessageKey {
+ if (target === 'in_progress') return 'progressStart';
+ if (target === 'blocked') return 'progressBlock';
+ return 'progressUnblock';
+ }
+ private progressTargets(work: TaskDetail): readonly TaskProgressTarget[] {
+ const targets: TaskProgressTarget[] = [];
+ if (work.state === 'assigned') targets.push('in_progress');
+ if (['available', 'assigned', 'in_progress'].includes(work.state)) targets.push('blocked');
+ if (work.state === 'blocked') targets.push(work.assigneeIds.length ? 'assigned' : 'available');
+ return targets.filter(target => work.allowedActions.includes('transition:' + target));
+ }
+ private progressNeedsReview(work: TaskDetail, draft: ProgressDraft): boolean {
+ const outcome = this.view!.outcome;
+ return draft.occurrenceId !== work.occurrenceId || draft.revision !== work.revision
+ || this.submittedProgress !== null && outcome?.kind === 'rejected' && outcome.reason === 'conflict';
+ }
+ private openProgress(target: TaskProgressTarget): void {
+ const work = this.view?.detail;
+ if (!work || this.blocked || !this.progressTargets(work).includes(target)) return;
+ this.progressDraft = Object.freeze({occurrenceId: work.occurrenceId, revision: work.revision, target, reason: ''});
+ this.submittedProgress = null;
+ this.progressError = false;
+ this.progressFocus = target === 'blocked' ? '#task-progress-reason' : '#task-progress-save';
+ }
+ private changeProgressReason(event: InputEvent): void {
+ if (this.blocked || this.progressDraft === null) return;
+ this.progressDraft = Object.freeze({...this.progressDraft, reason: (event.target as HTMLTextAreaElement).value});
+ this.progressError = false;
+ }
+ private reviewProgress(): void {
+ const draft = this.progressDraft, work = this.view?.detail;
+ if (draft === null || !work || this.blocked || work.occurrenceId !== draft.occurrenceId
+ || !this.progressTargets(work).includes(draft.target)) return;
+ this.progressDraft = Object.freeze({...draft, revision: work.revision});
+ this.submittedProgress = null;
+ this.progressError = false;
+ this.progressFocus = draft.target === 'blocked' && !validBlockingReason(draft.reason)
+ ? '#task-progress-reason' : '#task-progress-save';
+ }
+ private saveProgress(event: SubmitEvent): void {
+ event.preventDefault();
+ const draft = this.progressDraft, work = this.view?.detail;
+ if (draft === null || !work || this.blocked) return;
+ if (this.progressNeedsReview(work, draft) || !this.progressTargets(work).includes(draft.target)) {
+ this.progressFocus = '#task-progress-editor';
+ this.requestUpdate();
+ return;
+ }
+ if (draft.target === 'blocked' && !validBlockingReason(draft.reason)) {
+ this.progressError = true;
+ this.progressFocus = '#task-progress-reason';
+ return;
+ }
+ this.submittedProgress = draft;
+ this.lastForm = 'progress';
+ this.intent({type: 'transition', occurrenceId: draft.occurrenceId, revision: draft.revision,
+ target: draft.target, reason: draft.reason});
+ }
+ private progress(work: TaskDetail) {
+ const draft = this.progressDraft, targets = this.progressTargets(work);
+ if (draft === null && targets.length === 0 && work.state !== 'blocked') return nothing;
+ const review = draft !== null && this.progressNeedsReview(work, draft);
+ const available = draft !== null && targets.includes(draft.target);
+ const invalid = draft?.target === 'blocked' && !validBlockingReason(draft.reason);
+ const showError = invalid && (this.progressError || draft.reason.length > 0);
+ return html`
+ ${work.state === 'blocked' ? html`${this.text('progressCurrentReason')}
+ ${work.stateReason ?? this.text('progressReasonUnavailable')}
` : nothing}
+ ${draft === null ? html`${targets.map(target => html`
+ this.openProgress(target)}>`)}
`
+ : html`
+
+ `}
+ `;
+ }
private get assignmentDiscovery(): 'ready' | 'assignmentLoading' | 'assignmentDenied' | 'assignmentUnavailable' {
const current = this.administration;
if (current === null || current.phase === 'idle' || current.phase === 'loading' || current.phase === 'sending') return 'assignmentLoading';
@@ -379,7 +544,7 @@ export class DomusTasks extends LitElement {
return 'ready';
}
private assignmentName(id: string): string {
- const row = this.administration!.roster!.members.find(row => row.member.memberId === id);
+ const row = this.administration?.roster?.members.find(row => row.member.memberId === id);
return row?.presentation.alias ?? row?.metadata.name ?? this.text('assignmentUnnamed') + ' ' + id;
}
private assignmentNeedsReview(work: TaskDetail): boolean {
@@ -459,6 +624,8 @@ export class DomusTasks extends LitElement {
${this.text('performed')}: ${taskInstant(work.cycle.performedAt, this.language)}
` : nothing}
${work.dependencyReviewRequired ? html`${this.text('dependencyReview')}
` : nothing}
${work.pendingMaterials ? html`${this.text('pendingMaterials')}
` : nothing}
+ ${this.progress(work)}
+
${this.assignment(work)}
${work.allowedActions.includes('claim') ? html`
` : nothing}
${work.completionPoints === 'manager_required' ? html`
${this.text('manualPointsManager')}
` : nothing}
@@ -484,6 +651,7 @@ export class DomusTasks extends LitElement {
@click=${() => {this.lastForm = 'review'; this.intent(action === 'reopen' ? {type: 'reopen', reason: this.reasonDraft}
: {type: 'verify', decision: action === 'approve' ? 'approved' : 'rejected', reason: this.reasonDraft});}}>${this.text(action)}`)}
` : nothing}
+
${this.text('technical')}
- ${this.text('taskId')}
${work.occurrenceId}
- ${this.text('revision')}
- ${work.revision}
`;
}
@@ -495,6 +663,10 @@ export class DomusTasks extends LitElement {
private outcome() {
const result = this.view!.outcome; if (result === null) return nothing;
const kind = result.kind === 'receipt' ? result.stage === 'committed' ? 'saved' : 'historical' : result.kind;
+ if (kind === 'saved' && result.kind === 'receipt' && result.action === 'task.transition') return html`
+
+ ${this.text('technical')}
${this.text('operation')}: ${result.operationId}
`;
const assignmentSaved = kind === 'saved' && result.kind === 'receipt' && result.action === 'task.assign';
const body = assignmentSaved ? 'assignmentSavedBody' : kind === 'saved' && result.kind === 'receipt' && result.state === 'active' ? 'scheduleSaved' : `${kind}Body` as const;
const precisionRequired = result.kind === 'rejected' && result.reason === 'points_precision_two_required';
@@ -533,5 +705,8 @@ export class DomusTasks extends LitElement {
}
registerField();
registerCheckbox();
+registerButton();
+registerCard();
+registerFeedback();
customElements.define('domus-tasks', DomusTasks);
declare global {interface HTMLElementTagNameMap {'domus-tasks': DomusTasks;}}
diff --git a/frontend/src/presentation/task-messages.ts b/frontend/src/presentation/task-messages.ts
index 947bd430..e247281c 100644
--- a/frontend/src/presentation/task-messages.ts
+++ b/frontend/src/presentation/task-messages.ts
@@ -39,6 +39,20 @@ const english = Object.freeze({
assignmentReview: 'Review current assignment', assignmentSaved: 'Assignment saved',
assignmentUnchanged: 'Choose a different assignment to save a change.',
assignmentSavedBody: 'The planned assignees are recorded.', action_assign: 'Assign task',
+ action_transition: 'Change task progress',
+ progressStart: 'Start task', progressBlock: 'Block task', progressUnblock: 'Unblock task',
+ progressSave: 'Save progress', progressCancel: 'Cancel', progressReview: 'Review current task',
+ progressRefresh: 'Refresh current task', progressCurrent: 'Current state', progressProposed: 'Change to',
+ progressVersion: 'Task version', progressReason: 'Reason for blocking', progressCurrentReason: 'Blocking reason',
+ progressReasonHelp: 'Explain the obstacle. Up to 1,000 characters.',
+ progressInvalid: 'Enter a valid reason using up to 1,000 characters.',
+ progressChangedTitle: 'Review the changed task',
+ progressChanged: 'The task changed. Your proposed action and reason are retained. Review the current task before saving.',
+ progressUnavailableTitle: 'Action unavailable',
+ progressUnavailable: 'This action is unavailable for the current task. Refresh or cancel to choose another action.',
+ progressReasonUnavailable: 'The blocking reason is unavailable.',
+ progressReasonHistory: 'The saved blocking reason remains in task history.',
+ progressSaved: 'Task progress saved', progressSavedBody: 'The requested state change is recorded.',
materials: 'Materials used', quantity: 'Actual quantity', quantityHelp: 'Adjust the quantities used, including zero for anything unused.',
wholeQuantity: 'Use whole quantities for this material.', decimalPlaces: 'Maximum decimal places',
quantityInvalid: 'Enter a nonnegative quantity using the precision shown for this material.',
@@ -119,6 +133,20 @@ const spanish: Readonly> = Object.freeze({
assignmentReview: 'Revisar asignación actual', assignmentSaved: 'Asignación guardada',
assignmentUnchanged: 'Elige una asignación diferente para guardar un cambio.',
assignmentSavedBody: 'Las personas asignadas han quedado registradas.', action_assign: 'Asignar tarea',
+ action_transition: 'Cambiar progreso de la tarea',
+ progressStart: 'Iniciar tarea', progressBlock: 'Bloquear tarea', progressUnblock: 'Desbloquear tarea',
+ progressSave: 'Guardar progreso', progressCancel: 'Cancelar', progressReview: 'Revisar tarea actual',
+ progressRefresh: 'Actualizar tarea actual', progressCurrent: 'Estado actual', progressProposed: 'Cambiar a',
+ progressVersion: 'Versión de la tarea', progressReason: 'Motivo del bloqueo', progressCurrentReason: 'Motivo guardado del bloqueo',
+ progressReasonHelp: 'Explica el impedimento. Hasta 1000 caracteres.',
+ progressInvalid: 'Introduce un motivo válido de hasta 1000 caracteres.',
+ progressChangedTitle: 'Revisa la tarea modificada',
+ progressChanged: 'La tarea ha cambiado. Se conservan la acción y el motivo propuestos. Revisa la tarea actual antes de guardar.',
+ progressUnavailableTitle: 'Acción no disponible',
+ progressUnavailable: 'Esta acción no está disponible para la tarea actual. Actualiza o cancela para elegir otra acción.',
+ progressReasonUnavailable: 'El motivo del bloqueo no está disponible.',
+ progressReasonHistory: 'El motivo del bloqueo se conserva en el historial de la tarea.',
+ progressSaved: 'Progreso de la tarea guardado', progressSavedBody: 'El cambio de estado solicitado ha quedado registrado.',
materials: 'Materiales utilizados', quantity: 'Cantidad real', quantityHelp: 'Ajusta las cantidades utilizadas; indica cero si no has usado algo.',
wholeQuantity: 'Usa cantidades enteras para este material.', decimalPlaces: 'Máximo de decimales',
quantityInvalid: 'Introduce una cantidad no negativa con la precisión indicada para este material.',
diff --git a/frontend/tests/e2e/tasks.spec.ts b/frontend/tests/e2e/tasks.spec.ts
index 6f6699a8..7dd3d5b5 100644
--- a/frontend/tests/e2e/tasks.spec.ts
+++ b/frontend/tests/e2e/tasks.spec.ts
@@ -649,3 +649,191 @@ for (const mode of ['native', 'standalone'] as const) {
});
}
}
+
+for (const mode of ['native', 'standalone'] as const) {
+ for (const locale of ['en', 'es'] as const) {
+ test(`progress reason, conflict, recovery and restart in ${mode} ${locale}`, async ({browser, request}, info) => {
+ test.setTimeout(75_000);
+ expect((await request.post(origin(mode) + '/__fixture__/reset')).ok()).toBe(true);
+ const context = await browser.newContext({viewport: {width: locale === 'es' ? 390 : 1280, height: 844}, hasTouch: locale === 'es'});
+ const page = await context.newPage();
+ const t = (english: string, spanish: string) => locale === 'en' ? english : spanish;
+ const contrast = (element: Locator, backgroundProperty: string | null = null) => element.evaluate((node, property) => {
+ const style = getComputedStyle(node);
+ const luminance = (color: string) => {
+ const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1;
+ const context = canvas.getContext('2d')!; context.fillStyle = color; context.fillRect(0, 0, 1, 1);
+ const channels = [...context.getImageData(0, 0, 1, 1).data].slice(0, 3).map(value => {
+ const channel = value / 255; return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
+ };
+ const foreground = luminance(style.color);
+ const background = luminance(property === null ? style.backgroundColor : style.getPropertyValue(property));
+ return (Math.max(foreground, background) + 0.05) / (Math.min(foreground, background) + 0.05);
+ }, backgroundProperty);
+ const activate = async (target: Locator) => {
+ if (locale === 'es') await target.tap();
+ else {await target.focus(); await target.press('Enter');}
+ };
+ const signIn = async () => {
+ if (mode === 'standalone') {
+ await page.getByRole('button', {name: 'Sign in with Home Assistant', exact: true}).click();
+ await page.getByRole('link', {name: 'Continue as fixture user', exact: true}).click();
+ }
+ await page.getByRole('link', {name: /^(Tasks|Tareas)$/u, exact: true}).click();
+ await expect(page.locator('domus-tasks').getByRole('heading', {name: /^(Household tasks|Tareas del hogar)$/u})).toBeVisible();
+ await page.getByRole('combobox', {name: /^(Language|Idioma)$/u}).selectOption(locale);
+ await expect(page.getByRole('link', {name: t('Tasks', 'Tareas'), exact: true})).toBeVisible();
+ };
+ try {
+ const tasks = await open(page, context, mode);
+ await page.getByRole('combobox', {name: 'Language', exact: true}).selectOption(locale);
+ const title = 'Progress 🧰';
+ await tasks.getByLabel(t('Title', 'Título'), {exact: true}).fill(title);
+ await activate(tasks.getByRole('button', {name: t('Create task', 'Crear tarea'), exact: true}));
+ await expect(tasks.getByRole('heading', {name: title, exact: true})).toBeVisible();
+ const list = await (await page.request.get(base(mode) + '/api/v1/tasks/occurrences')).json();
+ const id = list.items.find((item: {title: string}) => item.title === title).occurrence_id;
+ const endpoint = base(mode) + '/api/v1/tasks/occurrences/' + id;
+ const writes: {key: string; body: string; context: string}[] = [];
+ page.on('request', item => {
+ if (item.method() === 'POST' && item.url() === endpoint + '/transition')
+ writes.push({key: item.headers()['idempotency-key'], body: item.postData()!, context: item.headers()['x-domus-context']});
+ });
+ const block = tasks.getByRole('button', {name: t('Block task', 'Bloquear tarea'), exact: true});
+ const unblock = tasks.getByRole('button', {name: t('Unblock task', 'Desbloquear tarea'), exact: true});
+ const save = tasks.getByRole('button', {name: t('Save progress', 'Guardar progreso'), exact: true});
+ const reason = tasks.getByRole('textbox', {name: t('Reason for blocking', 'Motivo del bloqueo'), exact: true});
+ const saved = tasks.getByText(t('Task progress saved', 'Progreso de la tarea guardado'), {exact: true});
+ const cancel = tasks.getByRole('button', {name: t('Cancel', 'Cancelar'), exact: true});
+ const edit = tasks.getByRole('button', {name: t('Change assignment', 'Cambiar asignación'), exact: true});
+ const assign = tasks.getByRole('button', {name: t('Save assignment', 'Guardar asignación'), exact: true});
+ const current = async () => (await (await page.request.get(endpoint)).json()).work;
+ const explanation = 'Waiting for & help\n🧰';
+ await activate(block); await expect(reason).toBeFocused(); await expect(save).toBeDisabled();
+ await reason.fill(' \n\t'); await expect(save).toBeDisabled();
+ await reason.fill('A'.repeat(1001)); await expect(save).toBeDisabled();
+ await reason.fill(explanation);
+ for (const colorScheme of ['light', 'dark'] as const) {
+ await page.emulateMedia({colorScheme});
+ await expect.poll(() => contrast(tasks.getByRole('article', {name: t('Block task', 'Bloquear tarea'), exact: true}))).toBeGreaterThanOrEqual(4.5);
+ await expect.poll(() => contrast(save, '--vyp-ha-primary')).toBeGreaterThanOrEqual(4.5);
+ await page.screenshot({path: info.outputPath('progress-editor-' + mode + '-' + locale + '-' + colorScheme + '.png'), fullPage: true});
+ }
+ await activate(cancel); await expect(block).toBeFocused();
+ for (const colorScheme of ['light', 'dark'] as const) {
+ await page.emulateMedia({colorScheme});
+ await expect.poll(() => contrast(tasks.locator('domus-allocation-settings').getByRole('article'))).toBeGreaterThanOrEqual(4.5);
+ await expect.poll(() => contrast(tasks.locator('domus-allocation-settings').getByRole('button',
+ {name: t('Save policy', 'Guardar política'), exact: true}), '--vyp-ha-primary')).toBeGreaterThanOrEqual(4.5);
+ }
+ expect(writes).toEqual([]);
+ await activate(block); await reason.fill(explanation); await activate(save); await expect(saved).toBeVisible();
+ expect(await current()).toMatchObject({revision: 2, state: 'blocked', state_reason: explanation, assignee_ids: []});
+ await expect(tasks.locator('#task-blocked-reason')).toHaveText(explanation);
+ await activate(unblock); await activate(save); await expect(block).toBeVisible();
+ expect(await current()).toMatchObject({revision: 3, state: 'available', state_reason: '', assignee_ids: []});
+ await activate(edit);
+ const own = tasks.getByRole('checkbox', {name: 'Fictional account a', exact: true});
+ if (locale === 'es') await own.tap(); else {await own.focus(); await own.press('Space');}
+ await activate(assign); await expect(edit).toBeVisible();
+ const assignees = (await current()).assignee_ids;
+ await activate(tasks.getByRole('button', {name: t('Start task', 'Iniciar tarea'), exact: true}));
+ await activate(save); await expect(block).toBeVisible();
+ expect(await current()).toMatchObject({revision: 5, state: 'in_progress', assignee_ids: assignees});
+
+ await activate(block); await reason.fill(explanation);
+ const concurrent = await context.newPage(); await concurrent.goto(base(mode) + '/#tasks');
+ const competing = concurrent.locator('domus-tasks');
+ await competing.getByRole('button', {name: title, exact: true}).click();
+ await competing.getByRole('button', {name: 'Block task', exact: true}).click();
+ await competing.getByRole('textbox', {name: 'Reason for blocking', exact: true}).fill('Another member blocked it');
+ await competing.getByRole('button', {name: 'Save progress', exact: true}).click();
+ await expect(competing.getByText('Task progress saved', {exact: true})).toBeVisible();
+ await concurrent.close();
+ const beforeConflict = writes.length;
+ await activate(save); await expect(save).toBeDisabled(); await expect(reason).toHaveValue(explanation);
+ await expect(tasks.getByText(t('Action unavailable', 'Acción no disponible'), {exact: true})).toBeVisible();
+ await expect(tasks.getByRole('listitem').filter({hasText: title})).toContainText(t('Blocked', 'Bloqueada'));
+ expect(writes).toHaveLength(beforeConflict);
+ await activate(tasks.getByRole('button', {name: t('Refresh current task', 'Actualizar tarea actual'), exact: true}));
+ await expect(reason).toHaveValue(explanation); await activate(cancel);
+ await expect(tasks.locator('#task-blocked-reason')).toHaveText('Another member blocked it');
+ await activate(unblock); await activate(save); await expect(block).toBeVisible();
+ expect(await current()).toMatchObject({revision: 7, state: 'assigned', assignee_ids: assignees});
+ expect((await request.post(origin(mode) + '/__fixture__/operator', {data: {action: 'snapshot'}})).ok()).toBe(true);
+
+ await activate(block); await reason.fill(explanation);
+ const second = await context.newPage(); await second.goto(base(mode) + '/#tasks');
+ const other = second.locator('domus-tasks');
+ await other.getByRole('button', {name: title, exact: true}).click();
+ await other.getByRole('button', {name: 'Change assignment', exact: true}).click();
+ await other.getByRole('button', {name: 'Clear selection', exact: true}).click();
+ await other.getByRole('button', {name: 'Save assignment', exact: true}).click();
+ await expect(other.getByRole('heading', {name: 'Assignment saved', exact: true})).toBeVisible();
+ await second.close();
+ const beforeReview = writes.length;
+ await activate(save);
+ const review = tasks.getByRole('button', {name: t('Review current task', 'Revisar tarea actual'), exact: true});
+ await expect(review).toBeFocused(); await expect(save).toBeDisabled(); await expect(reason).toHaveValue(explanation);
+ await expect(tasks.getByRole('listitem').filter({hasText: title})).toContainText(t('Available', 'Disponible'));
+ expect(writes).toHaveLength(beforeReview);
+ await activate(review); await expect(save).toBeFocused(); expect(writes).toHaveLength(beforeReview);
+ await page.route(endpoint + '/transition', async route => {
+ const committed = await route.fetch({maxRetries: 0, maxRedirects: 0}); expect(committed.status()).toBe(200);
+ await route.abort('connectionreset');
+ });
+ await activate(save);
+ await expect(tasks.getByRole('heading', {name: t('Result not confirmed', 'Resultado sin confirmar'), exact: true})).toBeVisible();
+ await expect(reason).toHaveValue(explanation); await expect(save).toBeDisabled();
+ expect(writes).toHaveLength(beforeReview + 1);
+ const retained = writes.at(-1)!;
+ expect(JSON.parse(retained.body)).toEqual({expected_revision: 8, target: 'blocked', reason: explanation});
+ await page.unroute(endpoint + '/transition'); await page.reload();
+ await expect(tasks.getByRole('heading', {name: 'Household tasks', exact: true})).toBeVisible();
+ await page.getByRole('combobox', {name: 'Language', exact: true}).selectOption(locale);
+ await activate(tasks.getByRole('button', {name: t('Check saved request', 'Comprobar solicitud guardada'), exact: true}).first());
+ await expect(saved).toBeVisible(); await expect(tasks.locator('#task-blocked-reason')).toHaveText(explanation);
+ const originalUrl = base(mode) + '/api/v1/tasks/requests/task.transition/' + retained.key;
+ const original = await (await page.request.get(originalUrl)).json();
+ expect(original).toMatchObject({state: 'committed', result: {revision: 9, state: 'blocked', state_reason: explanation, assignee_ids: []}});
+ const before = await (await request.get(origin(mode) + '/__fixture__/stats')).json();
+ const csrf = await (await page.request.get(base(mode) + '/api/v1/auth/csrf')).json();
+ const headers = {'Content-Type': 'application/json', Origin: origin(mode), 'X-CSRF-Token': csrf.csrf_token,
+ 'Idempotency-Key': retained.key, 'X-Domus-Context': retained.context};
+ const replay = await page.request.post(endpoint + '/transition', {data: retained.body, headers});
+ expect(replay.status()).toBe(200); expect((await replay.json()).operation_id).toBe(original.operation_id);
+ const changed = await page.request.post(endpoint + '/transition', {data: {...JSON.parse(retained.body), reason: 'Changed'}, headers});
+ expect(changed.status()).toBe(409);
+ expect((await (await request.get(origin(mode) + '/__fixture__/stats')).json()).counts).toEqual(before.counts);
+ await page.emulateMedia({colorScheme: 'dark'});
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
+ await page.screenshot({path: info.outputPath('progress-' + mode + '-' + locale + '-dark.png'), fullPage: true});
+ expect((await request.post(origin(mode) + '/__fixture__/operator', {data: {action: 'restart'}})).ok()).toBe(true);
+ await page.reload(); await signIn(); await activate(tasks.getByRole('button', {name: title, exact: true}));
+ await expect(tasks.locator('#task-blocked-reason')).toHaveText(explanation);
+ expect(await (await page.request.get(originalUrl)).json()).toMatchObject({operation_id: original.operation_id, result: original.result});
+ await activate(tasks.getByText(t('Saved requests', 'Solicitudes guardadas'), {exact: true}));
+ await activate(tasks.getByRole('button', {name: t('Dismiss saved request', 'Descartar solicitud guardada'), exact: true}).first());
+ await activate(unblock); await activate(save); await expect(block).toBeVisible();
+ await activate(tasks.getByRole('button', {name: t('Mark done now', 'Marcar como hecha ahora'), exact: true}));
+ await expect(tasks.getByText(t('No approval required', 'No necesita aprobación'), {exact: true})).toBeVisible();
+ expect((await (await page.request.get(endpoint)).json()).cycle.performers).toHaveLength(1);
+ expect((await request.post(origin(mode) + '/__fixture__/operator', {data: {action: 'restore'}})).ok()).toBe(true);
+ await page.reload(); await signIn();
+ const restored = await (await page.request.get(originalUrl)).json();
+ expect(restored).toMatchObject({state: 'historical', operation_id: original.operation_id, result: original.result});
+ expect(await current()).toMatchObject({revision: 7, state: 'assigned', assignee_ids: assignees});
+ const beforeRestoreReplay = await (await request.get(origin(mode) + '/__fixture__/stats')).json();
+ const nextCsrf = await (await page.request.get(base(mode) + '/api/v1/auth/csrf')).json();
+ const historical = await page.request.post(endpoint + '/transition', {data: retained.body,
+ headers: {...headers, 'X-CSRF-Token': nextCsrf.csrf_token}});
+ expect(historical.status()).toBe(200); expect(await historical.json()).toMatchObject({state: 'historical', operation_id: original.operation_id});
+ expect((await (await request.get(origin(mode) + '/__fixture__/stats')).json()).counts).toEqual(beforeRestoreReplay.counts);
+ await info.attach('progress-operation-evidence', {body: JSON.stringify({mode, locale, writes, original: original.operation_id,
+ restartRevision: 9, restoredRevision: 7, assignees}), contentType: 'application/json'});
+ } finally {await context.close();}
+ });
+ }
+}
diff --git a/frontend/tests/page.test.ts b/frontend/tests/page.test.ts
index 9fd97abb..896de6e8 100644
--- a/frontend/tests/page.test.ts
+++ b/frontend/tests/page.test.ts
@@ -449,6 +449,11 @@ test.each([null, {}, [], {type: 'future'}, {type: 'refresh', actor: 'forged'},
{type: 'assign', occurrenceId: 'work-1', revision: '1', assigneeIds: ['same', 'same']},
{type: 'assign', occurrenceId: 'work-1', revision: '1', assigneeIds: ['../foreign']},
{type: 'assign', occurrenceId: 'work-1', revision: '1', assigneeIds: [], householdId: 'foreign'},
+ {type: 'transition', occurrenceId: 'work-1', revision: '1', target: 'completed', reason: ''},
+ {type: 'transition', occurrenceId: 'work-1', revision: '1', target: 'blocked', reason: ''},
+ {type: 'transition', occurrenceId: 'work-1', revision: '1', target: 'blocked', reason: 'Waiting', actor: 'other'},
+ {type: 'transition', occurrenceId: '../work', revision: '1', target: 'blocked', reason: 'Waiting'},
+ {type: 'transition', occurrenceId: 'work-1', revision: 1, target: 'blocked', reason: 'Waiting'},
{type: 'create', title: 1, description: '', priority: 'normal'}, {type: 'create', title: 'Task', description: '', priority: 'future'},
{type: 'complete', materialUsages: true}, {type: 'complete', materialUsages: [{line_id: 'line', quantity: '1.0'}]},
{type: 'verify', decision: 'pending', reason: 'A'}, {type: 'reopen', reason: 1}, {type: 'select', occurrenceId: '../other'},
@@ -459,6 +464,10 @@ test('closed task events preserve semantic user inputs and exact material quanti
const inputs = [{type:'createCategory', label:'Garden'}, {type:'renameCategory', categoryId:'garden', revision:'9007199254740993', label:'Garden'},
{type: 'assign', occurrenceId: 'work-1', revision: '9007199254740993', assigneeIds: ['member-1', 'peer']},
{type: 'assign', occurrenceId: 'work-1', revision: '1', assigneeIds: []},
+ {type: 'transition', occurrenceId: 'work-1', revision: '9007199254740993', target: 'blocked', reason: 'Waiting\n🧰'},
+ {type: 'transition', occurrenceId: 'work-1', revision: '1', target: 'in_progress', reason: ''},
+ {type: 'transition', occurrenceId: 'work-1', revision: '1', target: 'assigned', reason: ''},
+ {type: 'transition', occurrenceId: 'work-1', revision: '1', target: 'available', reason: ''},
{type:'archiveCategory', categoryId:'garden', revision:'9007199254740993'},
{type:'create', title:'Clean', description:'', priority:'normal', categoryId:'garden'}, {type: 'refresh'}, {type: 'more'}, {type: 'claim'}, {type: 'select', occurrenceId: 'work-1'},
{type: 'create', title: 'Clean', description: '', priority: 'normal', basePointsMinor: 0},
@@ -472,6 +481,7 @@ test('the mounted task surface routes only owned semantic intents to its applica
const f = fixture(); f.phase('active'); const {app} = await f.open(); expect(app.tasks?.access?.memberId).toBe('identity-1');
const spies = {create: vi.spyOn(TaskController.prototype, 'create').mockResolvedValue(undefined),
assign: vi.spyOn(TaskController.prototype, 'assign').mockResolvedValue(undefined),
+ transition: vi.spyOn(TaskController.prototype, 'transition').mockResolvedValue(undefined),
createCategory: vi.spyOn(TaskController.prototype, 'createCategory').mockResolvedValue(undefined),
renameCategory: vi.spyOn(TaskController.prototype, 'renameCategory').mockResolvedValue(undefined),
archiveCategory: vi.spyOn(TaskController.prototype, 'archiveCategory').mockResolvedValue(undefined),
@@ -498,6 +508,8 @@ test('the mounted task surface routes only owned semantic intents to its applica
[{type:'renameCategory', categoryId:'garden', revision:'1', label:'Garden'}, 'renameCategory', ['garden', '1', 'Garden']],
[{type:'archiveCategory', categoryId:'garden', revision:'1'}, 'archiveCategory', ['garden', '1']],
[{type: 'more'}, 'more', []], [{type: 'select', occurrenceId: 'work-1'}, 'select', ['work-1']], [{type: 'claim'}, 'claim', []],
+ [{type: 'transition', occurrenceId: 'work-1', revision: '9007199254740993', target: 'blocked', reason: 'Waiting\n🧰'},
+ 'transition', ['work-1', '9007199254740993', 'blocked', 'Waiting\n🧰']],
[{type: 'complete', materialUsages: null}, 'complete', [null]],
[{type: 'complete', materialUsages: null, reviewed: review}, 'complete', [null, review]], [{type: 'verify', decision: 'approved', reason: ''}, 'verify', ['approved', '']],
[{type: 'reopen', reason: 'Repeat'}, 'reopen', ['Repeat']], [{type: 'recover', key: 'original'}, 'recover', ['original']],
diff --git a/frontend/tests/task-component.test.ts b/frontend/tests/task-component.test.ts
index 66fa0f8a..f37e1d94 100644
--- a/frontend/tests/task-component.test.ts
+++ b/frontend/tests/task-component.test.ts
@@ -1,11 +1,13 @@
import {afterEach, expect, test} from 'vitest';
import type {HaTextField} from '@vypdev/ha-ui/field';
import type {HaCheckbox} from '@vypdev/ha-ui/checkbox';
+import type {HaButton} from '@vypdev/ha-ui/button';
+import type {HaFeedback} from '@vypdev/ha-ui/feedback';
import type {AdministrationView} from '../src/application/administration-controller';
import {taskInstant, taskMessage} from '../src/presentation/task-messages';
import type {TaskRecord} from '../src/application/task-ports';
import type {TaskView} from '../src/application/task-controller';
-import type {TaskDetail} from '../src/domain/tasks';
+import type {TaskDetail, TaskReceipt} from '../src/domain/tasks';
import {revisionValue} from '../src/domain/administration';
import type {DomusTasks, TaskIntent} from '../src/presentation/domus-tasks';
import '../src/presentation/domus-tasks';
@@ -31,6 +33,305 @@ async function mount(value: TaskView | null = view(), locale: 'en' | 'es' = 'en'
return {element, root, intents, button, input, text: () => root.textContent!};
}
+async function progressFixture(locale: 'en' | 'es' = 'en', patch: Partial = {}) {
+ const detail: TaskDetail = {...work, state: 'assigned', assigneeIds: ['private-member-id'],
+ allowedActions: ['transition:in_progress', 'transition:blocked', 'complete'], ...patch};
+ const f = await mount(view({detail}), locale);
+ const button = async (label: string) => {
+ const found = [...f.root.querySelectorAll('vyp-ha-button')].find(item => item.state.label === label);
+ if (!found) throw new Error('Missing progress control ' + label);
+ await found.updateComplete;
+ return found;
+ };
+ const settle = async () => {
+ await f.element.updateComplete;
+ await Promise.all([...f.root.querySelectorAll('vyp-ha-button')].map(item => item.updateComplete));
+ await new Promise(resolve => requestAnimationFrame(() => resolve()));
+ };
+ const press = async (label: string) => {(await button(label)).click(); await settle();};
+ return {...f, detail, progressButton: button, press, settle};
+}
+
+test.each([
+ ['en', 'Block task', 'Save progress', 'Cancel', 'Task progress saved'],
+ ['es', 'Bloquear tarea', 'Guardar progreso', 'Cancelar', 'Progreso de la tarea guardado'],
+] as const)('%s progress retains its exact reason and supports cancel, save and confirmation', async (locale, block, save, cancel, confirmed) => {
+ const f = await progressFixture(locale);
+ await f.press(block);
+ const reason = f.root.querySelector('#task-progress-reason')!;
+ expect(f.root.activeElement).toBe(reason);
+ expect((await f.progressButton(save)).disabled).toBe(true);
+ await f.input('task-progress-reason', 'Waiting for \n🧰');
+ expect((await f.progressButton(save)).disabled).toBe(false);
+ await f.press(cancel);
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+ expect(f.root.activeElement).toBe(await f.progressButton(block));
+ expect(f.intents).toEqual([]);
+ await f.press(block);
+ await f.input('task-progress-reason', 'Waiting for \n🧰');
+ await f.press(save);
+ expect(f.intents).toEqual([{type: 'transition', occurrenceId: 'work-1', revision,
+ target: 'blocked', reason: 'Waiting for \n🧰'}]);
+ f.element.view = view({phase: 'loading', busy: true});
+ await f.element.updateComplete;
+ const saved: TaskReceipt = {kind: 'receipt', stage: 'committed', action: 'task.transition',
+ occurrenceId: 'work-1', operationId: 'progress-op', revision: revisionValue('2'),
+ state: 'blocked', stateReason: 'Waiting for \n🧰', cycle: null, archivedBy: null};
+ f.element.view = view({detail: {...f.detail, state: 'blocked', revision: revisionValue('2'),
+ stateReason: saved.stateReason, allowedActions: ['transition:assigned']}, outcome: saved});
+ await f.element.updateComplete;
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+ expect(f.root.querySelector('#task-progress-result')?.state?.title).toBe(confirmed);
+ expect(f.root.querySelector('#task-blocked-reason')?.textContent).toBe(saved.stateReason);
+ expect(f.root.querySelector('img,script')).toBeNull();
+});
+
+test.each([
+ {state: 'assigned', assigneeIds: ['private-member-id'], target: 'in_progress', label: 'Start task'},
+ {state: 'blocked', assigneeIds: ['private-member-id'], target: 'assigned', label: 'Unblock task'},
+ {state: 'blocked', assigneeIds: [], target: 'available', label: 'Unblock task'},
+] as const)('$label confirms its $target target before emitting an exact progress command', async ({state, assigneeIds, target, label}) => {
+ const f = await progressFixture('en', {state, assigneeIds, stateReason: state === 'blocked' ? 'Waiting' : '',
+ allowedActions: ['transition:' + target]});
+ await f.press(label);
+ expect(f.intents).toEqual([]);
+ expect(f.root.querySelector('#task-progress-reason')).toBeNull();
+ expect(f.root.querySelector('#task-progress-version')?.textContent).toContain('1');
+ await f.press('Save progress');
+ expect(f.intents).toEqual([{type: 'transition', occurrenceId: 'work-1', revision, target, reason: ''}]);
+});
+
+test('progress validates meaningful text and Unicode bounds before any intent', async () => {
+ const f = await progressFixture();
+ await f.press('Block task');
+ const form = f.root.querySelector('#task-progress-editor')!;
+ form.dispatchEvent(new SubmitEvent('submit', {cancelable: true}));
+ await f.settle();
+ expect(f.intents).toEqual([]);
+ expect(f.root.activeElement).toBe(f.root.querySelector('#task-progress-reason'));
+ expect(f.root.querySelector('[role="alert"]')?.textContent).toContain('Enter a valid reason');
+ for (const reason of [' \n\t', 'A\u0000B', '\ud800', '🧰'.repeat(1001)]) {
+ await f.input('task-progress-reason', reason);
+ expect((await f.progressButton('Save progress')).disabled).toBe(true);
+ form.dispatchEvent(new SubmitEvent('submit', {cancelable: true}));
+ expect(f.intents).toEqual([]);
+ }
+ await f.input('task-progress-reason', '🧰'.repeat(1000));
+ expect((await f.progressButton('Save progress')).disabled).toBe(false);
+ await f.press('Save progress');
+ expect(f.intents[0]).toMatchObject({target: 'blocked', reason: '🧰'.repeat(1000)});
+});
+
+test('a competing progress change retains the reason and requires separate review and save', async () => {
+ const f = await progressFixture();
+ await f.press('Block task');
+ await f.input('task-progress-reason', 'My retained reason');
+ await f.press('Save progress');
+ f.element.view = view({detail: {...f.detail, revision: revisionValue('2'), assigneeIds: ['peer']},
+ outcome: {kind: 'rejected', reason: 'conflict', correlationId: 'safe-conflict'}});
+ await f.element.updateComplete;
+ expect((f.root.querySelector('#task-progress-reason') as HTMLTextAreaElement).value).toBe('My retained reason');
+ expect((await f.progressButton('Save progress')).disabled).toBe(true);
+ expect(f.intents).toHaveLength(1);
+ await f.press('Review current task');
+ expect(f.root.activeElement).toBe(await f.progressButton('Save progress'));
+ expect((await f.progressButton('Save progress')).disabled).toBe(false);
+ expect(f.intents).toHaveLength(1);
+ await f.press('Save progress');
+ expect(f.intents[1]).toEqual({type: 'transition', occurrenceId: 'work-1', revision: '2',
+ target: 'blocked', reason: 'My retained reason'});
+});
+
+test('an unavailable progress target retains the proposal and offers refresh or cancellation', async () => {
+ const f = await progressFixture();
+ await f.press('Block task');
+ await f.input('task-progress-reason', 'My retained reason');
+ f.element.view = view({detail: {...f.detail, revision: revisionValue('2'), state: 'blocked',
+ stateReason: 'The other member blocked it', allowedActions: ['transition:assigned']}});
+ await f.element.updateComplete;
+ expect((await f.progressButton('Save progress')).disabled).toBe(true);
+ expect(f.root.querySelector('#task-progress-unavailable')?.state?.message).toContain('This action is unavailable');
+ expect((f.root.querySelector('#task-progress-reason') as HTMLTextAreaElement).value).toBe('My retained reason');
+ await f.press('Refresh current task');
+ expect(f.intents).toEqual([{type: 'refresh'}]);
+ await f.press('Cancel');
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+ expect(f.root.querySelector('#task-blocked-reason')?.textContent).toBe('The other member blocked it');
+});
+
+test('recoverable loading preserves a progress draft while scope retirement clears it', async () => {
+ const f = await progressFixture();
+ await f.press('Block task');
+ await f.input('task-progress-reason', 'A retained explanation');
+ f.element.view = view({phase: 'loading', busy: true});
+ await f.element.updateComplete;
+ f.element.view = view({detail: f.detail, notice: 'unavailable'});
+ await f.element.updateComplete;
+ expect((f.root.querySelector('#task-progress-reason') as HTMLTextAreaElement).value).toBe('A retained explanation');
+ f.element.view = view({detail: f.detail, scopeKey: 'different-household'});
+ await f.element.updateComplete;
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+ expect(f.intents).toEqual([]);
+});
+
+test.each([
+ {state: 'available', assigneeIds: [], allowedActions: ['transition:in_progress']},
+ {state: 'assigned', assigneeIds: ['private-member-id'], allowedActions: []},
+ {state: 'blocked', assigneeIds: ['private-member-id'], allowedActions: ['transition:available']},
+ {state: 'completed', assigneeIds: ['private-member-id'], allowedActions: ['transition:blocked']},
+] as const)('progress state and matching hint are both required %#', async patch => {
+ const f = await progressFixture('en', {...patch, stateReason: 'Saved explanation'});
+ expect(f.root.querySelectorAll('#task-progress-actions vyp-ha-button')).toHaveLength(0);
+});
+
+test('read-only access disables offered progress controls', async () => {
+ const f = await progressFixture();
+ f.element.view = view({detail: f.detail, readOnly: true});
+ await f.element.updateComplete;
+ expect((await f.progressButton('Start task')).disabled).toBe(true);
+ expect((await f.progressButton('Block task')).disabled).toBe(true);
+ await f.press('Block task');
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+ expect(f.intents).toEqual([]);
+});
+
+test('a blocking reason remains readable and inert without mutation authority', async () => {
+ const reason = 'Waiting for
\n🧰';
+ const f = await progressFixture('en', {state: 'blocked', stateReason: reason, allowedActions: []});
+ expect(f.root.querySelector('#task-blocked-reason')?.textContent).toBe(reason);
+ expect(f.root.querySelector('img,script')).toBeNull();
+});
+
+test('only the matching submitted progress receipt closes the editor at int64 precision', async () => {
+ const captured = revisionValue('9223372036854775806');
+ const next = revisionValue('9223372036854775807');
+ const f = await progressFixture('en', {revision: captured});
+ await f.press('Block task');
+ await f.input('task-progress-reason', 'Waiting');
+ await f.press('Save progress');
+ const saved: TaskReceipt = {kind: 'receipt', stage: 'committed', action: 'task.transition', operationId: 'progress-op',
+ occurrenceId: 'work-1', revision: next, state: 'blocked', stateReason: 'Waiting', cycle: null, archivedBy: null};
+ for (const patch of [
+ {stage: 'historical', archivedBy: 'restore-op'},
+ {occurrenceId: 'different-task'},
+ {revision: captured},
+ {state: 'in_progress'},
+ {stateReason: 'Different reason'},
+ ] satisfies Partial[]) {
+ f.element.view = view({detail: f.detail, outcome: {...saved, ...patch}});
+ await f.element.updateComplete;
+ expect(f.root.querySelector('#task-progress-editor')).not.toBeNull();
+ }
+ f.element.view = view({detail: {...f.detail, revision: next, state: 'blocked', stateReason: 'Waiting', allowedActions: []}, outcome: saved});
+ await f.element.updateComplete;
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+});
+
+
+test('a same-revision server conflict needs one explicit review and a separate save', async () => {
+ const f = await progressFixture();
+ await f.press('Start task'); await f.press('Save progress');
+ const conflict = {kind: 'rejected', reason: 'conflict', correlationId: 'safe-conflict'} as const;
+ f.element.view = view({detail: f.detail, outcome: conflict}); await f.settle();
+ expect((await f.progressButton('Save progress')).disabled).toBe(true);
+ expect(f.root.activeElement).toBe(await f.progressButton('Review current task'));
+ f.element.view = view({detail: f.detail, outcome: conflict}); await f.settle();
+ await f.press('Review current task');
+ expect(f.intents).toHaveLength(1);
+ expect((await f.progressButton('Save progress')).disabled).toBe(false);
+ await f.press('Save progress'); expect(f.intents).toHaveLength(2);
+});
+
+test('reviewing a changed blank blocking draft returns focus to its required reason', async () => {
+ const f = await progressFixture();
+ await f.press('Block task');
+ f.element.view = view({detail: {...f.detail, revision: revisionValue('2')}}); await f.settle();
+ await f.press('Review current task');
+ expect(f.root.activeElement).toBe(f.root.querySelector('#task-progress-reason'));
+ expect((await f.progressButton('Save progress')).disabled).toBe(true);
+ expect(f.intents).toEqual([]);
+});
+
+test('start confirmation survives unavailable reads and task selection retires its proposal', async () => {
+ const f = await progressFixture();
+ await f.press('Start task');
+ f.element.view = view({phase: 'loading', busy: true}); await f.settle();
+ f.element.view = view({detail: f.detail, notice: 'unavailable'}); await f.settle();
+ expect(f.root.activeElement).toBe(await f.progressButton('Save progress'));
+ f.element.view = view({detail: {...f.detail, occurrenceId: 'different-task'}}); await f.settle();
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+ expect(f.intents).toEqual([]);
+});
+
+test('progress event handlers reject retired controls and state changes before rendering', async () => {
+ const f = await progressFixture();
+ const trigger = await f.progressButton('Block task');
+ const press = (control: Element) => control.dispatchEvent(new CustomEvent('ha-press-request'));
+ f.element.view = view({detail: null}); press(trigger); await f.settle();
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+ f.element.view = view({detail: f.detail}); await f.settle();
+ const current = await f.progressButton('Block task');
+ f.element.view = view({detail: f.detail, readOnly: true}); press(current); await f.settle();
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+ f.element.view = view({detail: f.detail}); await f.settle();
+ const unavailable = await f.progressButton('Block task');
+ f.element.view = view({detail: {...f.detail, allowedActions: []}}); press(unavailable); await f.settle();
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+ f.element.view = view({detail: f.detail}); await f.settle();
+ await f.press('Block task'); await f.input('task-progress-reason', 'Keep this draft');
+ const form = f.root.querySelector('#task-progress-editor')!;
+ const reason = f.root.querySelector('#task-progress-reason')!;
+ const submit = () => form.dispatchEvent(new SubmitEvent('submit', {cancelable: true}));
+ f.element.view = view({detail: f.detail, readOnly: true});
+ reason.value = 'Ignore this stale input'; reason.dispatchEvent(new InputEvent('input')); submit(); await f.settle();
+ f.element.view = view({detail: f.detail}); await f.settle();
+ expect(reason.value).toBe('Keep this draft');
+ f.element.view = view({detail: null}); submit(); await f.settle();
+ f.element.view = view({detail: f.detail}); await f.settle();
+ f.element.view = view({detail: {...f.detail, occurrenceId: 'another-task'}}); submit(); await f.settle();
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+ submit(); reason.dispatchEvent(new InputEvent('input')); await f.settle();
+ expect(f.intents).toEqual([]);
+});
+
+test('a target revoked at the same revision cannot be submitted or reviewed by a stale control', async () => {
+ const f = await progressFixture();
+ await f.press('Block task'); await f.input('task-progress-reason', 'Waiting');
+ const form = f.root.querySelector('#task-progress-editor')!;
+ f.element.view = view({detail: {...f.detail, revision: revisionValue('2')}}); await f.settle();
+ const review = await f.progressButton('Review current task');
+ const press = () => review.dispatchEvent(new CustomEvent('ha-press-request'));
+ f.element.view = view({detail: null}); press();
+ f.element.view = view({detail: {...f.detail, revision: revisionValue('2')}, readOnly: true}); press();
+ f.element.view = view({detail: {...f.detail, occurrenceId: 'other-task'}}); press();
+ f.element.view = view({detail: {...f.detail, revision: revisionValue('2'), allowedActions: []}}); press(); await f.settle();
+ form.dispatchEvent(new SubmitEvent('submit', {cancelable: true})); await f.settle();
+ expect(f.root.activeElement).toBe(form);
+ f.element.view = view({detail: {...f.detail, allowedActions: []}}); await f.settle();
+ form.dispatchEvent(new SubmitEvent('submit', {cancelable: true})); await f.settle();
+ expect(f.intents).toEqual([]);
+ await f.press('Cancel'); press(); await f.settle();
+ expect(f.root.querySelector('#task-progress-editor')).toBeNull();
+});
+
+test('a pending focus survives a temporarily absent detail without focusing detached controls', async () => {
+ const f = await progressFixture();
+ const trigger = await f.progressButton('Start task');
+ trigger.dispatchEvent(new CustomEvent('ha-press-request'));
+ f.element.view = view({detail: null}); await f.settle();
+ f.element.view = view({detail: f.detail}); await f.settle();
+ expect(f.root.activeElement).toBe(await f.progressButton('Save progress'));
+ (await f.progressButton('Cancel')).dispatchEvent(new CustomEvent('ha-press-request'));
+ await f.element.updateComplete;
+ f.element.remove(); await new Promise(resolve => requestAnimationFrame(() => resolve()));
+ expect(f.intents).toEqual([]);
+});
+
+test('a blocked legacy detail has a readable missing-reason fallback', async () => {
+ const f = await progressFixture('en', {state: 'blocked', stateReason: undefined, allowedActions: []});
+ expect(f.root.querySelector('#task-blocked-reason')?.textContent).toBe('The blocking reason is unavailable.');
+});
+
function assignmentRoster(): Pick {
const member = {memberId: 'private-member-id', haUserId: context.subject, role: 'adult' as const,
status: 'active' as const, revision, exceptions: []};
@@ -53,6 +354,22 @@ async function assignmentFixture(locale: 'en' | 'es' = 'en', patch: Partial {
+ const f = await assignmentFixture('en', {allowedActions: ['assign', 'transition:blocked', 'complete']});
+ f.button('Change assignment').click(); await f.element.updateComplete;
+ await f.select(0, true);
+ const editor = f.root.querySelector('#assignment-editor');
+ const trigger = f.root.querySelector('#task-progress-blocked')!;
+ await trigger.updateComplete; trigger.click(); await f.element.updateComplete;
+ expect(f.root.querySelector('.task-work-actions')?.hasAttribute('hidden')).toBe(true);
+ expect(f.root.querySelector('#assignment-editor')).toBe(editor);
+ const cancel = [...f.root.querySelectorAll('vyp-ha-button')].find(button => button.state.label === 'Cancel')!;
+ await cancel.updateComplete; cancel.click(); await f.element.updateComplete;
+ expect(f.root.querySelector('.task-work-actions')?.hasAttribute('hidden')).toBe(false);
+ expect(f.root.querySelector('vyp-ha-checkbox')?.checked).toBe(true);
+ expect(f.intents).toEqual([]);
+});
+
test.each([
['en', []], ['es', []],
['en', ['peer']], ['es', ['peer']],
diff --git a/frontend/tests/task-controller.test.ts b/frontend/tests/task-controller.test.ts
index 51f5b87b..9f2db573 100644
--- a/frontend/tests/task-controller.test.ts
+++ b/frontend/tests/task-controller.test.ts
@@ -28,6 +28,118 @@ function fixture() {
const controller = new TaskController('native', identity, server, journal, clock, entropy);
return {controller, server, identity, session, storage, journal, clock, entropy, setNow: (value: number) => {now = value;}, advance: () => {now = 100000;}};
}
+test.each([
+ {state: 'in_progress', revision: '2', allowedActions: ['transition:blocked'], notice: 'conflict'},
+ {state: 'blocked', revision: '2', allowedActions: ['transition:assigned'], notice: 'conflict'},
+ {state: 'assigned', revision: '1', allowedActions: [], notice: 'action_not_allowed'},
+] as const)('refused progress refreshes both list and selected $state facts before another decision', async current => {
+ const f = fixture();
+ const initial: TaskDetail = {...detail, state: 'assigned', assigneeIds: ['member-1'], allowedActions: ['transition:blocked']};
+ f.server.list.mockReturnValue(read({items: [initial], nextCursor: null}));
+ f.server.detail.mockReturnValue(read(initial));
+ await f.controller.refresh(); await f.controller.select('work-1');
+ const changed: TaskDetail = {...initial, state: current.state, revision: revisionValue(current.revision),
+ stateReason: current.state === 'blocked' ? 'A competing reason' : '', allowedActions: current.allowedActions};
+ f.server.list.mockReturnValue(read({items: [changed], nextCursor: null}));
+ f.server.detail.mockReturnValue(read(changed));
+ await f.controller.transition('work-1', revision, 'blocked', 'My retained reason');
+ expect(f.controller.view.notice).toBe(current.notice);
+ expect(f.controller.view.detail).toEqual(changed);
+ expect(f.controller.view.page?.items).toEqual([changed]);
+ expect(f.server.list).toHaveBeenCalledTimes(2);
+ expect(f.server.send).not.toHaveBeenCalled();
+ expect(f.entropy.requestKey).not.toHaveBeenCalled();
+ expect(f.controller.view.records).toEqual([]);
+});
+
+test.each(['unavailable', 'forbidden'] as const)('a refused progress list refresh handles %s without stale list facts', async reason => {
+ const f = fixture();
+ f.server.detail.mockReturnValue(read({...detail, allowedActions: ['transition:blocked']}));
+ await f.controller.refresh(); await f.controller.select('work-1');
+ const changed: TaskDetail = {...detail, state: 'in_progress', revision: revisionValue('2'), allowedActions: ['transition:blocked']};
+ f.server.detail.mockReturnValue(read(changed));
+ f.server.list.mockImplementationOnce(() => ({result: Promise.reject(new EntryReadError(reason)), cancel: vi.fn()}));
+ await f.controller.transition('work-1', revision, 'blocked', 'My retained reason');
+ expect(f.controller.view.notice).toBe(reason);
+ expect(f.controller.view.page).toBeNull();
+ expect(f.controller.view.detail).toEqual(reason === 'forbidden' ? null : changed);
+ expect(f.server.send).not.toHaveBeenCalled();
+ expect(f.entropy.requestKey).not.toHaveBeenCalled();
+});
+
+test('progress preserves a lost original and recovers once under current facts', async () => {
+ const f = fixture();
+ await f.controller.transition('work-1', revision, 'blocked', 'Waiting');
+ expect(f.server.send).not.toHaveBeenCalled();
+ await f.controller.refresh();
+ f.server.detail.mockReturnValue(read({...detail, allowedActions: ['transition:blocked']}));
+ await f.controller.select('work-1');
+ f.server.send.mockImplementationOnce(async () => {
+ f.server.detail.mockReturnValue(read({...detail, revision: revisionValue('2'), state: 'blocked',
+ stateReason: 'Waiting', allowedActions: ['transition:available']}));
+ return {kind: 'uncertain'};
+ });
+ await f.controller.transition('work-1', revision, 'blocked', 'Waiting');
+ const original = f.server.send.mock.calls[0][0];
+ expect(original).toEqual({key: 'key-1', command: {action: 'task.transition', occurrenceId: 'work-1',
+ payload: {expected_revision: revision, target: 'blocked', reason: 'Waiting'}}});
+ expect(f.controller.view.records?.[0]).toMatchObject({stage: 'uncertain', command: original.command});
+ await f.controller.transition('work-1', revisionValue('2'), 'available', '');
+ expect(f.controller.view.notice).toBe('previous_request_unresolved');
+ f.server.original.mockReturnValue(read({...saved, action: 'task.transition', revision: revisionValue('2'),
+ state: 'blocked', stateReason: 'Waiting'}));
+ await f.controller.recover('key-1');
+ expect(f.server.original).toHaveBeenCalledWith({...original, operationId: null}, context);
+ expect(f.server.send).toHaveBeenCalledOnce();
+ expect(f.controller.view.detail).toMatchObject({state: 'blocked', revision: '2', stateReason: 'Waiting'});
+});
+
+test('progress conflict retains its selected target and shows refreshed competing facts', async () => {
+ const f = fixture();
+ await f.controller.refresh();
+ f.server.detail.mockReturnValue(read({...detail, allowedActions: ['transition:blocked']}));
+ await f.controller.select('work-1');
+ f.server.detail.mockReturnValue(read({...detail, revision: revisionValue('2'), allowedActions: ['transition:blocked']}));
+ await f.controller.transition('work-1', revision, 'blocked', 'My reason');
+ expect(f.controller.view.notice).toBe('conflict');
+ expect(f.controller.view.detail?.revision).toBe('2');
+ expect(f.server.send).not.toHaveBeenCalled();
+ await f.controller.transition('another-task', revisionValue('2'), 'blocked', 'My reason');
+ expect(f.server.send).not.toHaveBeenCalled();
+ f.server.send.mockImplementationOnce(async () => {
+ f.server.detail.mockReturnValue(read({...detail, revision: revisionValue('3'), state: 'blocked',
+ stateReason: 'A competing reason', allowedActions: ['transition:available']}));
+ return {kind: 'rejected', reason: 'conflict', correlationId: 'safe-conflict'};
+ });
+ await f.controller.transition('work-1', revisionValue('2'), 'blocked', 'My reason');
+ expect(f.controller.view.outcome).toMatchObject({kind: 'rejected', reason: 'conflict'});
+ expect(f.controller.view.detail).toMatchObject({state: 'blocked', revision: '3', stateReason: 'A competing reason'});
+ expect(f.controller.view.records?.[0]).toMatchObject({command: {
+ payload: {expected_revision: '2', target: 'blocked', reason: 'My reason'}}});
+});
+
+test('progress uses current hints, scope and command denial before further disclosure', async () => {
+ const f = fixture();
+ await f.controller.refresh();
+ await f.controller.select('work-1');
+ await f.controller.transition('work-1', revision, 'blocked', 'Waiting');
+ expect(f.controller.view.notice).toBe('action_not_allowed');
+ expect(f.server.send).not.toHaveBeenCalled();
+ f.server.detail.mockReturnValue(read({...detail, allowedActions: ['transition:blocked']}));
+ await f.controller.select('work-1');
+ f.server.send.mockResolvedValueOnce({kind: 'rejected', reason: 'forbidden', correlationId: 'safe-denial'});
+ await f.controller.transition('work-1', revision, 'blocked', 'Waiting');
+ expect(f.controller.view.notice).toBe('forbidden');
+ expect(f.controller.view.detail).toBeNull();
+ expect(f.controller.view.records).toBeNull();
+ await f.controller.refresh();
+ await f.controller.select('work-1');
+ f.server.access.mockReturnValue(read({...f.controller.view.access!, householdId: 'foreign'}));
+ await f.controller.transition('work-1', revision, 'blocked', 'Waiting');
+ expect(f.controller.view.notice).toBe('context_changed');
+ expect(f.server.send).toHaveBeenCalledOnce();
+});
+
test('assignment refreshes current authority and preserves a lost original across recovery', async () => {
const f = fixture(); await f.controller.refresh();
await f.controller.assign('work-1', revision, ['member-2']);
diff --git a/frontend/tests/task-http.test.ts b/frontend/tests/task-http.test.ts
index 4a576383..884e27db 100644
--- a/frontend/tests/task-http.test.ts
+++ b/frontend/tests/task-http.test.ts
@@ -50,6 +50,69 @@ function fixture(mode: 'native' | 'standalone' = 'standalone') {
}
afterEach(() => vi.useRealTimers());
+test.each((['native', 'standalone'] as const).flatMap(mode =>
+ (['in_progress', 'blocked', 'assigned', 'available'] as const).map(target => ({mode, target}))))(
+ '$mode progress to $target binds its exact original state and reason', async ({mode, target}) => {
+ const f = fixture(mode);
+ const reason = target === 'blocked' ? 'Waiting for parts\n🧰' : '';
+ const command = taskCommand({action: 'task.transition', occurrenceId: 'work-1',
+ payload: {expected_revision: REV, target, reason}})!;
+ const request = {key: 'progress-key', command};
+ const saved = {...receipt(1), result: {...receipt(1).result,
+ state: target, state_reason: reason, assignee_ids: target === 'available' ? [] : ['member-1']}};
+ f.transport.mockResolvedValueOnce(reply({csrf_token: 'c'.repeat(64)})).mockResolvedValueOnce(reply(saved));
+ expect(await f.server.send(request, context)).toMatchObject({
+ kind: 'receipt', action: 'task.transition', revision: NEXT, state: target, stateReason: reason});
+ const [path, init] = f.transport.mock.calls[1];
+ expect(path).toBe(f.target.applicationBase + 'api/v1/tasks/occurrences/work-1/transition');
+ expect(init.method).toBe('POST');
+ expect(init.body).toBe('{"expected_revision":' + REV + ',"target":' + JSON.stringify(target)
+ + ',"reason":' + JSON.stringify(reason) + '}');
+ expect(new Headers(init.headers).get('Idempotency-Key')).toBe('progress-key');
+ f.transport.mockResolvedValueOnce(reply({...saved,
+ action: 'task.transition', command_key: 'progress-key', delivery: 'pending'}));
+ expect(await f.server.original({...request, operationId: 'op-1'}, context).result)
+ .toMatchObject({kind: 'receipt', state: target, stateReason: reason});
+ expect(f.transport.mock.calls[2][0]).toBe(f.target.applicationBase
+ + 'api/v1/tasks/requests/task.transition/progress-key');
+ });
+
+test.each([
+ {state: 'in_progress'},
+ {state_reason: 'A different reason'},
+ {occurrence_id: 'another-task'},
+ {revision: REV},
+])('a progress receipt with a different bound fact %# remains uncertain', async changes => {
+ const f = fixture();
+ const command = taskCommand({action: 'task.transition', occurrenceId: 'work-1',
+ payload: {expected_revision: REV, target: 'blocked', reason: 'Waiting'}})!;
+ const saved = {...receipt(1), result: {...receipt(1).result, state: 'blocked', state_reason: 'Waiting', ...changes}};
+ f.transport.mockResolvedValueOnce(reply({csrf_token: 'c'.repeat(64)})).mockResolvedValueOnce(reply(saved));
+ expect(await f.server.send({key: 'progress-key', command}, context)).toEqual({kind: 'uncertain'});
+ f.transport.mockResolvedValueOnce(reply({...saved,
+ action: 'task.transition', command_key: 'progress-key', delivery: 'pending'}));
+ await expect(f.server.original({key: 'progress-key', command, operationId: 'op-1'}, context).result)
+ .rejects.toThrow('invalid_response');
+});
+
+test('task detail preserves the exact current blocking reason', async () => {
+ const f = fixture();
+ const raw = detail();
+ raw.work.state = 'blocked';
+ raw.work.state_reason = 'Waiting for \n🧰';
+ f.transport.mockResolvedValueOnce(reply(raw));
+ expect(await f.server.detail('work-1', 'home', context).result)
+ .toMatchObject({state: 'blocked', stateReason: raw.work.state_reason});
+});
+
+test.each([null, 1, '', ' \n\t', '\u0000Invalid', '\ud800', '🧰'.repeat(1001)])(
+ 'invalid current blocking reason %# is rejected', async state_reason => {
+ const f = fixture();
+ const raw = detail();
+ f.transport.mockResolvedValueOnce(reply({...raw, work: {...raw.work, state: 'blocked', state_reason}}));
+ await expect(f.server.detail('work-1', 'home', context).result).rejects.toThrow('invalid_response');
+ });
+
test.each(['native', 'standalone'] as const)('%s assignment uses PUT and binds the original assignee set', async mode => {
const f = fixture(mode);
const command = taskCommand({action: 'task.assign', occurrenceId: 'work-1',
diff --git a/frontend/tests/task-journal.test.ts b/frontend/tests/task-journal.test.ts
index 87212b86..9ee687be 100644
--- a/frontend/tests/task-journal.test.ts
+++ b/frontend/tests/task-journal.test.ts
@@ -10,6 +10,25 @@ function fixture() {
const storage: OwnedStorage = {getItem: key => data.get(key) ?? null, setItem: (key, value) => {data.set(key, value);}, removeItem: key => {data.delete(key);}};
return {data, storage, journal: new TaskSessionJournal(storage)};
}
+test('progress and prior creation and assignment requests coexist with their frozen bodies', () => {
+ const f = fixture();
+ f.journal.open(scope, 100);
+ f.journal.prepare('create', command, 100);
+ f.journal.record('create', 'committed', 'create-operation', 101);
+ const assignment = taskCommand({action: 'task.assign', occurrenceId: 'work-1',
+ payload: {expected_revision: '1', assignee_ids: ['member-1']}})!;
+ f.journal.prepare('assignment', assignment, 102);
+ f.journal.record('assignment', 'committed', 'assignment-operation', 103);
+ const progress = taskCommand({action: 'task.transition', occurrenceId: 'work-1',
+ payload: {expected_revision: '9007199254740993', target: 'blocked', reason: 'Waiting\n🧰'}})!;
+ f.journal.prepare('progress', progress, 104);
+ f.journal.record('progress', 'uncertain', null, 105);
+ const reopened = new TaskSessionJournal(f.storage).open(scope, 106);
+ expect(reopened.map(record => record.command)).toEqual([command, assignment, progress]);
+ expect(reopened[2]).toMatchObject({key: 'progress', scope, stage: 'uncertain', operationId: null});
+ expect(Object.isFrozen(reopened[2].command.payload)).toBe(true);
+ expect(new TaskSessionJournal(f.storage).open({...scope, memberId: 'other'}, 107)).toEqual([]);
+});
test('assignment and older creation originals coexist across reload with frozen identities', () => {
const f = fixture(); f.journal.open(scope, 100);
f.journal.prepare('older-create', command, 100);
diff --git a/frontend/tests/tasks.test.ts b/frontend/tests/tasks.test.ts
index 401bbba5..b787e225 100644
--- a/frontend/tests/tasks.test.ts
+++ b/frontend/tests/tasks.test.ts
@@ -7,6 +7,54 @@ const complete = {action: 'task.complete', occurrenceId: 'work-1', payload: {
expected_revision: revision, performer_ids: ['member-1'], performed_at: '9223372036854775807',
material_usages: [{line_id: 'line-1', quantity: '3.333333'}]}};
+test.each([
+ {target: 'in_progress', reason: ''},
+ {target: 'blocked', reason: ' Waiting for parts\nThen inspect\t🧰 '},
+ {target: 'assigned', reason: ''},
+ {target: 'available', reason: ''},
+ {target: 'blocked', reason: '🧰'.repeat(1000)},
+])('progress command preserves the selected target and exact bounded reason %#', ({target, reason}) => {
+ const raw = {action: 'task.transition', occurrenceId: 'work-1',
+ payload: {expected_revision: revision, target, reason}};
+ const value = taskCommand(raw);
+ expect(value).toEqual(raw);
+ expect(value).not.toBe(raw);
+ expect(Object.isFrozen(value)).toBe(true);
+ expect(Object.isFrozen(value?.payload)).toBe(true);
+});
+
+test.each([
+ {target: 'completed', reason: ''},
+ {target: 'draft', reason: ''},
+ {target: 'cancelled', reason: 'Cancel'},
+ {target: 'skipped', reason: 'Skip'},
+ {target: 'future', reason: ''},
+ {target: 'in_progress', reason: 'Unexpected reason'},
+ {target: 'assigned', reason: 'Unexpected reason'},
+ {target: 'available', reason: 'Unexpected reason'},
+ {target: 'blocked', reason: ''},
+ {target: 'blocked', reason: ' \n\t\u0085'},
+ {target: 'blocked', reason: '\u0000Invalid'},
+ {target: 'blocked', reason: '\ud800'},
+ {target: 'blocked', reason: '🧰'.repeat(1001)},
+])('invalid progress input cannot become a command %#', payload => {
+ expect(taskCommand({action: 'task.transition', occurrenceId: 'work-1',
+ payload: {expected_revision: revision, ...payload}})).toBeUndefined();
+});
+
+test('progress rejects altered scope, unknown fields, omitted reason and invalid revision', () => {
+ const raw = {action: 'task.transition', occurrenceId: 'work-1',
+ payload: {expected_revision: revision, target: 'blocked', reason: 'Waiting'}};
+ for (const value of [
+ {...raw, actor: 'other'},
+ {...raw, occurrenceId: '../work'},
+ {...raw, payload: {...raw.payload, actor_id: 'other'}},
+ {...raw, payload: {expected_revision: revision, target: 'blocked'}},
+ {...raw, payload: {...raw.payload, expected_revision: 1}},
+ {...raw, payload: {...raw.payload, expected_revision: '01'}},
+ ]) expect(taskCommand(value)).toBeUndefined();
+});
+
test.each([[], ['member-1'], Array.from({length: 32}, (_, index) => 'member-' + index)].map(assignee_ids => ({assignee_ids})))(
'assignment preserves and freezes the exact bounded selection %#', ({assignee_ids}) => {
const raw = {action: 'task.assign', occurrenceId: 'work-1', payload: {expected_revision: revision, assignee_ids}};
diff --git a/specs/CATALOG.md b/specs/CATALOG.md
index 73609161..8e51b561 100644
--- a/specs/CATALOG.md
+++ b/specs/CATALOG.md
@@ -12,7 +12,7 @@ debt or convert unknown historic intent into a design decision.
|---|---|---|---|---|
| `platform-foundation` | Proposed | One local modular application serves the complete household product in both a Supervisor-managed App and standalone Docker from the first release. Home Assistant owns user authentication; Domus owns its business records. | [Local application platform and persistence](./platform-foundation.md) + 2 companion | 189 paths · 2026-11-01 |
| `household-identity` | Proposed | Each participating person uses their own Home Assistant account. Domus associates that verified user with one household member and applies explicit backend permissions independently of an optional person entity. | [Household members, Home Assistant identity and permissions](./household-identity.md) + 4 companion | 222 paths · 2026-11-02 |
-| `household-tasks` | Proposed | Members create and perform household responsibilities with explicit assignments, actual performers and history. A recurring definition survives completion of each individual occurrence. | [Task definitions, occurrences and household execution](./household-tasks.md) + 3 companion | 62 paths · 2026-11-19 |
+| `household-tasks` | Proposed | Members create and perform household responsibilities with explicit assignments, actual performers and history. A recurring definition survives completion of each individual occurrence. | [Task definitions, occurrences and household execution](./household-tasks.md) + 4 companion | 62 paths · 2026-11-19 |
| `recurrence-calendar` | Proposed | A bounded scheduler turns task definitions into stable occurrences and a family calendar distinguishes planned start, deadline and actual completion. Original recurrence outcomes bind receipt status, action, result and source-cycle identity before replay and snapshot acceptance. | [Recurrence engine and family calendar](./recurrence-calendar.md) + 3 companion | 37 paths · 2026-11-09 |
| `points-rewards` | Proposed | Task completion produces auditable point entries. Household-configurable collaboration policies determine each share and the actual award total; corrections preserve history and optional rewards never control basic participation. | [Auditable points, participation and optional rewards](./points-rewards.md) | 54 paths · 2026-11-11 |
| `shopping-management` | Proposed | Shopping combines manual intent, replenishment and task materials without losing provenance. Buying an item and physically receiving it are separate recorded facts. | [Shared shopping demand, purchases and receipt](./shopping-management.md) | 47 paths · 2026-11-17 |
@@ -50,7 +50,7 @@ debt or convert unknown historic intent into a design decision.
- Owner: Domus maintainers (review assignment pending)
- Last verified: 2026-11-19
-- Specifications: [`specs/household-tasks.md`](./household-tasks.md) · [`specs/task-execution-foundation.md`](./task-execution-foundation.md) · [`specs/household-task-categories.md`](./household-task-categories.md) · [`specs/task-assignment-interface.md`](./task-assignment-interface.md)
+- Specifications: [`specs/household-tasks.md`](./household-tasks.md) · [`specs/task-execution-foundation.md`](./task-execution-foundation.md) · [`specs/household-task-categories.md`](./household-task-categories.md) · [`specs/task-assignment-interface.md`](./task-assignment-interface.md) · [`specs/task-progress-interface.md`](./task-progress-interface.md)
- Workflows: [`.github/workflows/ci_check.yml`](../.github/workflows/ci_check.yml)
- Entrypoints: [`backend/src/domus/entrypoints/task_http.py`](../backend/src/domus/entrypoints/task_http.py) · [`backend/src/domus/entrypoints/schedule_creation_http.py`](../backend/src/domus/entrypoints/schedule_creation_http.py)
- Core code: [`backend/src/domus/domain/task_values.py`](../backend/src/domus/domain/task_values.py) · [`backend/src/domus/domain/task_policy.py`](../backend/src/domus/domain/task_policy.py) · [`backend/src/domus/domain/tasks.py`](../backend/src/domus/domain/tasks.py) · [`backend/src/domus/application/task_ports.py`](../backend/src/domus/application/task_ports.py) · [`backend/src/domus/infrastructure/sqlite_task_records.py`](../backend/src/domus/infrastructure/sqlite_task_records.py) · [`backend/src/domus/infrastructure/sqlite_task_schema.py`](../backend/src/domus/infrastructure/sqlite_task_schema.py) · [`backend/src/domus/infrastructure/sqlite_tasks.py`](../backend/src/domus/infrastructure/sqlite_tasks.py) · [`backend/src/domus/infrastructure/sqlite_task_integrity.py`](../backend/src/domus/infrastructure/sqlite_task_integrity.py) · [`backend/src/domus/application/task_authorization.py`](../backend/src/domus/application/task_authorization.py) · [`backend/src/domus/application/task_commands.py`](../backend/src/domus/application/task_commands.py) · [`backend/src/domus/application/task_creation.py`](../backend/src/domus/application/task_creation.py) · [`backend/src/domus/application/task_requests.py`](../backend/src/domus/application/task_requests.py) · [`backend/src/domus/application/task_queries.py`](../backend/src/domus/application/task_queries.py) · [`frontend/src/application/task-overview.ts`](../frontend/src/application/task-overview.ts) · [`frontend/src/adapters/task-http.ts`](../frontend/src/adapters/task-http.ts) · [`frontend/src/domain/tasks.ts`](../frontend/src/domain/tasks.ts) · [`frontend/src/application/task-controller.ts`](../frontend/src/application/task-controller.ts) · [`frontend/src/presentation/domus-tasks.ts`](../frontend/src/presentation/domus-tasks.ts) · [`frontend/src/presentation/domus-task-overview.ts`](../frontend/src/presentation/domus-task-overview.ts) · [`frontend/src/adapters/task-values.ts`](../frontend/src/adapters/task-values.ts) · [`frontend/src/adapters/task-journal.ts`](../frontend/src/adapters/task-journal.ts)
diff --git a/specs/catalog.json b/specs/catalog.json
index d74615d1..0287c3f5 100644
--- a/specs/catalog.json
+++ b/specs/catalog.json
@@ -482,7 +482,8 @@
"specs/household-tasks.md",
"specs/task-execution-foundation.md",
"specs/household-task-categories.md",
- "specs/task-assignment-interface.md"
+ "specs/task-assignment-interface.md",
+ "specs/task-progress-interface.md"
],
"workflows": [
".github/workflows/ci_check.yml"
diff --git a/specs/task-progress-interface.md b/specs/task-progress-interface.md
new file mode 100644
index 00000000..51dc0b76
--- /dev/null
+++ b/specs/task-progress-interface.md
@@ -0,0 +1,286 @@
+# Start, block and unblock tasks from Tasks
+
+- Status: Draft
+- Catalog capability: household-tasks
+
+## 1. Executive summary
+
+Add Start, Block, and Unblock actions to the existing Tasks workspace so members can make eligible work visible as in progress, record why work is blocked, and deliberately resume blocked work. Show the saved blocking reason beside a blocked task. Preserve the selected task’s assignees and use current server-provided transition hints, current command authority, and the exact reviewed revision for every change. The retained contracts and cases in `specs/household-tasks.md`, `specs/task-execution-foundation.md`, `specs/household-task-categories.md`, and `specs/task-assignment-interface.md` remain authoritative; this companion specifies the progress interface delta.
+
+```text
+Open task -> review current actions -> choose Start, Block, or Unblock -> review any conflict -> deliberately save -> see current task state and, when blocked, its saved reason
+```
+
+## 2. Problem, current behavior, and evidence
+
+### 2.1 Problem
+
+Members can manage tasks in the existing Tasks workspace, but cannot use it to start assigned work, explain a blocker, or resume blocked work. The interface also needs to preserve the reason and proposed change through validation errors, concurrent updates, and interrupted responses so members can tell what was saved and what still needs action.
+
+### 2.2 Current behavior
+
+The selected source includes the task workspace and presentation, controller, HTTP adapter, and journal boundaries documented by the existing task contracts. The issue describes task transitions and current action hints as existing backend capabilities, while this interface delta is prospective. The selected source evidence cited here does not independently establish every backend transition behavior; the retained execution contract remains the authority for lifecycle and command semantics.
+
+The selected tree contains `frontend/src/presentation/domus-task-overview.ts` and `frontend/src/presentation/domus-automation-execution.ts` as presentation references. The issue identifies `@vypdev/ha-ui` version `0.1.0-next.2` as the intended released component package, pinned through `frontend/package.json` and `pnpm-lock.yaml`; its use for this delta is a proposed implementation constraint, not evidence of completed integration.
+
+### 2.3 Evidence
+
+The retained task lifecycle, authorization, revision, receipt, and history contracts are in `specs/household-tasks.md` and `specs/task-execution-foundation.md`; the existing Tasks assignment journey is in `specs/task-assignment-interface.md`. The catalog registers task presentation evidence including `frontend/src/presentation/domus-task-overview.ts`. `specs/README.md` defines the specification and catalog publication goals. No implementation, acceptance run, or publication outcome for this proposed delta is asserted here.
+
+## 3. Actors, surfaces, and terminology
+
+Household members use the existing Tasks workspace to act on a selected task occurrence. The selected task’s current detail and action hints determine which progress actions are offered. The existing task command remains responsible for enforcing lifecycle policy, household scope, revision, and authority; the interface is not an authorization boundary.
+
+“Start” moves assigned work to In progress. “Block” moves eligible Available, Assigned, or In progress work to Blocked and requires a reason. “Unblock” moves blocked work to Assigned when its current assignee set is nonempty, or to Available when it is empty. “Current hint” means the action advertised for the selected task after refreshing its current details; a stale hint alone never authorizes a change. “Blocking reason” is the exact submitted text saved as the task’s current `state_reason` while blocked. “Selected occurrence identity” and “revision” identify the task and version the member reviewed before acting.
+
+## 4. Goals, non-goals, and fixed invariants
+
+### 4.1 Goals
+
+Let a member start an assigned task only when the current `transition:in_progress` hint is present. Let a member block an Available, Assigned, or In progress task only when the current `transition:blocked` hint is present. Let a member unblock a blocked task to Assigned when current assignees exist, or to Available when none exist, and require the matching current target hint. Preserve assignee identities. Enforce current `tasks.complete` authority for In progress, Blocked, and Assigned targets, and `tasks.manage` authority for Available.
+
+For blocking, require meaningful valid multiline text within the existing 1000 Unicode code point limit, validated with `validate_task_text(multiline=True, required=True)`. Preserve the exact valid submission and a correctable draft across validation errors and recoverable failures. Reject blank reasons, invalid Unicode, disallowed controls, and over-limit text. Show the saved reason as text to permitted readers while the task is blocked, with accessible labels, instructions, and errors. Start and Unblock use the existing empty reason string; the historical blocking reason remains in its receipt and history.
+
+Before admitting an action, capture the selected occurrence identity, target, reason, and revision, then refresh current session, scope, task detail, and action hints through the existing controller path. A changed revision or competing post-admission conflict must retain the proposed target and reason and show current facts. Require explicit review and a separate deliberate save at the reviewed revision while the target remains permitted. If the target is unavailable, offer refresh or cancel and require a deliberate new choice. Follow existing protected-view retirement behavior when authority is revoked. Direct writes must transactionally recheck current command authority and exact revision.
+
+### 4.2 Non-goals
+
+This delta does not redefine task lifecycle, transition policy, authorization, receipts, history, or journal semantics, and does not replace the retained task owners. It does not introduce new task states, broaden available actions, or let the client’s visible controls grant authority.
+
+### 4.3 Fixed product/safety invariants
+
+Current server state and command checks govern every mutation; hints are not authority. A rejected or conflicted action must not silently change the task or discard the member’s proposed target or reason. Any interrupted request remains bound to its original key, action, body, and scope; recovery must use the existing recorded-authorization boundary, produce at most one transition/history/receipt, and reject a changed payload under the same key. Keep current task facts distinct from any recovered historical result, including after restore. Preserve the existing prepared/uncertain request gate and compatibility with prior creation and assignment journal entries.
+
+Publication completion requires that the specification satisfy the required format, that internal and cross-document consistency is checked, and that reciprocal catalog ownership, paths, and evidence agree with the generated view. These are publication constraints, not product goals or claims that checks have run.
+
+| Requirement | Behavior |
+|---|---|
+| task-progress-interface-R01 | Offer Start for the permitted assigned-to-in-progress transition. Offer Block for permitted available, assigned and in-progress work. Offer Unblock for blocked work, targeting assigned when assignees remain and available when empty, subject to the server's current allowed action. Display the saved reason. |
+| task-progress-interface-R02 | Enforce the existing state machine, human authority, household scope, exact selected revision and unchanged assignee identities. Current authority governs direct writes and original receipt disclosure. |
+| task-progress-interface-R03 | Require a meaningful valid blocking reason within the existing 1,000-code-point multiline bound. Preserve a correctable reason and show distinct invalid, denied, unavailable and conflict outcomes. |
+| task-progress-interface-R04 | Retain the captured task, target, reason and revision across a competing update. Show the current task and require explicit review before a fresh deliberate save. A newly unavailable target has an actionable cancellation or refresh path. |
+| task-progress-interface-R05 | Freeze the original command body, key and scope before sending. A lost response recovers the same operation after reload or restart and an exact replay adds no transition, history, points or stock effect. |
+| task-progress-interface-R06 | Provide English and Spanish keyboard and touch flows with clear labels, focus, cancellation, busy states, light/dark legibility and protected recovery. |
+
+## 5. Current versus proposed product journey
+
+The retained task lifecycle, transition policy, assignment, authorization, revision, receipt, and history contracts remain in `specs/household-tasks.md` and `specs/task-execution-foundation.md`. This companion adds controls to the existing Tasks experience: members can start assigned work, block eligible work with a reason, and deliberately unblock it according to the task’s current assignee set.
+
+| Stage | Current Tasks experience | Proposed Tasks experience | User effect |
+|---|---|---|---|
+| Find and select | The task overview groups work and emits a selection intent for an occurrence. | Keep that entry point; show permitted progress actions with the selected task’s current state and action hints. | The member can see which actions are currently offered for this occurrence. |
+| Start or block | The interface does not offer these transitions from Tasks. | Start assigned work, or block available, assigned, or in-progress work. Blocking requires a meaningful multiline explanation. | Work status and the reason it cannot proceed are visible to permitted readers. |
+| Unblock | The interface does not offer this transition from Tasks. | Explicitly choose the currently permitted target: assigned when assignees remain, otherwise available. | The member understands whether responsibility remains with the existing assignees or work becomes available. |
+| Resolve changes and observe | The retained command contract governs revision conflicts and original-request receipts. | Refresh facts before admission; on conflict preserve the proposed action and reason for review, and recover uncertain requests using their frozen original request. | A stale action cannot silently apply, and a retry cannot create a second transition. |
+
+Flow: select occurrence -> refresh session, scope, detail, and hints -> choose an offered action -> review and deliberately save -> see the current result or review/recover. A changed revision or competing conflict requires reviewing current facts and a separate deliberate save. An unavailable target requires refresh or cancel and a new deliberate choice. Revoked authority follows the existing protected-view retirement behavior.
+
+## 6. Functional behavior and state model
+
+### Normal transitions
+
+- Start is available only for an assigned task with the current `transition:in_progress` hint. It moves the task to `in_progress` and preserves assignee identities.
+- Block is available only for an available, assigned, or in-progress task with the current `transition:blocked` hint. It moves the task to `blocked`, preserves assignee identities, and saves the exact validated reason as the current `state_reason`.
+- Unblock is available only for a blocked task and the matching current hint. With a nonempty current assignee set, `transition:assigned` returns it to `assigned`; with an empty set, `transition:available` returns it to `available`. Preserve assignee identities.
+- Start, block, and unblock use the retained transition command and state policy. Start and unblock submit the existing empty reason, clearing the current reason through the accepted transition. Historical reasons remain in their original receipt and history.
+- Current authorization is target-specific: `tasks.complete` is required for `in_progress`, `blocked`, and `assigned` targets; `tasks.manage` is required for `available`. A visible control or stale hint grants no authority.
+
+### Blocking reason and feedback
+
+Require meaningful multiline text validated with `validate_task_text(multiline=True, required=True)` and the existing 1000 Unicode code point maximum. Reject blank required reasons, invalid Unicode, disallowed controls, and over-limit input. Preserve valid submitted text exactly. Preserve the correctable draft after validation errors and recoverable failures. Render the saved current reason as text beside the blocked state for permitted readers, with associated accessible labels, instructions, and errors.
+
+Show clear loading, unavailable, denied, invalid, conflict, uncertain, and confirmed states. On conflict, show current task facts without discarding the proposed target or reason; require explicit review and then a separate deliberate save at the reviewed revision while the target remains permitted. If the target is no longer available, offer refresh or cancel and require a new action choice. Do not imply an unconfirmed transition succeeded.
+
+The task overview in `frontend/src/presentation/domus-task-overview.ts` already groups tasks and emits occurrence selection intents. The existing bilingual presentation in `frontend/src/presentation/domus-automation-execution.ts` demonstrates released button, card, and feedback components and localized status/action rendering; use the declared `@vypdev/ha-ui` package version in `frontend/package.json` and lockfile. Keep keyboard focus, readable labels, and narrow touch layouts usable in English and Spanish.
+
+## 7. User-facing configuration
+
+This interface increment adds no user-configurable settings. Keep the blocking reason’s existing fixed 1000 Unicode code point limit and validator behavior; it is a correctness and safety constraint, not a preference. Keep action eligibility, target selection, and authorization derived from current task facts and server-provided hints. Do not let users configure transition rules, permissions, revision checks, or request-recovery behavior.
+
+## 8. Clean Architecture design
+
+### Responsibilities and dependency direction
+
+| Boundary | Responsibility for this delta | Must not own |
+|---|---|---|
+| Domain | Retained `TaskOccurrence` transition policy and `next_occurrence_state` rules determine valid state changes and reason semantics. | UI visibility, provider or DOM concerns. |
+| Application | Reuse the existing task transition command, current authorization, exact revision check, receipt, history, and transaction boundary. | Duplicated presentation policy or provider DTOs. |
+| Adapters and infrastructure | Preserve existing persistence, composition, and original-request recovery boundaries; map outcomes to semantic results. | Client-selected authority or relaxed revision checks. |
+| Entrypoint/controller | Refresh current session, scope, task detail, and action hints before admitting an action; bind the request to the selected occurrence and frozen original request. | Treating a cached hint as authorization or rebuilding a changed request for replay. |
+| Presentation | Render current state, permitted actions, reason editor, review/conflict, uncertainty, and result; emit user intents. | Performing mutations or deciding authorization. |
+
+The existing architecture contract in `specs/task-execution-foundation.md` keeps pure task policy in Domain, orchestration and semantic ports in Application, provider/storage details outside those layers, and presentation limited to view models and rendering. Preserve those dependency directions in both supported compositions.
+
+### Request, concurrency, and trust boundaries
+
+Capture the selected occurrence identity, target, reason, and revision. Before admission, use the existing controller path to refresh session, scope, detail, and action hints. Direct writes must transactionally recheck current command authority and exact revision. A stale revision or competing post-admission conflict retains the proposal and displays current facts; only explicit review followed by a separate deliberate save may proceed at the reviewed revision while the target remains permitted.
+
+Prepare the task journal with its original key, canonical body, selected revision, and verified installation, channel, actor, and household scope before explicit send. For an interrupted or unbound response, keep the outcome uncertain and check the existing original-request endpoint with the same frozen key, action, and body binding. Extend its typed workspace allowlist for `task.transition` through `recorded_authorization`; repeated protected reads return the same recorded operation. Exact replay creates one transition, history entry, and receipt; a changed payload under that key conflicts. Show current task facts separately from a recovered historical result, including after activated restore. Preserve the prepared/uncertain request gate and journal compatibility with prior creation and assignment entries. Only an explicit deliberate save initiates a new transition.
+
+If authority is revoked, follow existing protected-view retirement behavior. Treat task input and returned facts as untrusted at presentation boundaries; render reasons as text and preserve household scoping. Keep schema 34 if implementation confirms existing persisted formats cover this change; migration needs remain subject to implementation evidence.
+
+### Verification constraints
+
+Preserve the existing CI acceptance gates, configured self-hosted runner placement, and full released action versions. The selected source declares the frontend package manager and scripts in `frontend/package.json`; declaration alone does not establish execution or specification coverage. Follow the existing task browser journeys and applicable container jobs, with acceptance covering Ingress and standalone, both CPU images, English keyboard and Spanish narrow touch journeys, and an immutable installed Edge candidate. The precise invocation and prerequisites for SDD format, consistency, catalog, and product validation remain unverified here; require those observable outcomes without treating a different documentation check as SDK consistency verification. Do not infer passing acceptance from command declarations.
+
+## 9. UI/UX and content contract
+
+### UI/UX and content contract
+
+Add start, block, and unblock actions to the existing Tasks detail experience. Render only actions permitted by the current task detail and transition hints. Show the current task state and assignees, then the available action and any required reason. While blocked, show the saved current `state_reason` as readable text to permitted task readers. Start and unblock submit the existing empty reason value; a successful transition clears the current reason while its historical value remains in the existing receipt and history.
+
+Blocking uses a labeled multiline reason editor. Explain that a reason is required and limited to 1000 Unicode code points. Preserve a valid entered draft if validation or a recoverable request failure prevents saving. Associate instructions and validation errors with the editor, expose errors in text, and do not rely on color alone. The existing task interface owns the shell and interaction boundaries in `specs/task-assignment-interface.md`; the selected presentation examples in `frontend/src/presentation/domus-task-overview.ts` and `frontend/src/presentation/domus-automation-execution.ts` demonstrate the project's task overview and button, card, feedback, focus, and bilingual presentation patterns.
+
+Use one clear primary action at a time. Confirmation must identify the task, proposed state, reason when present, and revision being saved. Conflict review presents current facts and the retained proposal; the user reviews those facts and then makes a separate deliberate save. If the target is no longer available, offer refresh or cancel and require a new deliberate choice. Present pending, unavailable, denied, rejected, conflict, uncertain, recovered historical result, and completed states in plain language, separating current task facts from historical operation results. Keep diagnostics secondary and omit protected details after access is revoked.
+
+Use the existing English and Spanish locale behavior and provide keyboard operation, visible focus, programmatic labels, and readable narrow-screen layouts. Controls and feedback should follow the released `@vypdev/ha-ui` contracts already used by the selected presentation components; retain the existing task shell and multiline reason semantics.
+
+## 10. Failure, recovery, and cleanup
+
+### Failure, recovery, and cleanup
+
+A validation failure leaves the task unchanged and preserves the editable reason for correction. A rejected or unavailable request must state its impact, cause, next action, and retained draft. Do not report a transition as failed after a committed result has been recovered.
+
+Before admission, refresh the current session, household scope, task detail, and action hints through the existing controller path. A stale hint alone never admits a command. On revision change or a competing post-admission conflict, retain the proposed target and exact reason, display current task facts, and require explicit review followed by a separate save against the reviewed revision if the target remains permitted. If the target becomes unavailable, offer refresh or cancel; do not select a replacement automatically. If authority is revoked, use the existing protected-view retirement behavior.
+
+Prepare the task journal with the original request key, canonical body, selected revision, and verified installation, channel, actor, and household scope before sending. Treat interrupted or unbound responses as uncertain. On reload or restart, recover through the existing original-request endpoint with the same frozen key, action, body, and authorization binding; extend its typed workspace allowlist for the existing `task.transition` action through recorded authorization. Repeated protected original reads return the same recorded operation. Exact replay produces one transition, history entry, and receipt; a changed payload under that key conflicts. Show current task facts separately from a recovered historical result, including after activated restore. Only an explicit deliberate save starts a new transition. Preserve the prepared/uncertain request gate and compatibility with earlier creation and assignment journal entries.
+
+## 11. Security, permissions, and privacy
+
+### Security, permissions, and privacy
+
+Transition hints describe current permitted actions but do not grant authority. The server remains authoritative: it rechecks current command authority and exact revision transactionally for direct writes. Preserve assignee identities. Require `tasks.complete` for in-progress, blocked, and assigned targets, and `tasks.manage` for the available target. Unblock chooses assigned only when the current assignee set is nonempty; otherwise it chooses available and requires the corresponding current transition hint.
+
+Treat reason text and all client-supplied task, revision, target, and journal data as untrusted. Validate blocking text with the existing `validate_task_text(multiline=True, required=True)` semantics: require meaningful valid multiline text within 1000 Unicode code points and reject blank required reasons, invalid Unicode, and disallowed controls. Preserve valid submitted text exactly. Render saved and proposed reasons as text, not executable markup. A journal record or cached hint is recovery context, never authorization. Original-operation reads retain transaction-time grants and the recorded authorization boundary. On revocation, retire the protected view and do not disclose task or member details no longer authorized.
+
+## 12. Observability and operational UX
+
+### Observability and operational UX
+
+Show users the current task state, the action outcome, and whether review, refresh, correction, or recovery is required. Keep operation identity and revision available in the existing authorized receipt/history experience; distinguish the current task from a historical recovered result. Do not expose reason text or task details to unauthorized readers. Operational diagnostics should identify the operation and sanitized failure category without copying protected request content into logs or user-facing diagnostics.
+
+Acceptance evidence must exercise start, block, both unblock destinations, validation and draft retention, changed-revision and competing-conflict review, unavailable targets, authority retirement, exact replay, changed-payload conflict, and transactional rejection of stale revision or revoked authority. Validate English keyboard and Spanish narrow-touch journeys, plus supported ingress and standalone coverage, both CPU images, and an immutable installed Edge candidate. Follow the existing CI acceptance gates and preserve configured self-hosted runner placement and full released action versions. The selected tree includes `frontend/tests/e2e/tasks.spec.ts` and `.github/workflows/ci_check.yml`; their complete applicability to this new increment and the concrete installed Edge invocation remain to be verified during implementation.
+
+## 13. Compatibility, migration, rollout, and rollback
+
+### Compatibility, migration, rollout, and rollback
+
+Keep the existing task states, transition policy, receipts, history, authorization, and journal recovery semantics as the owning contract in `specs/household-tasks.md`, `specs/task-execution-foundation.md`, and `specs/task-assignment-interface.md`. This companion defines only the Tasks interface delta. Preserve schema 34 if implementation evidence confirms existing persisted formats cover the change; otherwise document the required migration and restart/restore behavior before readiness. Journal changes must continue to read prior creation and assignment entries and must not reinterpret an uncertain original request as permission to issue a new command.
+
+Qualify the increment on supported ingress and standalone surfaces, English keyboard and Spanish narrow touch journeys, both CPU images, and an immutable installed Edge candidate. Follow existing installation and operations guidance in `docs/installation-home-assistant.md` and `docs/operations.md`; keep rollback compatible with the existing paired application and database restore approach. The concrete migration need, rollout procedure, rollback evidence, and invocation/prerequisites for installed acceptance remain unverified in the selected source and must be resolved as implementation outcomes.
+
+## 14. Testing strategy and numeric budget
+
+Nine distinct cases cover progress, authority, reason validation, concurrent
+review, original recovery, rollback, browser use and persistence. Each supplied
+case retains its exact identity and observable assertions. Repeated executions
+add evidence for the same cases. The retained task owner cases remain in force.
+
+| Area | Minimum distinct cases | Behaviors/risks covered |
+|---|---:|---|
+| Progress journey | 1 | Observable scenarios in the case inventory. |
+| Available work | 1 | Observable scenarios in the case inventory. |
+| Authority and scope | 1 | Observable scenarios in the case inventory. |
+| Reason validation | 1 | Observable scenarios in the case inventory. |
+| State and concurrency | 1 | Observable scenarios in the case inventory. |
+| Original recovery | 1 | Observable scenarios in the case inventory. |
+| Failure and rollback | 1 | Observable scenarios in the case inventory. |
+| Browser acceptance | 1 | Observable scenarios in the case inventory. |
+| Persistence and integrated acceptance | 1 | Observable scenarios in the case inventory. |
+| Total | 9 | Distinct inventory cases; repeated executions do not add cases. |
+
+| Case ID | Area | Requirements | Scenario |
+|---|---|---|---|
+| task-progress-interface-C01 | Progress journey | task-progress-interface-R01, task-progress-interface-R02 | Start assigned work, block it with a saved reason and unblock it to assigned. Retain the same task and assignees while revisions advance once per accepted change. Show the current saved reason. |
+| task-progress-interface-C02 | Available work | task-progress-interface-R01, task-progress-interface-R02 | Block and unblock an unassigned task through its current permitted actions and return to available with an empty assignee set. Exercise an actor whose permissions expose only the valid existing targets. |
+| task-progress-interface-C03 | Authority and scope | task-progress-interface-R02 | Respect current task actions, role/member grants and revocation. Reject a foreign task and a newly denied direct write. Revoke the original transition authority and deny receipt disclosure in both compositions. |
+| task-progress-interface-C04 | Reason validation | task-progress-interface-R03 | Preserve exact multiline text and accept the existing bound. Reject blank required reasons, forbidden characters and over-bound Unicode text before a browser write and at the normal API boundary. Keep the correctable draft. |
+| task-progress-interface-C05 | State and concurrency | task-progress-interface-R02, task-progress-interface-R04 | Compete at one selected revision in two sessions. Retain the losing reason and target, display current facts and require explicit review before another save. A target that becomes unavailable requires a deliberate new decision. |
+| task-progress-interface-C06 | Original recovery | task-progress-interface-R05 | Commit a transition then lose its response. Reload, recover the frozen original operation and verify exact replay adds no history or effects. Reject key reuse with a different target or reason and retain earlier journal records. |
+| task-progress-interface-C07 | Failure and rollback | task-progress-interface-R02, task-progress-interface-R03, task-progress-interface-R05 | Inject a late transactional failure and observe unchanged task and absent receipt. Exercise unavailable reads, unknown responses and denied current authority with truthful feedback and retained recoverable input. |
+| task-progress-interface-C08 | Browser acceptance | task-progress-interface-R01, task-progress-interface-R04, task-progress-interface-R06 | Use English keyboard and Spanish 390 px touch through Ingress and standalone. Exercise start, reason validation, cancellation, block, conflict review and unblock, with focus and light/dark legibility. |
+| task-progress-interface-C09 | Persistence and integrated acceptance | task-progress-interface-R01, task-progress-interface-R02, task-progress-interface-R05, task-progress-interface-R06 | Restart and activate a compatible restore containing blocked work and its original receipt. Inspect retained reason and audit, then complete through the existing performer flow. Qualify both CPU images and the exact installed Edge candidate with scoped QA cleanup. |
+
+## 15. Documentation and discoverability
+
+Document the Tasks journey for starting assigned work, explaining a block, and deliberately resuming blocked work. Explain the visible state and saved blocking reason, current action availability, conflict review, correction of a reason draft, and what happens when authority or a target changes. Provide accessible, localized English keyboard and Spanish narrow-touch guidance. Keep state, transition, and authorization rules in the retained owners, including `specs/household-tasks.md` and `specs/task-execution-foundation.md`; this companion describes only the interface and recovery delta. The selected project pins `@vypdev/ha-ui` at `0.1.0-next.2` in `frontend/package.json` and `pnpm-lock.yaml`. Existing presentation examples are `frontend/src/presentation/domus-automation-execution.ts` and `frontend/src/presentation/domus-task-overview.ts`. Use the released button, feedback, and card contracts for progress controls and the existing multiline reason control and text validation semantics. Render the saved reason as text for permitted readers while blocked. The companion specification at `specs/task-progress-interface.md` is a proposed create, not an existing file.
+
+| Path | Change |
+| --- | --- |
+| frontend/package.json | reference |
+| pnpm-lock.yaml | reference |
+| frontend/src/presentation/domus-automation-execution.ts | reference |
+| frontend/src/presentation/domus-task-overview.ts | reference |
+| specs/task-progress-interface.md | create |
+
+[frontend/package.json](../frontend/package.json) · [pnpm-lock.yaml](../pnpm-lock.yaml) · [frontend/src/presentation/domus-automation-execution.ts](../frontend/src/presentation/domus-automation-execution.ts) · [frontend/src/presentation/domus-task-overview.ts](../frontend/src/presentation/domus-task-overview.ts) · [specs/task-progress-interface.md](task-progress-interface.md)
+
+## 16. Acceptance scenarios
+
+1. Start assigned work, block it with a saved reason and unblock it to assigned. Retain the same task and assignees while revisions advance once per accepted change. Show the current saved reason. (task-progress-interface-C01)
+
+2. Block and unblock an unassigned task through its current permitted actions and return to available with an empty assignee set. Exercise an actor whose permissions expose only the valid existing targets. (task-progress-interface-C02)
+
+3. Respect current task actions, role/member grants and revocation. Reject a foreign task and a newly denied direct write. Revoke the original transition authority and deny receipt disclosure in both compositions. (task-progress-interface-C03)
+
+4. Preserve exact multiline text and accept the existing bound. Reject blank required reasons, forbidden characters and over-bound Unicode text before a browser write and at the normal API boundary. Keep the correctable draft. (task-progress-interface-C04)
+
+5. Compete at one selected revision in two sessions. Retain the losing reason and target, display current facts and require explicit review before another save. A target that becomes unavailable requires a deliberate new decision. (task-progress-interface-C05)
+
+6. Commit a transition then lose its response. Reload, recover the frozen original operation and verify exact replay adds no history or effects. Reject key reuse with a different target or reason and retain earlier journal records. (task-progress-interface-C06)
+
+7. Inject a late transactional failure and observe unchanged task and absent receipt. Exercise unavailable reads, unknown responses and denied current authority with truthful feedback and retained recoverable input. (task-progress-interface-C07)
+
+8. Use English keyboard and Spanish 390 px touch through Ingress and standalone. Exercise start, reason validation, cancellation, block, conflict review and unblock, with focus and light/dark legibility. (task-progress-interface-C08)
+
+9. Restart and activate a compatible restore containing blocked work and its original receipt. Inspect retained reason and audit, then complete through the existing performer flow. Qualify both CPU images and the exact installed Edge candidate with scoped QA cleanup. (task-progress-interface-C09)
+
+## 17. Requirements traceability
+
+Each requirement maps reciprocally to the supplied cases that exercise it.
+The nine case identities and their scenario definitions come from issue #143.
+Earlier owning case identities retain their definitions and existing evidence.
+
+| Requirement | Cases |
+|---|---|
+| task-progress-interface-R01 | task-progress-interface-C01, task-progress-interface-C02, task-progress-interface-C08, task-progress-interface-C09 |
+| task-progress-interface-R02 | task-progress-interface-C01, task-progress-interface-C02, task-progress-interface-C03, task-progress-interface-C05, task-progress-interface-C07, task-progress-interface-C09 |
+| task-progress-interface-R03 | task-progress-interface-C04, task-progress-interface-C07 |
+| task-progress-interface-R04 | task-progress-interface-C05, task-progress-interface-C08 |
+| task-progress-interface-R05 | task-progress-interface-C06, task-progress-interface-C07, task-progress-interface-C09 |
+| task-progress-interface-R06 | task-progress-interface-C08, task-progress-interface-C09 |
+
+Publication requires the specification format, internal and cross-document
+consistency, and reciprocal catalog ownership, paths and generated evidence.
+Executed product acceptance is recorded with its actual scope.
+
+## 18. Implementation sequence
+
+1. Publish this companion through the existing managed Action on the exact reviewed parent and verify the resulting branch before implementation; the retained execution contract requires publication and exact-branch validation first (`specs/task-execution-foundation.md`).
+2. Implement the Tasks presentation using the existing domain, application, and adapter boundaries and the pinned `@vypdev/ha-ui` 0.1.0-next.2 contracts. Preserve existing task-shell behavior and use the bounded multiline reason control; consult the package declaration and lockfile in `frontend/package.json` and `pnpm-lock.yaml`. Existing presentation adoption references are `frontend/src/presentation/domus-automation-execution.ts` and `frontend/src/presentation/domus-task-overview.ts`.
+3. Add current action-hint admission, refresh and revision review, reason draft retention, protected-view retirement, and transactional authority/revision checks. Keep task transition, authorization, receipt, history, and original-request recovery semantics owned by the retained contracts in `specs/household-tasks.md`, `specs/task-execution-foundation.md`, and `specs/task-assignment-interface.md`.
+4. Extend the bounded task journal and original-request allowlist for `task.transition` through the recorded authorization boundary. Preserve frozen key/action/body/scope on recovery; exact replay yields one transition, history entry, and receipt, while a changed payload conflicts. Keep the prepared/uncertain request gate and compatibility with existing journal entries.
+5. Deliver the start, block, and both unblock outcomes; multiline blocking reason validation/display; and refreshed admission, conflict review, unavailable-target, revocation, and direct-write behavior. Preserve keyboard access, English and Spanish content, and narrow touch usability. Keep the existing schema when implementation confirms persisted formats already cover the change.
+6. Qualify the complete supported coverage: Ingress and standalone, both CPU images, and an immutable installed Edge candidate. Follow the existing CI acceptance gates, preserve configured self-hosted runner placement and full released action versions, and collect the corresponding UX, image, and installed-artifact evidence. The parent workflow is `.github/workflows/ci_check.yml`; its actual job scope must remain intact.
+
+## 19. Definition of Done
+
+- [ ] Every requirement is covered by an observable case and reciprocal traceability; each declared case exercises only the requirements it actually covers, including transition eligibility and authority, reason validation and retention, refreshed admission, reviewed conflict recovery, target unavailability/revocation, and transactional direct-write checks.
+- [ ] Start, block, and unblock use current matching transition hints, preserve assignee identities, apply the specified target authority, and retain the existing task command and state-policy semantics.
+- [ ] Blocking validates required meaningful multiline text with `validate_task_text(multiline=True, required=True)`, enforces the 1000 Unicode code point limit and existing Unicode/control rules, preserves correctable drafts, and shows the saved reason as text to permitted readers. Start and unblock clear current reason as specified while history retains prior reasons.
+- [ ] Admission refreshes current session, scope, task detail, and action hints through the existing controller path. Stale hints never authorize a change. Conflicts retain proposed target and reason, show current facts, and require explicit review followed by a separate save at the reviewed revision. Unavailable targets require a deliberate new choice; authority revocation follows protected-view retirement; direct writes transactionally recheck current authority and exact revision.
+- [ ] Original-request recovery preserves frozen request binding and scope, admits the existing `task.transition` action through recorded authorization, and proves exact replay, changed-payload conflict, and one-time transition/history/receipt behavior after interruption or restart. Current task facts remain distinguishable from the recovered historical result, including after activated restore.
+- [ ] Existing CI acceptance gates pass with the configured self-hosted runner placement and full released action versions. Acceptance covers the Tasks journeys, applicable container jobs, Ingress and standalone, both CPU images, and an immutable installed Edge candidate. Preserve existing repository coverage thresholds and qualify complete supported coverage without exclusions or denominator reduction.
+- [ ] Accessibility, keyboard use, narrow touch behavior, English and Spanish, and reason-control labels, instructions, and errors are reviewed against implemented journeys.
+- [ ] The specification satisfies the required format; internal and cross-document consistency is checked; reciprocal catalog ownership, paths, and evidence agree with the generated view. These are observable publication outcomes, not generic maintainer acceptance. The installed root and frontend package declarations expose no `validate:specifications` or `generate:specifications` script; the concrete SDD validation invocation and prerequisite therefore remain unverified. A documentation check alone does not establish these outcomes.
+- [ ] No readiness-blocking decision remains unresolved.
+
+## 20. References and decisions
+
+- Issue: https://github.com/vypdev/domus/issues/143
+- Selected source revision: `50ddb2d60de4b4a53970ecdde70eb746ade38d30`.
+- Retained owning contracts: `specs/household-tasks.md`, `specs/task-execution-foundation.md`, `specs/household-task-categories.md`, and `specs/task-assignment-interface.md`. This companion defines only the Tasks progress-interface delta; existing owner contracts and cases remain in force.
+- UI package declaration and lock: `frontend/package.json` and `pnpm-lock.yaml`. Existing presentation references: `frontend/src/presentation/domus-automation-execution.ts` and `frontend/src/presentation/domus-task-overview.ts`.
+- Existing acceptance workflow: `.github/workflows/ci_check.yml`; preserve its current gates, runner placement, and full action versions. The concrete invocation/prerequisite for SDK specification validation was not observed in the selected project declarations.
+- Decisions: use the existing task transition command, current server action hints and authorization, controller refresh path, reason validator, journal, and original-request recovery boundary. Retain schema 34 only if implementation confirms current persisted formats suffice. Publish and verify the managed issue branch from the reviewed parent before contributor implementation.
+- Deferred work: no change to the owning task contracts or unrelated task operations.
diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py
index da7db869..97d30810 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.49"
+ assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.51"
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": []}
@@ -64,15 +64,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] == "0a95702a5f53911cc12c645bf7f6f2e8dcd626cd"
+ assert commits[0] == "4f79b75d65835037a51b51e3742cd372bc45edfe"
assert (
- "DOMUS_SOURCE_SHA256=0fcb5041bdb95712545b0deb6aec3ed2d8f545289cd034537f0d70ae78a71989"
+ "DOMUS_SOURCE_SHA256=b57247ac5e62686f8ff42b1ac71cbcde5e47ea54ff873b543077db0102e865dc"
in source
)
- assert "ARG BUILD_VERSION=0.0.0-edge.49" in source
+ assert "ARG BUILD_VERSION=0.0.0-edge.51" in source
candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text())
assert candidate["sourceCommit"] == commits[0]
- assert candidate["version"] == "0.0.0-edge.49"
+ assert candidate["version"] == "0.0.0-edge.51"
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
@@ -149,8 +149,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.49"
- assert artifact["sourceCommit"] == "0a95702a5f53911cc12c645bf7f6f2e8dcd626cd"
+ assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.51"
+ assert artifact["sourceCommit"] == "4f79b75d65835037a51b51e3742cd372bc45edfe"
assert artifact["storageSchema"] == 34
for field in ["sourceArchiveSHA256", "wheelSHA256"]:
assert re.fullmatch("[a-f0-9]{64}", artifact[field])
diff --git a/tests/backend/test_task_execution_commands.py b/tests/backend/test_task_execution_commands.py
index e443e4d9..80e1eb1b 100644
--- a/tests/backend/test_task_execution_commands.py
+++ b/tests/backend/test_task_execution_commands.py
@@ -3,7 +3,7 @@
from dataclasses import replace
import pytest
-from test_task_commands import child_commands, fixture, resource
+from test_task_commands import child_commands, counts, fixture, resource
from domus.application.task_commands import (
AssignTask,
@@ -247,6 +247,55 @@ def fail(self, value, expected_revision):
assert state(store, occurrence_id) == before
+@pytest.mark.parametrize(
+ "target",
+ [
+ OccurrenceState.IN_PROGRESS,
+ OccurrenceState.BLOCKED,
+ OccurrenceState.ASSIGNED,
+ OccurrenceState.AVAILABLE,
+ ],
+)
+def test_late_progress_write_failure_rolls_back_and_the_original_key_can_retry(
+ tmp_path, monkeypatch, target
+):
+ commands, _, store, occurrence_id, _, _ = prepared(
+ tmp_path, assign=target is not OccurrenceState.AVAILABLE
+ )
+ if target in {OccurrenceState.ASSIGNED, OccurrenceState.AVAILABLE}:
+ work, _ = work_at(store, occurrence_id)
+ commands.transition(
+ "block-first",
+ TransitionTask(occurrence_id, work.revision, OccurrenceState.BLOCKED, "Waiting"),
+ )
+ work, _ = work_at(store, occurrence_id)
+ request = TransitionTask(
+ occurrence_id,
+ work.revision,
+ target,
+ "Waiting\n🧰" if target is OccurrenceState.BLOCKED else "",
+ )
+ before, before_counts = state(store, occurrence_id), counts(store)
+ original = SQLiteTasks.save_occurrence
+
+ def fail(self, value, expected_revision):
+ original(self, value, expected_revision)
+ raise StorageFailure("injected_progress_failure")
+
+ with monkeypatch.context() as patch:
+ patch.setattr(SQLiteTasks, "save_occurrence", fail)
+ with pytest.raises(StorageFailure, match="injected_progress_failure"):
+ commands.transition("retry-progress", request)
+ assert state(store, occurrence_id) == before
+ assert counts(store) == before_counts
+ receipt = commands.transition("retry-progress", request)
+ after = state(store, occurrence_id)
+ assert after[0].state is target and after[0].revision == work.revision + 1
+ assert after[0].assignee_ids == work.assignee_ids
+ assert commands.transition("retry-progress", request) == receipt
+ assert state(store, occurrence_id) == after
+
+
def link(store, occurrence_id, required, subtasks=()):
# Seed pre-existing references; the public dependency editor remains separate work.
with store.write() as unit:
diff --git a/tests/backend/test_task_http.py b/tests/backend/test_task_http.py
index bc19ce02..51e34231 100644
--- a/tests/backend/test_task_http.py
+++ b/tests/backend/test_task_http.py
@@ -102,6 +102,96 @@ def test_assignment_original_read_preserves_the_recorded_members_and_current_aut
assert api.client.get(PREFIX + "/requests/task.assign/assign").status_code == 403
+def test_transition_original_preserves_reason_replay_and_current_authority(api):
+ created = create(api)
+ occurrence = created["result"]["occurrence_id"]
+ member = api.client.get("/api/v1/authorization").json()["member"]["member_id"]
+ checked(
+ api,
+ "put",
+ "/occurrences/" + occurrence + "/assignment",
+ {"expected_revision": 1, "assignee_ids": [member]},
+ "assign",
+ )
+ started = checked(
+ api,
+ "post",
+ "/occurrences/" + occurrence + "/transition",
+ {"expected_revision": 2, "target": "in_progress", "reason": ""},
+ "start",
+ )
+ body = {"expected_revision": 3, "target": "blocked", "reason": "Waiting for parts\n🧰"}
+ blocked = checked(api, "post", "/occurrences/" + occurrence + "/transition", body, "block")
+ current = api.client.get(PREFIX + "/occurrences/" + occurrence).json()
+ assert current["work"]["state"] == "blocked"
+ assert current["work"]["state_reason"] == body["reason"]
+ assert current["work"]["assignee_ids"] == [member]
+ original = api.client.get(PREFIX + "/requests/task.transition/start")
+ assert original.status_code == 200, original.text
+ assert original.json() == {
+ **started,
+ "delivery": "pending",
+ "action": "task.transition",
+ "command_key": "start",
+ }
+ recovered = api.client.get(PREFIX + "/requests/task.transition/block")
+ assert recovered.status_code == 200, recovered.text
+ assert recovered.json()["operation_id"] == blocked["operation_id"]
+ assert recovered.json()["result"]["state_reason"] == body["reason"]
+ history = api.client.get(PREFIX + "/occurrences/" + occurrence + "/history").json()
+ assert (
+ checked(api, "post", "/occurrences/" + occurrence + "/transition", body, "block") == blocked
+ )
+ changed = api.client.post(
+ PREFIX + "/occurrences/" + occurrence + "/transition",
+ json={**body, "reason": "A different obstacle"},
+ headers=api.headers("block"),
+ )
+ assert changed.status_code == 409
+ assert api.client.get(PREFIX + "/occurrences/" + occurrence).json() == current
+ assert api.client.get(PREFIX + "/occurrences/" + occurrence + "/history").json() == history
+ assert api.client.get(PREFIX + "/requests/task.transition/missing").status_code == 404
+ assert (
+ api.client.get(PREFIX + "/requests/task.transition/block?actor_id=other").status_code == 422
+ )
+ with api.store.write() as unit:
+ actor = unit.members.get("home", member)
+ unit.members.save(
+ replace(actor, role=Role.VIEWER, revision=actor.revision + 1), actor.revision
+ )
+ api.user("a" * 32)
+ assert api.client.get(PREFIX + "/requests/task.transition/block").status_code == 403
+
+
+@pytest.mark.parametrize("reason", [" \n\t", "A\x00B", "\ud800", "🧰" * 1001])
+def test_progress_reason_rejection_at_the_normal_http_boundary_is_inert(api, reason):
+ import json
+
+ occurrence = create(api)["result"]["occurrence_id"]
+ path = "/occurrences/" + occurrence
+ before = api.client.get(PREFIX + path).json()
+ history = api.client.get(PREFIX + path + "/history").json()
+ response = api.client.post(
+ PREFIX + path + "/transition",
+ content=json.dumps({"expected_revision": 1, "target": "blocked", "reason": reason}),
+ headers={**api.headers("invalid-progress"), "Content-Type": "application/json"},
+ )
+ assert response.status_code == 422
+ assert api.client.get(PREFIX + path).json() == before
+ assert api.client.get(PREFIX + path + "/history").json() == history
+ assert api.client.get(PREFIX + "/requests/task.transition/invalid-progress").status_code == 404
+
+
+def test_progress_http_accepts_and_recovers_the_exact_unicode_reason_bound(api):
+ occurrence = create(api)["result"]["occurrence_id"]
+ body = {"expected_revision": 1, "target": "blocked", "reason": "🧰" * 1000}
+ receipt = checked(api, "post", "/occurrences/" + occurrence + "/transition", body, "bound")
+ assert receipt["result"]["state_reason"] == body["reason"]
+ original = api.client.get(PREFIX + "/requests/task.transition/bound")
+ assert original.status_code == 200
+ assert original.json()["result"] == receipt["result"]
+
+
@pytest.mark.parametrize("amount", [0, 225, 1_000_000])
def test_configured_task_preserves_exact_amount_in_original_receipt(api, amount):
body = {"title": "Inspect the filter", "overrides": {"point_value_minor": amount}}
diff --git a/tests/backend/test_task_queries.py b/tests/backend/test_task_queries.py
index 86c905ee..37f3f789 100644
--- a/tests/backend/test_task_queries.py
+++ b/tests/backend/test_task_queries.py
@@ -316,6 +316,7 @@ def test_own_operation_lookup_rechecks_original_authority_without_rerunning_prec
"task.create",
"task.claim",
"task.assign",
+ "task.transition",
"task.complete",
"task.verify",
"task.reopen",
diff --git a/tests/python/test_ci_contract.py b/tests/python/test_ci_contract.py
index 16f4f5cf..28bb0cfb 100644
--- a/tests/python/test_ci_contract.py
+++ b/tests/python/test_ci_contract.py
@@ -373,10 +373,10 @@ def test_both_cpu_images_run_all_actual_household_browser_journeys() -> None:
audit = next(
step
for step in steps
- if step.get("name") == "Require all sixty actual-image household journeys"
+ if step.get("name") == "Require all sixty-four actual-image household journeys"
)
assert all(field in audit["run"] for field in ["expected", "unexpected", "skipped", "flaky"])
- assert "expected']==60" in audit["run"]
+ assert "expected']==64" in audit["run"]
cleanup = next(
step for step in steps if step.get("name") == "Require no surviving image browser fixtures"
)