From 2f08cc89d91749d8a07d9870c9133bd25aa21553 Mon Sep 17 00:00:00 2001 From: "copilot-action[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:09:35 +0100 Subject: [PATCH 1/7] docs(sdd): specify issue contract in specs/task-assignment-interface.md --- specs/CATALOG.md | 4 +- specs/catalog.json | 3 +- specs/task-assignment-interface.md | 245 +++++++++++++++++++++++++++++ 3 files changed, 249 insertions(+), 3 deletions(-) create mode 100644 specs/task-assignment-interface.md diff --git a/specs/CATALOG.md b/specs/CATALOG.md index 3be3e543..6ae7c28c 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) + 2 companion | 53 paths · 2026-11-11 | +| `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 | 53 paths · 2026-11-11 | | `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-11 -- 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) +- 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) - 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) diff --git a/specs/catalog.json b/specs/catalog.json index d4722bab..08f783d6 100644 --- a/specs/catalog.json +++ b/specs/catalog.json @@ -481,7 +481,8 @@ "specs": [ "specs/household-tasks.md", "specs/task-execution-foundation.md", - "specs/household-task-categories.md" + "specs/household-task-categories.md", + "specs/task-assignment-interface.md" ], "workflows": [ ".github/workflows/ci_check.yml" diff --git a/specs/task-assignment-interface.md b/specs/task-assignment-interface.md new file mode 100644 index 00000000..9e1f3cf1 --- /dev/null +++ b/specs/task-assignment-interface.md @@ -0,0 +1,245 @@ +# Assign and release household tasks from the Tasks workspace + +- Status: Draft +- Catalog capability: household-tasks + +## 1. Executive summary + +This companion specifies the Tasks workspace delta for authorized managers to review, replace, or release a task’s planned assignees. The workspace discovers assignment from the selected task’s current server-derived actions, loads authorized active household members, and submits canonical member identities with that task’s current revision. Save and recovery preserve the existing command’s authorization, state rules, and original-operation guarantees. The retained contracts and cases in `specs/household-tasks.md` and `specs/task-execution-foundation.md` remain authoritative; this document adds the assignment interface and its recovery behavior. + +## 2. Problem, current behavior, and evidence + +### 2.1 Problem + +The Tasks workspace supports self-claiming, completion, and review, but task managers need a discoverable way to distribute planned work, replace assignees, or return eligible work to the shared pool. The requested change connects the existing protected assignment capability to the workspace; it does not define a new assignment contract. + +### 2.2 Current behavior + +The selected implementation contains task assignment and authorization boundaries, a task detail action named `assign`, an authorized roster read, and frontend task request and journal boundaries. The task presentation currently renders self-claim, completion, and review; the requested manager assignment editor is prospective. These are source observations, not evidence that this interface or the requested acceptance outcomes are implemented. + +### 2.3 Evidence + +`backend/src/domus/entrypoints/task_http.py` exposes the assignment endpoint. `backend/src/domus/application/task_commands.py` contains `TaskCommands.assign` and assignee validation; `backend/src/domus/application/task_authorization.py` maps `task.assign` to task-management permission. `backend/src/domus/application/task_queries.py` supplies task detail actions, and `backend/src/domus/application/household_roster.py` owns the roster query. Frontend boundaries include `frontend/src/presentation/domus-tasks.ts`, `frontend/src/application/task-controller.ts`, `frontend/src/application/task-ports.ts`, `frontend/src/adapters/task-http.ts`, and `frontend/src/adapters/task-journal.ts`. The retained contracts in `specs/household-tasks.md` and `specs/task-execution-foundation.md` govern assignment, task state, authority, revision, and operation receipts. The current assignment interface and its acceptance are proposed, not observed. + +## 3. Actors, surfaces, and terminology + +The household task manager enters from a selected task in the Tasks workspace and may edit only when that task’s current server-derived actions allow assignment. Household members are the available assignee choices; the visible names and current selection come from authorized member discovery. The task command remains the authority for household scope and current permission. Restricted members who are eligible to claim work continue through the established self-claim journey rather than receiving manager assignment controls. + +“Planned assignees” means the task’s current assigned member identities, distinct from the actor who submits a command and from actual performers recorded under the retained task contract. “Release” means saving an empty assignee set only where the task’s current state permits it. The interface must use canonical member identities for commands and readable names for people. + +## 4. Goals, non-goals, and fixed invariants + +### 4.1 Goals + +The proposed delta must let a currently authorized manager discover assignment from task detail, review existing assignees, discover authorized active household members, and save one or more canonical identities against the selected task revision. It must support replacement and state-permitted release, enforce the unique-member maximum of 32, and expose clear outcomes for loading, empty or unavailable discovery, denied access, invalid selection, conflict, uncertain response, and confirmed assignment. + +If a competing revision wins, show the current task while retaining the local selection; require explicit review and a deliberate save using the refreshed revision. Recovery of a saved request must use its original request key, body, and scope. The complete English and Spanish desktop-keyboard and narrow-screen touch journeys must support accessible labels and focus, cancellation, save, retry, and understandable status feedback. Ingress and standalone acceptance must preserve the assigned task and original operation through restart and permit inspection of audit, completion, and performer behavior. + +### 4.2 Non-goals + +This companion does not change the task and execution contracts, their existing case identities, assignment authorization policy, task-state rules, self-claim policy, completion behavior, or performer attribution. It does not add assignment beyond the selected task’s advertised actions or broaden member discovery, household scope, or permissions. + +### 4.3 Fixed product/safety invariants + +Every assignment command must recheck current task-management authority and household scope at the command boundary, including revocation and member/profile exceptions. A client-visible action or selected identity is not proof of authority. Only authorized active household members may be admitted, subject to the established contract; duplicates, malformed identities, foreign members, and unsupported counts must be rejected through normal entry points. Release must obey the existing state machine, including the required assignee set for in-progress work. + +A conflict must not silently overwrite another update or discard the user’s draft. A retry or recovery must identify the original operation and return its recorded result at most once; it must not mutate the frozen request’s key, body, or scope. These are additions to the interface contract, not replacements for the retained requirements in `specs/household-tasks.md` and `specs/task-execution-foundation.md`. + +| Requirement | Behavior | +| --- | --- | +| SDD-I141-U1-R1 | In the Tasks workspace, a currently authorized task manager can discover the server-derived assign action, load authorized active household members, review the current assignment, and save one or more canonical member identities using the selected task revision, subject to the unique-member limit of 32 and task-state release rules. | +| SDD-I141-U1-R2 | Assignment commands enforce current task-management authority and household scope, including revocation and member/profile exceptions; eligible restricted members use the established self-claim journey. | +| SDD-I141-U1-R3 | After a competing revision, the interface shows the current task, retains the draft selection, and requires explicit review and deliberate retry with the refreshed revision; recovery preserves the original request key, body, and scope. | +| SDD-I141-U1-R4 | The interface distinguishes loading, empty member discovery, read failure, denied access, invalid selection, conflict, uncertain response, and confirmed assignment, and retains selected members when recovery is available. | +| SDD-I141-U1-R5 | The complete English and Spanish desktop-keyboard and narrow-screen touch journeys support editing, focus, labels, cancellation, save, retry, and understandable status feedback. | +| SDD-I141-U1-R6 | Ingress and standalone preserve the assigned task and original operation across restart, with inspectable audit and accepted completion and performer behavior. | + +## 5. Current versus proposed product journey + +The immutable owners `specs/household-tasks.md` and `specs/task-execution-foundation.md` remain authoritative for task lifecycle, assignment, authorization, revisions, receipts, and history. This companion adds the assignment-management journey to the existing Tasks workspace; it does not replace those contracts or their cases. + +| Stage | Current contract | Proposed Tasks workspace journey | User effect | +|---|---|---|---| +| Open task | Task detail exposes server-derived actions; the selected task revision and current authorization govern commands. | A manager opens the selected task and sees assignment controls only when its current server-derived actions include `assign`. | The control reflects current eligibility rather than a client-side role guess. | +| Discover and review | Authorized household member reads are bounded and permission-scoped. Assignment distinguishes planned assignees from performers and the actor. | Load eligible active household members, display readable names and accessible selection labels, and show the current assignment. | The manager can review responsibility before changing it; an empty or unavailable directory is explicit. | +| Edit and save | Assignment replaces the assignee set under task-management authority and expected revision; at most 32 unique members are supported. | Select one or more canonical member identities, or clear the selection to release work where the task state permits. Save deliberately against the selected task revision using the existing request journal. | The task contract remains in force, including the required assignee set for in-progress work. | +| Resolve and observe | A stale revision does not apply a change; operation receipts identify the original request. | On conflict, show the current task while retaining the draft; require review and a deliberate save with the refreshed revision. On uncertain response, recover using the frozen original key, body, and scope. | The manager can distinguish unapplied work from a confirmed assignment and recover without creating a second operation. | + +Flow: open task -> discover and review members -> edit selection -> save at current revision -> confirm, review conflict, or recover the original operation. The selected task and member identities remain within current household scope throughout. + +## 6. Functional behavior and state model + +### 6.1 Normal path and alternatives + +1. The Tasks workspace reads task detail and uses its current server-derived `assign` action to offer assignment management. The command boundary independently checks current task-management authority and household scope; visibility is not authorization. +2. The workspace loads authorized active household members and presents their names with the task’s current selected members. Loading, successful empty discovery, and read failure have distinct feedback. Inactive, outdated, or unauthorized options cannot be admitted as valid current choices. +3. The manager selects up to 32 unique canonical member identities and saves against the displayed task revision. A successful response reports the confirmed assignment; refreshing task detail shows the committed planned assignees. Replacing the set is supported. Clearing it releases supported task states to the shared pool; an in-progress task must retain its contractually required assignee set. +4. A restricted member eligible to self-claim follows the established self-claim journey. The editor and direct command do not grant reassignment authority to a restricted member or treat a selected identity as proof of authority. + +Malformed, duplicate, over-limit, inactive, or foreign identities produce actionable validation or denial while preserving the editable draft when safe. Current authorization, membership/profile exceptions, and scope are checked at command time, including after revocation. These rules extend the retained assignment and permission contracts in `specs/household-tasks.md` and `specs/task-execution-foundation.md`. + +### 6.2 State and recovery + +| Interface state | Meaning and next action | Retained facts | +|---|---|---| +| Loading members/task | Current authorized reads are pending; wait for results. | Existing draft selection. | +| Empty member discovery | Read succeeded with no eligible active options; explain that assignment cannot proceed and allow refresh or exit. | Existing task context and draft where applicable. | +| Read failure | Discovery or task read failed; offer an explicit retry when safe. Do not present failure as an empty list. | Existing draft selection. | +| Denied | Current authority or household scope does not permit the read or command; do not expose protected member/task details. Eligible restricted members may use self-claim where offered. | Only information already authorized for display. | +| Invalid selection | The submitted selection violates identity, uniqueness, count, availability, or task-state rules; correct the selection. | Draft selection and current task context. | +| Conflict | Another change won at the selected revision; show the current task, retain the draft, and require deliberate review and save using the refreshed revision. Never blindly retry a changed assignment. | Refreshed task/revision and editable draft. | +| Uncertain response | The client cannot determine whether the command completed; recover or retry the exact original request using its frozen key, body, and scope. | Original operation identity and payload. | +| Confirmed assignment | The command receipt confirms the recorded result; refresh may verify the current task projection. | Receipt and committed assignment facts. | + +A lost response recovered under the same frozen operation returns the original recorded assignment once. A changed payload under the same key is not a retry; a genuinely new deliberate command requires a new operation identity. Existing receipt, revision, and history semantics remain owned by the immutable task contracts. The concrete observable journeys include replacement/release and the in-progress constraint, authorization and denial, authorized member discovery, conflict review, frozen-request recovery, and validation boundaries. + +## 7. User-facing configuration + +No user-facing configuration is introduced. The assignment editor uses the existing task-management authority, household scope, task state machine, expected revision, and unique-member limit of 32. These are fixed contract constraints, not preferences a household can weaken. The selected task and authorized discovery determine the available choices; the current assignment is displayed for review. Eligible restricted members continue to use the established self-claim policy and journey described by `specs/task-execution-foundation.md`. No new persistence or migration setting is required by this interface delta. + +## 8. Clean Architecture design + +### 8.1 Responsibilities and dependency direction + +The assignment interface extends existing task boundaries described in `specs/household-tasks.md` and `specs/task-execution-foundation.md`; it must not create a parallel authorization or task-state implementation. + +| Boundary | Responsibility for this delta | Must not own | +|---|---|---| +| Domain policy | Existing task policy defines valid assignee sets, release eligibility, in-progress constraints, revisions, and task transitions. | UI selection state, provider DTOs, or presentation decisions. | +| Application | Coordinate authorized member discovery and assignment command; return semantic outcomes for success, denial, validation, conflict, and recovery. | Framework rendering or client-side authority decisions. | +| Semantic ports | Express task detail/action, authorized member discovery, assignment, and original-operation recovery in domain terms. | Provider-specific response shapes as product policy. | +| Adapters and infrastructure | Map the existing task and roster interfaces, HTTP results, and request-journal records to semantic contracts; preserve operation identity and map errors accurately. | Duplicated task authorization/state rules or claims that a request succeeded without its result. | +| Entrypoints and composition | Adapt authenticated workspace/API input and wire the existing services while preserving the established trust boundary. | Duplicated orchestration or trusting client-supplied member IDs as authority. | +| Presentation | Render task action availability, member names and labels, current/draft selection, status, and recovery choices accessibly in English and Spanish. | Authorization, mutation policy, revision resolution, or direct persistence. | + +Dependency direction: Tasks workspace presentation -> application use cases -> domain policy and semantic ports <- task/member adapters; composition supplies adapters to the existing entrypoints. View state may retain a draft selection, while the server remains authoritative for current task, members, permission, revision, and command outcome. + +### 8.2 Contracts, state, and trust boundaries + +The assignment command accepts canonical member identities, the selected expected task revision, and the existing operation identity/scope contract. Authorized member discovery supplies names and eligibility data; the client must not infer eligibility from cached profiles or treat a supplied identity as a grant. The command rechecks current task-management authority, household scope, member/profile exceptions, and revision at commit. The existing task request journal freezes key, body, and scope for recovery. Conflict refresh changes the revision used by a later deliberate command, not the original operation payload. Receipts and task history remain the durable evidence of committed assignment and actor. + +### 8.3 Executable constraints + +Architecture and acceptance evidence must demonstrate that UI action visibility cannot bypass command authorization; assignment and release use the existing revisioned command boundary; member reads remain permission-scoped; retries preserve the original request; and provider errors map to distinct user-observable states. The repository standard requires executable dependency/contract checks, but the concrete invocation and prerequisites for specification validation are unverified in the selected project; do not treat an example command as evidence that this interface or its boundaries have been checked. + +## 9. UI/UX and content contract + +The Tasks workspace exposes assignment editing only when the selected task’s current server-derived actions include `assign`. Show the current assignees by readable name, load available choices through authorized household member discovery, and submit canonical member identities with the selected task revision. Allow up to 32 unique members. Offer release to the shared pool only when the task state permits an empty assignee set; preserve the in-progress assignee constraint. Replacing an assignment or releasing work must be a deliberate save. The retained task state and authorization contracts remain in `specs/household-tasks.md` and `specs/task-execution-foundation.md`. + +```text +Assign task: Water the plants +Current assignees: Mina +Select household members (up to 32) +[x] Mina +[ ] Luis + +[Cancel] [Save assignment] +``` + +Provide localized labels, instructions, validation, and status feedback in English and Spanish, following the existing fallback conventions. The editor and member list must work with keyboard and touch at desktop and narrow-screen sizes, with visible logical focus, accessible names, and state conveyed in text. Cancellation returns to task detail without saving. After a save, show whether the assignment was confirmed and who is responsible; do not imply success while the result is uncertain. The existing task presentation contract is in `specs/task-execution-foundation.md`. + +## 10. Failure, recovery, and cleanup + +Show distinct loading, empty member list, read failure, denied access, invalid selection, conflict, uncertain response, and confirmed assignment states. Empty discovery is not a read failure. Explain errors in impact, cause, next action, then retained state order. Keep the draft selection when recovery is possible. + +If the task revision changed, show the current task and its assignment, retain the draft, and require the manager to review and deliberately save again with the refreshed revision. Do not silently rebase or automatically resubmit. For a lost response, recover or retry the original operation using its frozen request key, body, and scope; return the original recorded result once. A genuinely changed request requires a new operation. These rules extend the revision and receipt behavior in `specs/task-execution-foundation.md`. + +## 11. Security, permissions, and privacy + +The editor is a presentation affordance, not an authority boundary. Recheck current task-management authority, household scope, membership and applicable member/profile exceptions at the command boundary, including revocation between display and save. A selected member identity conveys no authority. Denied, restricted, revoked, or foreign-household attempts must not change the assignment or disclose unauthorized member data. Eligible restricted members use the established self-claim journey. Use authorized member discovery for options and current selections; reject inactive, outdated, malformed, duplicate, over-limit, or foreign identities through normal entry points. Preserve the task execution authorization and privacy contract in `specs/task-execution-foundation.md`. + +## 12. Observability and operational UX + +Give the manager a clear status for discovery and save, including whether action is required and whether responsibility has changed. On success, show the confirmed assignee names and refreshed task state. On conflict or uncertain response, state what is known, what remains unresolved, and the recovery action. Operational evidence may distinguish denial, validation failure, revision conflict, and unavailable discovery, using existing sanitized handling. Do not expose credentials, household identifiers, unrestricted payloads, or unnecessary member details in diagnostics. No new external telemetry or notification behavior is established by this delta; concrete logging or metric hooks remain unverified in the selected source. + +## 13. Compatibility, migration, rollout, and rollback + +This companion adds assignment management to the existing Tasks workspace and relies on the retained task command, revision, authorization, and operation-receipt contracts in `specs/household-tasks.md` and `specs/task-execution-foundation.md`. Preserve existing task states, self-claim and completion behavior, and in-flight operation recovery. The required behavior applies to ingress and standalone: after restart, the assigned task and original operation remain recoverable, with inspectable audit and the accepted completion and performer behavior. Determine whether migration is needed from implementation evidence; no migration or rollout mechanism is established by this draft. Validate the English and Spanish journeys, both deployment targets, restart and restore behavior, and installed Edge acceptance as product outcomes. The concrete invocation and prerequisites for these checks remain unverified in the selected source. + +## 14. Testing strategy and numeric budget + +The minimum budget is nine distinct companion cases, one for each defined acceptance scenario. This is a floor, not evidence that tests have run or that the behavior is complete. Allocate coverage across authorized assignment and member discovery; task-state and member-identity validation; revision conflict and original-operation recovery; English/Spanish keyboard and touch usability; and persistence, audit, and completion/performer behavior in both ingress and standalone compositions. Exercise normal entry points and direct commands, including current authority and household scope. Use deterministic responses and controlled restart/recovery conditions; do not count repeated runs of the same behavior as distinct cases. + +The retained contracts remain authoritative for task-state, assignment, authorization, and execution behavior: `specs/household-tasks.md` (including household-tasks-R3) and `specs/task-execution-foundation.md` (including TEF-03 and the assignment and role-default sections). Their existing cases remain references and are not redefined or credited to this companion. The selected source shows the assignment route in `backend/src/domus/entrypoints/task_http.py`; `TaskCommands.assign` is declared in `backend/src/domus/application/task_commands.py`. Task action derivation is in `backend/src/domus/application/task_queries.py`. These are source facts, not acceptance evidence for the proposed interface. + +The repository standard names `pnpm run validate:specifications` in `specs/README.md`, but this draft has not verified its execution prerequisites or the referenced validator definition. No concrete invocation for complete SDK specification/catalog consistency is established here. Record validation as an outcome: authored specification requirements are checked against the required format and internal/cross-document consistency, without representing a command declaration as an executed or passing check. + +| Area | Minimum distinct cases | Behaviors/risks covered | +|---|---:|---| +| assignment | 2 | Observable scenarios in the case inventory. | +| authorization | 1 | Observable scenarios in the case inventory. | +| member discovery | 1 | Observable scenarios in the case inventory. | +| conflict | 1 | Observable scenarios in the case inventory. | +| recovery | 1 | Observable scenarios in the case inventory. | +| validation | 1 | Observable scenarios in the case inventory. | +| usability | 1 | Observable scenarios in the case inventory. | +| persistence | 1 | Observable scenarios in the case inventory. | +| Total | 9 | Distinct inventory cases; repeated executions do not add cases. | + +| Case ID | Area | Requirements | Scenario | +| --- | --- | --- | --- | +| task-assignment-interface-C01 | assignment | SDD-I141-U1-R1 | An authorized task manager selects one or multiple active members and observes the committed planned assignment after refresh. | +| task-assignment-interface-C02 | assignment | SDD-I141-U1-R1 | The manager replaces an existing assignment and releases a supported task to the shared pool; an in-progress task enforces its required assignee set. | +| task-assignment-interface-C03 | authorization | SDD-I141-U1-R2 | Current authority and scope govern the editor and direct command. Restricted, denied, revoked, and foreign-household attempts receive the appropriate denial. | +| task-assignment-interface-C04 | member discovery | SDD-I141-U1-R1, SDD-I141-U1-R4 | Member options and current selections use authorized discovery. Empty, unavailable, inactive, and outdated options have explicit recovery and admission outcomes. | +| task-assignment-interface-C05 | conflict | SDD-I141-U1-R3, SDD-I141-U1-R4 | A competing revision produces a conflict. Reviewing the current task retains the draft selection and requires a deliberate save using the refreshed revision. | +| task-assignment-interface-C06 | recovery | SDD-I141-U1-R3, SDD-I141-U1-R4 | A lost response is resolved through the same frozen key and body. Retrying or recovering returns the original recorded assignment once. | +| task-assignment-interface-C07 | validation | SDD-I141-U1-R1, SDD-I141-U1-R4 | Supported member-count boundaries and malformed, duplicate, or foreign identities are validated through the normal entry points. | +| task-assignment-interface-C08 | usability | SDD-I141-U1-R5 | English keyboard and Spanish mobile touch journeys cover editing, cancellation, save, conflict review, and retry with understandable focus and feedback. | +| task-assignment-interface-C09 | persistence | SDD-I141-U1-R6 | Ingress and standalone retain the assigned task and original operation after restart, with an inspectable audit and the accepted completion and performer behavior. | + +## 15. Documentation and discoverability + +Document the Tasks workspace assignment journey, including how managers discover the server-derived action, choose and review members, release work when allowed, and recover from conflicts or uncertain responses. Explain the visible states and the meaning of a confirmed assignment, and provide localized English and Spanish guidance consistent with the interface. Keep task rules and authority in the retained owners, `specs/household-tasks.md` and `specs/task-execution-foundation.md`; this companion documents their interface and recovery delta rather than restating those contracts. The existing user guide is `docs/user-guide.md`. + +The selected project declares `@vypdev/ha-ui` version `0.1.0-next.2` in `frontend/package.json`; the interface should use the published controls specified by the issue while preserving the existing frontend task boundaries. The request journal boundary is declared as `TaskJournalPort` in `frontend/src/application/task-ports.ts`, with `TaskSessionJournal` in `frontend/src/adapters/task-journal.ts`. Concrete verification of the package's rendered behavior and a complete SDK consistency invocation remain unverified. + +| Path | Change | +| --- | --- | +| specs/task-assignment-interface.md | create | + +[specs/task-assignment-interface.md](task-assignment-interface.md) + +## 16. Acceptance scenarios + +These are future observable acceptance scenarios; none is represented as implemented, executed, or passed. + +1. In the Tasks workspace, a currently authorized task manager sees the assignment control only when the selected task’s server-derived actions allow it, discovers authorized active household members, and saves one or multiple canonical identities at the selected revision. After refresh, the planned assignment is visible. Replacing an assignment and releasing supported work behave according to the retained task-state rules; an in-progress task preserves its required assignee set. (task-assignment-interface-C01, task-assignment-interface-C02) +2. Current task-management authority and household scope govern both editor and command. Restricted, denied, revoked, and foreign-household attempts are denied appropriately, while eligible restricted members can use the established self-claim journey. Member discovery distinguishes empty, unavailable, inactive, and outdated options and gives an explicit recovery and admission outcome. (task-assignment-interface-C03, task-assignment-interface-C04) +3. When a competing revision wins, the interface identifies the conflict and shows the current task. It retains the draft selection, requires review, and only retries after deliberate action using the refreshed revision. If a response is lost, recovery uses the original frozen request key and body and returns the original recorded assignment once. (task-assignment-interface-C05, task-assignment-interface-C06) +4. Normal entry points reject unsupported member counts, malformed or duplicate identities, and foreign identities with understandable validation. Loading, empty discovery, read failure, denial, invalid selection, conflict, uncertain response, and confirmed assignment are distinguishable; selected members remain available when recovery permits. (task-assignment-interface-C04, task-assignment-interface-C06, task-assignment-interface-C07) +5. The complete English desktop keyboard journey and Spanish narrow-screen touch journey support editing, labels, focus, cancellation, save, conflict review, retry, and understandable status feedback. (task-assignment-interface-C08) +6. In both ingress and standalone, restart retains the assigned task and original operation; the audit can be inspected, and accepted completion and performer behavior remains intact under the retained contracts. (task-assignment-interface-C09) + +The companion scenarios refine the existing task journey; they do not change the retained owners’ state machine, assignment semantics, or role defaults. + +## 17. Requirements traceability + +The host-maintained traceability inventory must map each requirement to only the cases that exercise it, reciprocally with the case definitions. Assignment discovery, authorized member selection, save, revision, member limit, and state-permitted release map to task-assignment-interface-C01, task-assignment-interface-C02, task-assignment-interface-C04, and task-assignment-interface-C07. Current authority, household scope, revocation, restricted-member exceptions, and self-claim map to task-assignment-interface-C03. Conflict review and deliberate refreshed-revision retry map to task-assignment-interface-C05; frozen-key/body recovery maps to task-assignment-interface-C06. Distinct interface states and retained selections map to task-assignment-interface-C04, task-assignment-interface-C05, task-assignment-interface-C06, and task-assignment-interface-C07. Localization, input mode, focus, labels, cancellation, save, and retry map to task-assignment-interface-C08. Restart, audit, and retained completion/performer behavior map to task-assignment-interface-C09. Preserve all nine case identities exactly; existing owner case IDs are references, not new definitions. + +Publication acceptance must make three outcomes observable: the specification satisfies the required format; internal and cross-document consistency is checked; and reciprocal catalog ownership, paths, and evidence agree with the generated view. Structural counts and reciprocal mappings establish inventory consistency only; they do not establish semantic completeness or executed acceptance. The selected tree declares `pnpm run validate:specifications` in `specs/README.md`, but the invocation prerequisites and validator definition were not inspected, so its availability and scope remain unverified. No specific command is asserted as satisfying these publication outcomes. + +| Requirement | Cases | +|---|---| +| SDD-I141-U1-R1 | task-assignment-interface-C01, task-assignment-interface-C02, task-assignment-interface-C04, task-assignment-interface-C07 | +| SDD-I141-U1-R2 | task-assignment-interface-C03 | +| SDD-I141-U1-R3 | task-assignment-interface-C05, task-assignment-interface-C06 | +| SDD-I141-U1-R4 | task-assignment-interface-C04, task-assignment-interface-C05, task-assignment-interface-C06, task-assignment-interface-C07 | +| SDD-I141-U1-R5 | task-assignment-interface-C08 | +| SDD-I141-U1-R6 | task-assignment-interface-C09 | + +## 18. Implementation sequence + +Implement the Tasks workspace delta against the retained contracts in `specs/household-tasks.md` and `specs/task-execution-foundation.md`; leave `specs/household-task-categories.md` unchanged. Connect the server-derived assignment action and authorized active-member discovery to an editor that shows readable current assignees, accepts canonical member identities, and submits the selected task revision. Enforce current task-management authority and household scope at the command boundary, the unique-member limit of 32, and the existing state rules for replacement and release, including the in-progress assignee constraint. Preserve the eligible restricted-member self-claim journey. + +Implement conflict review so the current task is shown while the draft selection remains available; require a deliberate save with the refreshed revision. Freeze the original request key, body, and scope for uncertain-response recovery. Present distinct loading, empty, read-failure, denied, invalid-selection, conflict, uncertain, and confirmed states, retaining selections when recovery is available. Complete the English and Spanish keyboard and narrow-screen touch journeys, then qualify authorized assignment and release, authority and scope denials, member discovery outcomes, conflict review, original-operation recovery, input boundaries, localization and accessibility, and persistence across restart in ingress and standalone. Determine migration needs from implementation evidence and verify audit, completion, and performer behavior against the retained task contract. + +## 19. Definition of Done + +Done when all nine supplied acceptance cases preserve their declared identities and concrete observable assertions, and every requirement maps only to cases that exercise it. Evidence must establish that authorized managers can assign one or more active members, replace assignments, and release supported tasks; current authority and household scope govern both the editor and direct command; member discovery and its empty, unavailable, inactive, and outdated outcomes are explicit; conflicts retain the draft and require reviewed retry at the refreshed revision; and uncertain responses recover the original recorded assignment once using the frozen request. Verify supported member-count boundaries and rejection of malformed, duplicate, or foreign identities through normal entry points. Verify understandable English keyboard and Spanish mobile touch flows, including focus, labels, cancellation, save, conflict review, and retry. Verify ingress and standalone restart persistence, inspectable audit, and the retained completion and performer behavior. These are acceptance outcomes, not claims that implementation or tests have run. + +The specification satisfies the required format; internal and cross-document consistency is checked; reciprocal catalog ownership, paths, and evidence agree with the generated view. Preserve these three publication outcomes as explicit acceptance gates. The selected source documents the specification standard in `specs/README.md`; the concrete invocation and prerequisites for these publication checks remain unverified. Required product validation, coverage, and deployment evidence must be reported with their actual scope; a declaration or structural count alone is not executed acceptance or semantic completeness. + +## 20. References and decisions + +Issue: https://github.com/vypdev/domus/issues/141. This is a bounded companion delta for the household-tasks capability. Existing contracts and cases remain owned by the immutable `specs/household-tasks.md` and `specs/task-execution-foundation.md`; `specs/household-task-categories.md` remains unchanged. The selected source revision is `6c7428dd7101a375802b67c3c7e8c2513b2c2053`. The repository standard is `specs/README.md`. The issue describes existing assignment, authorization, revision, receipt, and member-discovery entry points; implementation details and verification outcomes must be confirmed against the selected project during implementation. No verification command or passing result is asserted here. From 95fff8ab5ff0a5a85872596447c314e365813d1b Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 06:09:34 +0100 Subject: [PATCH 2/7] feat(tasks): manage planned assignees and recover original assignments --- .github/workflows/ci_check.yml | 4 +- backend/src/domus/application/task_queries.py | 1 + backend/src/domus/entrypoints/task_http.py | 2 +- docs/contracts/household-api.openapi.json | 2 + .../native-household-api.openapi.json | 2 + .../evidence/task-assignment-qualification.md | 42 +++ .../evidence/task-navigation-integration.json | 8 +- docs/roadmap.md | 2 + docs/user-guide.md | 7 + frontend/src/adapters/task-http.ts | 9 +- frontend/src/adapters/task-values.ts | 7 +- frontend/src/application/task-controller.ts | 8 + frontend/src/application/task-ports.ts | 2 +- frontend/src/composition/entry-page.ts | 9 +- frontend/src/domain/tasks.ts | 13 + frontend/src/presentation/domus-app.ts | 2 +- frontend/src/presentation/domus-tasks.ts | 127 ++++++++- frontend/src/presentation/task-messages.ts | 32 ++- frontend/tests/e2e/tasks.spec.ts | 153 ++++++++++ frontend/tests/page.test.ts | 8 + frontend/tests/task-component.test.ts | 269 ++++++++++++++++++ frontend/tests/task-controller.test.ts | 86 ++++++ frontend/tests/task-http.test.ts | 49 ++++ frontend/tests/task-journal.test.ts | 13 + frontend/tests/tasks.test.ts | 24 ++ frontend/vitest.config.ts | 1 + specs/CATALOG.md | 10 +- specs/catalog.json | 19 +- tests/backend/test_task_http.py | 34 +++ tests/backend/test_task_queries.py | 29 +- tests/backend/test_task_restoration.py | 12 +- tests/browser/entry_server.py | 5 + tests/python/test_ci_contract.py | 4 +- 33 files changed, 947 insertions(+), 48 deletions(-) create mode 100644 docs/evidence/task-assignment-qualification.md diff --git a/.github/workflows/ci_check.yml b/.github/workflows/ci_check.yml index 05e527af..f2d6ad84 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 fifty-six actual-image household journeys + - name: Require all sixty 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']==56 and result['stats']['unexpected']==0 + assert result['stats']['expected']==60 and result['stats']['unexpected']==0 and result['stats']['skipped']==0 and result['stats']['flaky']==0" - name: Retain actual-image browser evidence diff --git a/backend/src/domus/application/task_queries.py b/backend/src/domus/application/task_queries.py index fcf59fdc..371734c0 100644 --- a/backend/src/domus/application/task_queries.py +++ b/backend/src/domus/application/task_queries.py @@ -842,6 +842,7 @@ def original(self, action: str, key: str) -> OperationView: if action not in { "task.create", "task.claim", + "task.assign", "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 cf159657..88666290 100644 --- a/backend/src/domus/entrypoints/task_http.py +++ b/backend/src/domus/entrypoints/task_http.py @@ -97,7 +97,7 @@ ) TaskWorkspaceAction = Literal[ - "task.create", "task.claim", "task.complete", "task.verify", "task.reopen" + "task.create", "task.claim", "task.assign", "task.complete", "task.verify", "task.reopen" ] diff --git a/docs/contracts/household-api.openapi.json b/docs/contracts/household-api.openapi.json index 5f0ae405..54fd3c2d 100644 --- a/docs/contracts/household-api.openapi.json +++ b/docs/contracts/household-api.openapi.json @@ -9570,6 +9570,7 @@ "enum": [ "task.create", "task.claim", + "task.assign", "task.complete", "task.verify", "task.reopen" @@ -31828,6 +31829,7 @@ "enum": [ "task.create", "task.claim", + "task.assign", "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 517eb742..c73bd1af 100644 --- a/docs/contracts/native-household-api.openapi.json +++ b/docs/contracts/native-household-api.openapi.json @@ -9532,6 +9532,7 @@ "enum": [ "task.create", "task.claim", + "task.assign", "task.complete", "task.verify", "task.reopen" @@ -31469,6 +31470,7 @@ "enum": [ "task.create", "task.claim", + "task.assign", "task.complete", "task.verify", "task.reopen" diff --git a/docs/evidence/task-assignment-qualification.md b/docs/evidence/task-assignment-qualification.md new file mode 100644 index 00000000..865693e9 --- /dev/null +++ b/docs/evidence/task-assignment-qualification.md @@ -0,0 +1,42 @@ +# Task assignment interface qualification + +[Issue #141](https://github.com/vypdev/domus/issues/141) connects the protected +assignment command to the Tasks workspace. The owning companion is +[task assignment interface](../../specs/task-assignment-interface.md), alongside +the retained household task and execution contracts. + +The editor follows the selected task's current `assign` action. It reuses the +authorized household roster, published ha-ui checkboxes and task request journal. +Current command authorization and expected revision govern every save. Provider +name availability and active household membership have separate meanings. A +missing provider name retains the canonical household identity as its label. +The existing public `task_assignee_denied` code preserves an authorized editor's +selection for correction. A current permission denial retires its protected view. + +The real lost-response journey exposed a recovery gap. The existing workspace +original-request allowlist omitted `task.assign`, returning HTTP 422 after an +assignment had committed. Both the typed route and application query now admit +the assignment action through their existing recorded-authorization boundary. +The two published OpenAPI projections include that action. A recovered receipt +binds the occurrence, revision and assignee set to the frozen request. + +| Published case | Executable evidence | +| --- | --- | +| task-assignment-interface-C01 | The [compiled assignment journey](../../frontend/tests/e2e/tasks.spec.ts) selects two named active members and checks the stored canonical identities and current projection. The [component cases](../../frontend/tests/task-component.test.ts) cover controlled ha-ui selection and deliberate save. | +| task-assignment-interface-C02 | The compiled journey replaces the set and releases work. The component tests enforce the in-progress minimum. The retained [command](../../tests/backend/test_task_commands.py) and [state policy tests](../../tests/backend/test_task_policy.py) exercise the authoritative state constraints. | +| task-assignment-interface-C03 | The [HTTP recovery regression](../../tests/backend/test_task_http.py) covers both compositions and current role revocation. The [query tests](../../tests/backend/test_task_queries.py) cover own-operation scope, explicit management exceptions and their revocation. Existing protected command tests reject restricted reassignment and unavailable household identities. | +| task-assignment-interface-C04 | The component tests distinguish pending discovery, successful empty discovery, denied access and unavailable reads, retain the draft, and expose refresh and removal of stale selections. Provider-name denial preserves canonical eligible options. | +| task-assignment-interface-C05 | Two authenticated browser tabs compete at the current revision. The losing editor retains its chosen member, shows the changed assignment and requires explicit review before a fresh save. The [controller tests](../../frontend/tests/task-controller.test.ts) also cover a conflict arriving after preflight and failed current reads. | +| task-assignment-interface-C06 | The compiled journey commits a release and drops its response. Reload and protected original-request recovery preserve the key, body and operation without another write. [HTTP decoding](../../frontend/tests/task-http.test.ts) refuses a receipt with a different assignee set. [Journal tests](../../frontend/tests/task-journal.test.ts) preserve assignment and older creation records together across reload. | +| task-assignment-interface-C07 | The [domain cases](../../frontend/tests/tasks.test.ts) admit empty release and one through 32 unique IDs, while refusing duplicates, malformed IDs and a 33rd selection. The normal composition decoder preserves those bounds. Backend assignment tests reject foreign, inactive and unsupported identities. | +| task-assignment-interface-C08 | Four compiled journeys exercise Ingress and standalone with English desktop keyboard and Spanish 390 px native touch. They cover editing, cancellation, multiple selection, save, conflict review and original-request recovery. Focus regressions cover the first choice, cancelled editor, failed validation and current-assignment review. | +| task-assignment-interface-C09 | Those journeys restart the actual composed runtime and recover the unchanged assignment operation, complete work under the actual performer, then restore the earlier checkpoint. An exact original PUT returns its historical result while the restored assignment and audit counts remain unchanged. [Restoration](../../tests/backend/test_task_restoration.py) and [history tests](../../tests/backend/test_sqlite_task_history.py) exercise durable original receipts and inspectable assignment history. | + +The interface and recovery allowlist use storage schema 34 and the existing +assignment, receipt and restoration formats. The selected ha-ui version is +`0.1.0-next.2`. + +Current-source Chromium qualification passes all four new compiled journeys. +The full frontend suite passes 1,833 cases with 100% of all four supported metrics +globally and per authored runtime file. Immutable candidate packaging, both image +architectures, installed Edge acceptance and exact-head PR gates are pending. diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json index f2942084..3fb7a02a 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.", + "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.", "actualProductFiles": { - ".vite/manifest.json": "857ddac99d888617f414cda4fbcedd4133a187b6d292750460dd8f66a732e588", - "assets/index-C5UQqRgD.js": "a7c554c95e87f2923fc82efcb873353ccf217241a0043375e9b58c09df6361fd", + ".vite/manifest.json": "57bca827cf42675475c7e61c7d04d0f4115d5a590a6e1b4adba5a77c842095fb", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "d795e3f20dc09de365a1427689e9474dc1e7fa284c43664724902d96a1620c0d" + "assets/index-CyP_LOPa.js": "4bd9bde4488b5736d19b4e4f8223faeebbd3249c847f28b201ac5c79f04f0de2", + "index.html": "2915734b7044319908e14097bbb74bce54a77a39b7e0fde850996d63f27c02ca" }, "localValidation": { "commit": "9a10d8114869be754962953903e773fe8e12c723", diff --git a/docs/roadmap.md b/docs/roadmap.md index de1ffb20..28baebfa 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -32,6 +32,8 @@ implementation, verification and packaging gates. The Family increments now cove [Base points during task creation](evidence/task-base-points-qualification.md) lets task configurators set the exact amount used by the existing award rules. Full task editors and owner acceptance of the installed recurrence experience remain open. +The [assignment interface](evidence/task-assignment-qualification.md) adds planned +assignees, replacement and release with explicit conflict review and original-request recovery. - M3 starts with the [protected product catalog and stock intake](evidence/inventory-catalog-qualification.md), followed by [movement history, adjustments and intake reversals](evidence/inventory-movement-qualification.md) and [minimum and target diff --git a/docs/user-guide.md b/docs/user-guide.md index d2cc1edd..530622cd 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -53,6 +53,13 @@ actions your role allows. Use **Retry inventory summary** if the summary could n each participant full points at whole-point precision, use a whole amount or ask a points manager to select two decimal places. Check **Family** after completing the task for posted points. - Select a task to inspect it. **Claim task** assigns eligible work to your own verified membership. **Mark done now** records you as the performer at the current server-anchored time. +- When task management is allowed, **Change assignment** opens the current planned + assignees. Select up to 32 active household members and choose **Save assignment**. + **Clear selection** prepares a release where the task state permits it. A task + in progress needs at least one assignee. **Cancel** closes the editor. + 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. - 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-http.ts b/frontend/src/adapters/task-http.ts index 26fbb2e7..4fc7be5c 100644 --- a/frontend/src/adapters/task-http.ts +++ b/frontend/src/adapters/task-http.ts @@ -21,7 +21,7 @@ function route(command: TaskCommand): string { const item = 'tasks/categories/' + command.categoryId; return command.action === 'task.category.archive' ? item + '/archive' : item; } - const action = command.action.slice(5); + const action = command.action === 'task.assign' ? 'assignment' : command.action.slice(5); return 'tasks/occurrences/' + command.occurrenceId + '/' + action; } const ASSIGNED_STATES = ['assigned', 'in_progress', 'blocked'] as const; @@ -126,15 +126,18 @@ export class HttpTaskServer implements TaskServer { const body = taskCommandBody(input.command); if (signal.aborted) throw new EntryReadError('unavailable'); posted = true; - const method = input.command.action === 'task.category.rename' ? 'PUT' : 'POST'; + const method = input.command.action === 'task.category.rename' || input.command.action === 'task.assign' ? 'PUT' : 'POST'; const reply = await this.network.request(route(input.command), method, expected, body, input.key, token, signal); if (reply.status === 200) return taskReceipt(reply.value, input, false); if ([401,403,409,422,503].includes(reply.status)) { const correlationId = failure(reply.value); const precisionRequired = reply.status === 422 && input.command.action === 'task.create' && (reply.value as {code: unknown}).code === 'points_precision_two_required'; + const assigneesUnavailable = reply.status === 403 && input.command.action === 'task.assign' + && (reply.value as {code: unknown}).code === 'task_assignee_denied'; return Object.freeze({kind: 'rejected' as const, - reason: precisionRequired ? 'points_precision_two_required' as const : reason(reply.status), correlationId}); + reason: precisionRequired ? 'points_precision_two_required' as const + : assigneesUnavailable ? 'assignees_unavailable' as const : reason(reply.status), correlationId}); } } catch {/* An unbound or missing reply cannot establish absence of the committed effect. */} return Object.freeze({kind: 'uncertain' as const}); diff --git a/frontend/src/adapters/task-values.ts b/frontend/src/adapters/task-values.ts index fa105b61..13d740cb 100644 --- a/frontend/src/adapters/task-values.ts +++ b/frontend/src/adapters/task-values.ts @@ -156,9 +156,13 @@ export function taskReceipt(value: unknown, request: TaskRequest | TaskOriginal, const result = fields(item.result, ['definition_id', 'definition_revision', 'occurrence_id', 'revision', 'state', 'assignee_ids', 'state_reason', 'prerequisite_ids', 'required_subtask_ids', ...pointFields], ['cycle', 'consumer_delivery', 'materials', 'compensates_cycle_id', 'dependency_review_required']); const occurrenceId = identifier(result.occurrence_id), revision = responseRevision(result.revision), state = choice(result.state, TASK_STATES); - identifier(result.definition_id); responseRevision(result.definition_revision); ids(result.assignee_ids); ids(result.prerequisite_ids, 64); ids(result.required_subtask_ids, 64); + identifier(result.definition_id); responseRevision(result.definition_revision); + const assigneeIds = ids(result.assignee_ids); + ids(result.prerequisite_ids, 64); ids(result.required_subtask_ids, 64); check(revision === (command.action === 'task.create' ? '1' : nextRevision(command.payload.expected_revision))); 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())); 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 @@ -170,6 +174,7 @@ export function taskReceipt(value: unknown, request: TaskRequest | TaskOriginal, else check(result.compensates_cycle_id === command.payload.cycle_id && result.dependency_review_required === true); } return Object.freeze({kind: 'receipt', stage, action: command.action, operationId, occurrenceId, revision, state, cycle: savedCycle, archivedBy, + ...command.action === 'task.assign' ? {assigneeIds} : {}, ...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 cb474e9a..25a66f88 100644 --- a/frontend/src/application/task-controller.ts +++ b/frontend/src/application/task-controller.ts @@ -164,6 +164,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') + await this.facts(generation, command.occurrenceId); }); } private async receiptFacts(command: TaskCommand, occurrence: string | null, prior: State, generation: number): Promise { @@ -197,6 +199,12 @@ export class TaskController { const work = this.state.detail; return work === null ? Promise.resolve() : this.execute({action: 'task.claim', occurrenceId: work.occurrenceId, payload: {expected_revision: work.revision}}); } + assign(occurrenceId: string, revision: Revision, assigneeIds: readonly 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.assign', occurrenceId, payload: {expected_revision: revision, assignee_ids: assigneeIds}}); + } 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/application/task-ports.ts b/frontend/src/application/task-ports.ts index 5ca7635f..b90bc9e5 100644 --- a/frontend/src/application/task-ports.ts +++ b/frontend/src/application/task-ports.ts @@ -5,7 +5,7 @@ import type {CommandResult, EntryRead} from './ports'; export interface TaskRequest {readonly key: string; readonly command: TaskCommand;} export interface TaskOriginal extends TaskRequest {readonly operationId: string | null;} export type TaskCommandResult = TaskReceipt | Exclude - | Readonly<{kind: 'rejected'; reason: 'points_precision_two_required'; correlationId: string}>; + | Readonly<{kind: 'rejected'; reason: 'points_precision_two_required' | 'assignees_unavailable'; correlationId: string}>; export interface TaskServer { access(expected: JournalContext): EntryRead; list(expected: JournalContext, cursor: string | null): EntryRead; diff --git a/frontend/src/composition/entry-page.ts b/frontend/src/composition/entry-page.ts index f4ad40e9..597dfcb4 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 {taskBasePointAmount, taskQuantity, taskScheduleDraft, TASK_PRIORITIES} from '../domain/tasks'; +import {taskAssignees, taskBasePointAmount, 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,8 +134,12 @@ 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']); + const item = fields(value, ['type'], ['title', 'description', 'priority', 'schedule', 'occurrenceId', 'materialUsages', 'decision', 'reason', 'key', 'categoryId', 'label', 'revision', 'reviewed', 'basePointsMinor', 'assigneeIds']); 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 === 'create') { fields(value, ['type', 'title', 'description', 'priority'], ['schedule', 'categoryId', 'basePointsMinor']); check(typeof item.title === 'string' && typeof item.description === 'string' && typeof item.priority === 'string' @@ -706,6 +710,7 @@ export function mountEntry(page: EntryPage): PageMount { case 'renameCategory': await active.taskWork(controller => controller.renameCategory(intent.categoryId, intent.revision, intent.label)); break; 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 '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 6a6ff33b..f2a1b5fd 100644 --- a/frontend/src/domain/tasks.ts +++ b/frontend/src/domain/tasks.ts @@ -36,6 +36,12 @@ export function taskBasePointAmount(value: unknown): number { return value; } export interface TaskMaterialUsage {readonly line_id: string; readonly quantity: string;} +export function taskAssignees(value: unknown): readonly string[] { + requireValue(Array.isArray(value) && value.length <= 32); + const ids = Array.from(value, taskIdentifier); + requireValue(new Set(ids).size === ids.length); + return Object.freeze(ids); +} 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_PRIORITIES = ['low', 'normal', 'high', 'urgent'] as const; @@ -70,6 +76,7 @@ export type TaskCommand = CategoryCommand | Readonly<{action: 'task.create'; payload: Readonly<{expected_revision: 0; title: string; description: string; priority: TaskPriority; 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.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[]}>}> @@ -159,6 +166,11 @@ export function taskCommand(value: unknown): TaskCommand | undefined { }})}); } const occurrenceId = taskIdentifier(item.occurrenceId); + if (action === 'task.assign') { + const body = fields(item.payload, ['expected_revision', 'assignee_ids']); + return Object.freeze({action, occurrenceId, payload: Object.freeze({expected_revision: revisionValue(body.expected_revision), + assignee_ids: taskAssignees(body.assignee_ids)})}); + } 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)})}); @@ -223,4 +235,5 @@ export interface TaskReceipt { readonly state: TaskState | 'active' | 'archived'; readonly cycle: TaskCycleSummary | null; readonly archivedBy: string | null; readonly basePointsMinor?: number; + readonly assigneeIds?: readonly string[]; } diff --git a/frontend/src/presentation/domus-app.ts b/frontend/src/presentation/domus-app.ts index 086e76cb..8e4d532f 100644 --- a/frontend/src/presentation/domus-app.ts +++ b/frontend/src/presentation/domus-app.ts @@ -257,7 +257,7 @@ export class DomusApp extends LitElement {
- diff --git a/frontend/src/presentation/domus-tasks.ts b/frontend/src/presentation/domus-tasks.ts index a45a58f0..fd85079c 100644 --- a/frontend/src/presentation/domus-tasks.ts +++ b/frontend/src/presentation/domus-tasks.ts @@ -4,9 +4,13 @@ import type {PropertyValues} from 'lit'; import {registerField} from '@vypdev/ha-ui/field'; import type {FieldValueEvent} from '@vypdev/ha-ui/field'; 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 type {AdministrationView} from '../application/administration-controller'; import type {TaskView} from '../application/task-controller'; import type {TaskRecord} from '../application/task-ports'; -import {categoryLabel, hasTaskText, taskQuantity, taskScheduleDraft, TASK_PRIORITIES, TASK_TEXT_LIMITS} from '../domain/tasks'; +import {categoryLabel, hasTaskText, taskAssignees, taskQuantity, taskScheduleDraft, 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 {language} from './messages'; @@ -22,6 +26,7 @@ import './domus-allocation-preview'; 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: 'create'; title: string; description: string; priority: TaskPriority; categoryId?: string; schedule?: TaskScheduleDraft; basePointsMinor?: number}> | Readonly<{type: 'createCategory'; label: string}> @@ -33,6 +38,7 @@ export type TaskIntent = Readonly<{type: 'refresh' | 'more' | 'claim'}> | Readonly<{type: 'recover' | 'dismiss'; key: string}>; 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[]}>; function validCategoryLabel(value: string): boolean { try {categoryLabel(value); return true;} catch {return false;} } @@ -46,7 +52,8 @@ 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 = {allocation: {attribute: false}, participantNames: {attribute: false}, view: {attribute: false}, retired: {attribute: false}, language: {attribute: false}, titleDraft: {state: true}, descriptionDraft: {state: true}, + static properties = {administration: {attribute: false}, assignmentDraft: {state: true}, assignmentError: {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}, @@ -61,8 +68,15 @@ export class DomusTasks extends LitElement { #task-base-points {--vyp-ha-surface:var(--canvas);--vyp-ha-border:var(--line); --vyp-ha-text:var(--text);--vyp-ha-text-secondary:var(--muted); --vyp-ha-primary:var(--accent);--vyp-ha-danger:var(--warning)} + .assignment {margin:24px 0}.assignment h4 {margin:0 0 8px}.assignment fieldset {margin-top:16px} + .assignment-choices {display:grid;gap:4px;max-height:320px;overflow:auto;padding:12px} + .assignment-choices vyp-ha-checkbox {min-height:44px;display:grid;align-content:center; + --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}}`]; declare allocation: AllocationView | null; + declare administration: Pick | null; declare participantNames: readonly ParticipantName[]; declare view: TaskView | null; declare retired: boolean; @@ -88,12 +102,17 @@ export class DomusTasks extends LitElement { private draftScope: string | null = null; private detailKey: string | null = null; private submittedDraft: string | null = null; - private lastForm: 'create' | 'review' | 'category' = 'create'; + private declare assignmentDraft: AssignmentDraft | null; + private declare assignmentError: boolean; + private submittedAssignment: AssignmentDraft | null = null; + private assignmentFocus: string | null = null; + private lastForm: 'create' | 'review' | 'category' | 'assignment' = '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.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 @@ -106,6 +125,7 @@ export class DomusTasks extends LitElement { this.basePointsDraft, this.scheduleKind, this.scheduleInput]); } private reset(): void { + 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 = ''; this.basePointsDraft = ''; this.basePointsError = null; @@ -120,9 +140,21 @@ 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; + 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 (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.assign' + && outcome.occurrenceId === this.assignmentDraft?.occurrenceId && this.assignmentDraft === this.submittedAssignment + && outcome.assigneeIds !== undefined + && JSON.stringify([...outcome.assigneeIds].sort()) === JSON.stringify([...this.assignmentDraft.assigneeIds].sort()) + && BigInt(outcome.revision) === BigInt(this.assignmentDraft.revision) + 1n && outcome !== changed.get('view')?.outcome) { + this.assignmentDraft = null; this.submittedAssignment = null; this.assignmentError = false; this.assignmentFocus = '#assignment-edit'; + } if (outcome?.kind === 'rejected' && outcome.reason === 'points_precision_two_required' && outcome !== changed.get('view')?.outcome) this.basePointsError = 'notice_points_precision_two_required'; if (outcome?.kind === 'receipt' && outcome.stage === 'committed' && outcome.action === this.submittedCategory?.action @@ -140,7 +172,13 @@ export class DomusTasks extends LitElement { 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' : '#task-reason')?.focus(); + this.shadowRoot?.querySelector(this.lastForm === 'create' ? '#task-title' : this.lastForm === 'category' ? '#task-category-label' + : this.lastForm === 'assignment' ? '#assignment-editor' : '#task-reason')?.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 (changed.has('view') && this.view?.notice === 'category_unavailable') this.renderRoot.querySelector('#task-category')?.focus(); const outcome = this.view?.outcome; @@ -151,7 +189,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', 'complete', 'verify', 'reopen'].includes(detail.type) && this.blocked) return; + if (['create', 'createCategory', 'renameCategory', 'archiveCategory', 'claim', 'assign', '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 { @@ -333,6 +371,78 @@ export class DomusTasks extends LitElement { } this.quantityError = null; this.intent({type: 'complete', materialUsages, ...reviewed === undefined ? {} : {reviewed}}); } + 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'; + if (!current.access?.permissions.includes('members.read') || current.errors.roster === 'forbidden') return 'assignmentDenied'; + if (current.errors.roster !== undefined || current.roster === null) return 'assignmentUnavailable'; + return 'ready'; + } + private assignmentName(id: string): string { + 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 { + if (this.assignmentDraft === null) return false; + const outcome = this.view!.outcome; + return this.assignmentDraft.revision !== work.revision + || this.submittedAssignment !== null && outcome?.kind === 'rejected' && outcome.reason === 'conflict'; + } + private chooseAssignee(id: string, event: CheckboxChangeEvent): void { + if (this.blocked || this.assignmentDraft === null || this.assignmentDiscovery !== 'ready') return; + try { + const {checked} = checkboxChangeDetail(event.detail); + const ids = this.assignmentDraft.assigneeIds.filter(selected => selected !== id); + this.assignmentDraft = Object.freeze({...this.assignmentDraft, assigneeIds: taskAssignees(checked ? [...ids, id] : ids)}); + this.assignmentError = false; + } catch {event.preventDefault(); this.assignmentError = true;} + } + private assignment(work: TaskDetail) { + if (!work.allowedActions.includes('assign')) return nothing; + const discovery = this.assignmentDiscovery, draft = this.assignmentDraft; + const choices = discovery === 'ready' ? this.administration!.roster!.members.filter(row => row.member.status === 'active') : []; + const stale = draft?.assigneeIds.filter(id => !choices.some(row => row.member.memberId === id)) ?? []; + const needsReview = this.assignmentNeedsReview(work); + const requiresAssignee = work.state === 'in_progress' && draft?.assigneeIds.length === 0; + const currentUnavailable = this.view!.notice === 'unavailable' || this.view!.notice === 'invalid_response'; + const invalid = discovery !== 'ready' || stale.length > 0 || requiresAssignee || currentUnavailable; + return html`

${this.text('assignmentTitle')}

+ ${discovery === 'ready' ? html`

${work.assigneeIds.length ? work.assigneeIds.map(id => this.assignmentName(id)).join(', ') : this.text('assignmentEmpty')}

` + : html`

${this.text(discovery)}

`} + ${draft === null ? html`` : html`
{ + event.preventDefault(); + if (this.blocked || invalid || needsReview) return; + this.lastForm = 'assignment'; this.submittedAssignment = draft; + this.intent({type: 'assign', occurrenceId: draft.occurrenceId, revision: draft.revision, assigneeIds: draft.assigneeIds}); + }}>
${this.text('assignmentChoose')} +

${this.text('assignmentHelp')} (${draft.assigneeIds.length}/32)

+ ${discovery !== 'ready' ? nothing : choices.length === 0 ? html`

${this.text('assignmentNoMembers')}

` + : html`
${choices.map(({member}) => html`= 32 && !draft.assigneeIds.includes(member.memberId)} + @ha-check-request=${(event: CheckboxChangeEvent) => this.chooseAssignee(member.memberId, event)}>`)}
`} + ${discovery === 'ready' && stale.length ? html` +
    ${stale.map(id => html`
  • ${this.assignmentName(id)}
  • `)}
` : nothing} + ${requiresAssignee ? html`` : nothing} + ${this.assignmentError ? html`` : nothing} + ${needsReview ? html`

${this.text('assignmentChanged')}

` : nothing} +
+
+
+
`}
`; + } private workDetail() { const work = this.view!.detail!; const allocation = this.allocationFor(work); @@ -346,6 +456,7 @@ 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.assignment(work)} ${work.allowedActions.includes('claim') ? html`
` : nothing} ${work.completionPoints === 'manager_required' ? html`

${this.text('manualPointsManager')}

` : nothing} ${work.allowedActions.includes('complete') ? html`
{event.preventDefault(); this.complete();}}> @@ -381,9 +492,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; - const body = kind === 'saved' && result.kind === 'receipt' && result.state === 'active' ? 'scheduleSaved' : `${kind}Body` as const; + 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'; - return html`

${this.text(kind)}

+ return html`

${this.text(assignmentSaved ? 'assignmentSaved' : kind)}

${precisionRequired ? nothing : html`

${this.text(body)}

`} ${result.kind === 'rejected' && !precisionRequired ? html`

${this.text(`notice_${result.reason}`)}

` : nothing} ${result.kind === 'receipt' && result.basePointsMinor !== undefined ? html`
${this.text('basePoints')}
@@ -417,5 +529,6 @@ export class DomusTasks extends LitElement { } } registerField(); +registerCheckbox(); 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 70212788..36d865e3 100644 --- a/frontend/src/presentation/task-messages.ts +++ b/frontend/src/presentation/task-messages.ts @@ -25,6 +25,19 @@ const english = Object.freeze({ list: 'Household tasks', empty: 'No tasks on this page', more: 'Next page', details: 'Task details', manualPointsManager: 'Ask a points administrator to record this work and enter the points for each participant.', claim: 'Claim task', complete: 'Mark done now', completionHelp: 'Record this task as performed by you now.', + assignmentTitle: 'Planned assignees', assignmentEmpty: 'Unassigned', assignmentEdit: 'Change assignment', + assignmentChoose: 'Assign household members', assignmentHelp: 'Choose up to 32 active household members.', + assignmentSave: 'Save assignment', assignmentCancel: 'Cancel', assignmentClear: 'Clear selection', + assignmentRefresh: 'Refresh assignment and members', assignmentLoading: 'Loading household members', + assignmentNoMembers: 'No active household members are available.', + assignmentUnavailable: 'Household members could not be loaded.', + assignmentDenied: 'Your current access does not allow viewing household members.', + assignmentUnnamed: 'Household member', assignmentStale: 'Remove unavailable members or refresh the choices.', + assignmentRemove: 'Remove unavailable member', assignmentRequired: 'An in-progress task needs at least one assignee.', + assignmentInvalid: 'Choose up to 32 different household members.', + assignmentChanged: 'The current assignment changed. Your selection is retained. Review the current assignment before saving.', + assignmentReview: 'Review current assignment', assignmentSaved: 'Assignment saved', + assignmentSavedBody: 'The planned assignees are recorded.', action_assign: 'Assign task', 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.', @@ -53,8 +66,9 @@ const english = Object.freeze({ notice_authentication_required: 'Verify your session again to view tasks.', notice_forbidden: 'Your current permissions do not allow this task action.', notice_unavailable: 'Tasks could not be loaded. Your saved work is retained. Refresh when the service is reachable.', notice_invalid_response: 'The response could not be verified. Refresh to check the current task.', - notice_invalid_input: 'Review the title, reason and quantities. Required fields must not be empty.', + notice_invalid_input: 'Review the title, reason, quantities and selected members. Complete all required fields.', notice_points_precision_two_required: 'Use whole base points or change the household Points allocation to two decimal places.', + notice_assignees_unavailable: 'Some selected members are unavailable. Refresh the choices and remove unavailable members before saving.', notice_conflict: 'This task changed. Review its current details before submitting again.', notice_read_only: 'Changes are blocked during read-only access.', notice_journal_unavailable: 'Browser recovery storage could not be confirmed. Task changes are blocked. Refresh in a supported browser.', notice_context_changed: 'Your account or household changed. Review the current tasks before making a change.', @@ -90,6 +104,19 @@ const spanish: Readonly> = Object.freeze({ list: 'Tareas del hogar', empty: 'No hay tareas en esta página', more: 'Página siguiente', details: 'Detalle de la tarea', manualPointsManager: 'Pide a un administrador de puntos que registre el trabajo e introduzca los puntos de cada participante.', claim: 'Quedarme esta tarea', complete: 'Marcar como hecha ahora', completionHelp: 'Registrar que tú has realizado esta tarea ahora.', + assignmentTitle: 'Personas asignadas', assignmentEmpty: 'Sin asignar', assignmentEdit: 'Cambiar asignación', + assignmentChoose: 'Asignar miembros del hogar', assignmentHelp: 'Elige hasta 32 miembros activos del hogar.', + assignmentSave: 'Guardar asignación', assignmentCancel: 'Cancelar', assignmentClear: 'Borrar selección', + assignmentRefresh: 'Actualizar asignación y miembros', assignmentLoading: 'Cargando miembros del hogar', + assignmentNoMembers: 'No hay miembros activos disponibles en el hogar.', + assignmentUnavailable: 'No se han podido cargar los miembros del hogar.', + assignmentDenied: 'Tu acceso actual no permite consultar los miembros del hogar.', + assignmentUnnamed: 'Miembro del hogar', assignmentStale: 'Quita los miembros que ya no están disponibles o actualiza la lista.', + assignmentRemove: 'Quitar miembro no disponible', assignmentRequired: 'Una tarea en curso necesita al menos una persona asignada.', + assignmentInvalid: 'Elige hasta 32 miembros distintos del hogar.', + assignmentChanged: 'La asignación actual ha cambiado. Se conserva tu selección. Revisa la asignación actual antes de guardar.', + assignmentReview: 'Revisar asignación actual', assignmentSaved: 'Asignación guardada', + assignmentSavedBody: 'Las personas asignadas han quedado registradas.', action_assign: 'Asignar tarea', 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.', @@ -118,8 +145,9 @@ const spanish: Readonly> = Object.freeze({ notice_authentication_required: 'Vuelve a verificar tu sesión para ver las tareas.', notice_forbidden: 'Tus permisos actuales no permiten esta acción sobre la tarea.', notice_unavailable: 'No se han podido cargar las tareas. Tu trabajo guardado se conserva. Actualiza cuando el servicio esté disponible.', notice_invalid_response: 'No se ha podido verificar la respuesta. Actualiza para comprobar la tarea actual.', - notice_invalid_input: 'Revisa el título, el motivo y las cantidades. Los campos obligatorios no pueden estar vacíos.', + notice_invalid_input: 'Revisa el título, el motivo, las cantidades y los miembros seleccionados. Completa los campos obligatorios.', notice_points_precision_two_required: 'Usa puntos base enteros o cambia el reparto de puntos del hogar a dos decimales.', + notice_assignees_unavailable: 'Algunos miembros seleccionados ya no están disponibles. Actualiza la lista y quítalos de la selección antes de guardar.', notice_conflict: 'Esta tarea ha cambiado. Revisa su estado actual antes de volver a enviar el cambio.', notice_read_only: 'Los cambios están bloqueados durante el acceso de solo lectura.', notice_journal_unavailable: 'No se ha podido confirmar el almacenamiento de recuperación del navegador. Los cambios están bloqueados. Actualiza en un navegador compatible.', notice_context_changed: 'Tu cuenta o tu hogar han cambiado. Revisa las tareas actuales antes de modificarlas.', diff --git a/frontend/tests/e2e/tasks.spec.ts b/frontend/tests/e2e/tasks.spec.ts index ed032687..4e2b452e 100644 --- a/frontend/tests/e2e/tasks.spec.ts +++ b/frontend/tests/e2e/tasks.spec.ts @@ -485,3 +485,156 @@ 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(`assignment review, recovery and restart in ${mode} ${locale}`, async ({browser, request}, info) => { + expect((await request.post(origin(mode) + '/__fixture__/reset')).ok()).toBe(true); + const owner = await browser.newContext({viewport: {width: locale === 'es' ? 390 : 1280, height: 844}, hasTouch: locale === 'es'}); + const peer = await browser.newContext(); + const page = await owner.newPage(), participant = await peer.newPage(); + const subject = mode === 'native' ? 'c' : 'b'; + const t = (english: string, spanish: string) => locale === 'en' ? english : spanish; + 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('combobox', {name: /^(Language|Idioma)$/u}).selectOption(locale); + await page.getByRole('link', {name: t('Tasks', 'Tareas'), exact: true}).click(); + }; + try { + const tasks = await open(page, owner, mode); + await page.getByRole('link', {name: 'Household', exact: true}).click(); + const administration = page.locator('domus-administration'); + await administration.getByRole('button', {name: 'Edit access rules', exact: true}).click(); + await administration.getByLabel('HA administrator mapping', {exact: true}).selectOption('selected_ha_user'); + await administration.getByLabel('Target Home Assistant account', {exact: true}).selectOption('a'.repeat(32)); + await saveAdministration(administration); + if (mode === 'native') await peer.addCookies([{name: 'ingress_session', value: 'e'.repeat(128), domain: '127.0.0.1', path: '/', httpOnly: true, sameSite: 'Strict'}]); + else await request.post(origin(mode) + '/__fixture__/identity', {data: {subject: subject.repeat(32)}}); + await participant.goto(base(mode) + '/'); + if (mode === 'standalone') { + await participant.getByRole('button', {name: 'Sign in with Home Assistant', exact: true}).click(); + await participant.getByRole('link', {name: 'Continue as fixture user', exact: true}).click(); + } + await participant.getByRole('button', {name: 'Request membership', exact: true}).click(); + await expect(participant.getByRole('heading', {name: 'Membership pending', exact: true})).toBeVisible(); + if (mode === 'standalone') await request.post(origin(mode) + '/__fixture__/identity', {data: {subject: 'a'.repeat(32)}}); + await administration.getByRole('button', {name: 'Refresh administration', exact: true}).click(); + await administration.getByRole('button', {name: 'Manage participant: Fictional account ' + subject, exact: true}).click(); + await administration.getByLabel('Membership status', {exact: true}).selectOption('active'); + await administration.getByRole('button', {name: 'Review changes', exact: true}).click(); + await administration.getByRole('checkbox', {name: 'Approve household access', exact: true}).check(); + await administration.getByRole('button', {name: 'Review changes', exact: true}).click(); + await administration.getByRole('button', {name: 'Save changes', exact: true}).click(); + await expect(administration.getByRole('heading', {name: 'Original request processed', exact: true})).toBeVisible(); + await administration.getByRole('button', {name: 'Close editor', exact: true}).click(); + await participant.getByRole('button', {name: 'Refresh status', exact: true}).click(); + await participant.getByRole('link', {name: 'Tasks', exact: true}).click(); + const ownerAccess = await (await page.request.get(base(mode) + '/api/v1/tasks/access')).json(); + const peerAccess = await (await participant.request.get(base(mode) + '/api/v1/tasks/access')).json(); + await page.getByRole('combobox', {name: 'Language', exact: true}).selectOption(locale); + await page.getByRole('link', {name: t('Tasks', 'Tareas'), exact: true}).click(); + const title = 'Assign & help'; + 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() === 'PUT' && item.url() === endpoint + '/assignment') + writes.push({key: item.headers()['idempotency-key'], body: item.postData()!, context: item.headers()['x-domus-context']}); + }); + const edit = tasks.getByRole('button', {name: t('Change assignment', 'Cambiar asignación'), exact: true}); + const save = tasks.getByRole('button', {name: t('Save assignment', 'Guardar asignación'), exact: true}); + const ownChoice = tasks.getByRole('checkbox', {name: 'Fictional account a', exact: true}); + const peerChoice = tasks.getByRole('checkbox', {name: 'Fictional account ' + subject, exact: true}); + const toggle = async (target: Locator) => { + if (locale === 'es') await target.tap(); + else {await target.focus(); await target.press('Space');} + }; + await activate(edit); await toggle(ownChoice); await toggle(peerChoice); + await activate(tasks.getByRole('button', {name: t('Cancel', 'Cancelar'), exact: true})); + expect(writes).toEqual([]); + await activate(edit); await expect(ownChoice).not.toBeChecked(); + await toggle(ownChoice); await toggle(peerChoice); await activate(save); + await expect(tasks.getByRole('heading', {name: t('Assignment saved', 'Asignación guardada'), exact: true})).toBeVisible(); + expect(JSON.parse(writes[0].body)).toEqual({expected_revision: 1, assignee_ids: [ownerAccess.member_id, peerAccess.member_id]}); + expect((await (await page.request.get(endpoint)).json()).work.assignee_ids.sort()).toEqual([ownerAccess.member_id, peerAccess.member_id].sort()); + expect((await request.post(origin(mode) + '/__fixture__/operator', {data: {action: 'snapshot'}})).ok()).toBe(true); + + await activate(edit); await toggle(ownChoice); + const concurrent = await owner.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: 'Change assignment', exact: true}).click(); + await competing.getByRole('checkbox', {name: 'Fictional account ' + subject, exact: true}).uncheck(); + await competing.getByRole('button', {name: 'Save assignment', exact: true}).click(); + await expect(competing.getByRole('heading', {name: 'Assignment saved', exact: true})).toBeVisible(); + await concurrent.close(); + await activate(save); + const review = tasks.getByRole('button', {name: t('Review current assignment', 'Revisar asignación actual'), exact: true}); + await expect(review).toBeVisible(); await expect(save).toBeDisabled(); + await expect(ownChoice).not.toBeChecked(); await expect(peerChoice).toBeChecked(); + expect(writes).toHaveLength(1); + await activate(review); await activate(save); + await expect(edit).toBeVisible(); expect(JSON.parse(writes[1].body).expected_revision).toBe(3); + + await activate(edit); await activate(tasks.getByRole('button', {name: t('Clear selection', 'Borrar selección'), exact: true})); + await page.route(endpoint + '/assignment', 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(save).toBeDisabled(); expect(writes).toHaveLength(3); + const released = writes[2]; expect(JSON.parse(released.body)).toEqual({expected_revision: 4, assignee_ids: []}); + await page.unroute(endpoint + '/assignment'); await page.reload(); + 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(tasks.getByRole('heading', {name: t('Assignment saved', 'Asignación guardada'), exact: true})).toBeVisible(); + expect(writes).toHaveLength(3); + const original = await (await page.request.get(base(mode) + '/api/v1/tasks/requests/task.assign/' + released.key)).json(); + expect(original).toMatchObject({state: 'committed', result: {assignee_ids: [], revision: 5, state: 'available'}}); + await expect(tasks.locator('.assignment')).toContainText(t('Unassigned', 'Sin asignar')); + await activate(edit); await toggle(peerChoice); await activate(save); await expect(edit).toBeVisible(); + const retained = writes[3]; + const operation = await (await page.request.get(base(mode) + '/api/v1/tasks/requests/task.assign/' + retained.key)).json(); + expect(operation.result).toMatchObject({assignee_ids: [peerAccess.member_id], revision: 6}); + await page.screenshot({path: info.outputPath('assignment-' + mode + '-' + locale + '.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})); + expect((await (await page.request.get(endpoint)).json()).work).toMatchObject({revision: 6, assignee_ids: [peerAccess.member_id]}); + expect(await (await page.request.get(base(mode) + '/api/v1/tasks/requests/task.assign/' + retained.key)).json()) + .toMatchObject({operation_id: operation.operation_id, result: operation.result}); + 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(); + const completed = await (await page.request.get(endpoint)).json(); + expect(completed.cycle.performers.map((item: {member_id: string}) => item.member_id)).toEqual([ownerAccess.member_id]); + expect(completed.work.assignee_ids).toEqual([peerAccess.member_id]); + + expect((await request.post(origin(mode) + '/__fixture__/operator', {data: {action: 'restore'}})).ok()).toBe(true); + await page.reload(); await signIn(); + 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 replay = await page.request.put(endpoint + '/assignment', {data: retained.body, headers: {'Content-Type': 'application/json', Origin: origin(mode), + 'X-CSRF-Token': csrf.csrf_token, 'Idempotency-Key': retained.key, 'X-Domus-Context': retained.context}}); + expect(replay.status()).toBe(200); + expect(await replay.json()).toMatchObject({state: 'historical', operation_id: operation.operation_id, result: operation.result}); + expect((await (await page.request.get(endpoint)).json()).work).toMatchObject({revision: 2, state: 'assigned'}); + expect((await (await page.request.get(endpoint)).json()).work.assignee_ids.sort()).toEqual([ownerAccess.member_id, peerAccess.member_id].sort()); + expect((await (await request.get(origin(mode) + '/__fixture__/stats')).json()).counts).toEqual(before.counts); + await info.attach('assignment-operation-evidence', {body: JSON.stringify({mode, locale, writes, operationId: operation.operation_id, + originalRelease: original.operation_id, restartRevision: 6, restoredRevision: 2, performerId: ownerAccess.member_id}), contentType: 'application/json'}); + } finally {await peer.close(); await owner.close();} + }); + } +} diff --git a/frontend/tests/page.test.ts b/frontend/tests/page.test.ts index 403a214a..9fd97abb 100644 --- a/frontend/tests/page.test.ts +++ b/frontend/tests/page.test.ts @@ -446,6 +446,9 @@ test('household-browser-C18: a signed-out language choice has no identity or mut test.each([null, {}, [], {type: 'future'}, {type: 'refresh', actor: 'forged'}, {type: 'create', title: 'Task', description: '', priority: 'normal', householdId: 'forged'}, {type: 'create', title: 'Task', description: '', priority: 'normal', basePointsMinor: '225'}, + {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: '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'}, @@ -454,6 +457,8 @@ test.each([null, {}, [], {type: 'future'}, {type: 'refresh', actor: 'forged'}, }); test('closed task events preserve semantic user inputs and exact material quantities', () => { 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:'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}, @@ -466,6 +471,7 @@ test('closed task events preserve semantic user inputs and exact material quanti test('the mounted task surface routes only owned semantic intents to its application controller', async () => { 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), createCategory: vi.spyOn(TaskController.prototype, 'createCategory').mockResolvedValue(undefined), renameCategory: vi.spyOn(TaskController.prototype, 'renameCategory').mockResolvedValue(undefined), archiveCategory: vi.spyOn(TaskController.prototype, 'archiveCategory').mockResolvedValue(undefined), @@ -480,6 +486,8 @@ test('the mounted task surface routes only owned semantic intents to its applica send({type: 'create', title: 'Forged actor', description: '', priority: 'normal', actor: 'other'}); await Promise.resolve(); expect(spies.create).not.toHaveBeenCalled(); const review = {occurrenceId:'work-1',revision:'1',performerIds:['identity-1','other'],fingerprint:'c'.repeat(64)}; const cases: readonly [unknown, keyof typeof spies, readonly unknown[]][] = [ + [{type: 'assign', occurrenceId: 'work-1', revision: '9007199254740993', assigneeIds: ['identity-1', 'other']}, + 'assign', ['work-1', '9007199254740993', ['identity-1', 'other']]], [{type: 'create', title: 'Clean', description: 'Wipe', priority: 'high'}, 'create', ['Clean', 'Wipe', 'high', undefined, undefined, undefined]], [{type: 'create', title: 'Clean', description: 'Wipe', priority: 'high', schedule: {kind: 'fixed', start: {kind: 'date', local: '2027-01-02'}, rrule: 'FREQ=WEEKLY'}}, diff --git a/frontend/tests/task-component.test.ts b/frontend/tests/task-component.test.ts index f6511d12..eab006fe 100644 --- a/frontend/tests/task-component.test.ts +++ b/frontend/tests/task-component.test.ts @@ -1,8 +1,11 @@ import {afterEach, expect, test} from 'vitest'; import type {HaTextField} from '@vypdev/ha-ui/field'; +import type {HaCheckbox} from '@vypdev/ha-ui/checkbox'; +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 {revisionValue} from '../src/domain/administration'; import type {DomusTasks, TaskIntent} from '../src/presentation/domus-tasks'; import '../src/presentation/domus-tasks'; @@ -27,6 +30,272 @@ async function mount(value: TaskView | null = view(), locale: 'en' | 'es' = 'en' field.value = value; field.dispatchEvent(new InputEvent('input', {bubbles: true})); await element.updateComplete;}; return {element, root, intents, button, input, text: () => root.textContent!}; } + +function assignmentRoster(): Pick { + const member = {memberId: 'private-member-id', haUserId: context.subject, role: 'adult' as const, + status: 'active' as const, revision, exceptions: []}; + return {phase: 'ready', access: {state: 'active', setupAllowed: false, enrollmentAllowed: false, + member, effectiveRole: 'adult', policyRevision: revision, permissions: ['members.read']}, errors: {}, + roster: {directoryState: 'available', members: ['private-member-id', 'peer'].map((id, index) => ({ + member: {...member, memberId: id}, presentation: {memberId: id, alias: index === 0 ? 'Owner ' : null, revision}, + metadata: {state: 'available', name: index === 0 ? 'Provider owner' : 'Helper & friend', avatarState: 'unavailable'}}))}}; +} +async function assignmentFixture(locale: 'en' | 'es' = 'en', patch: Partial = {}) { + const detail = {...work, allowedActions: ['assign'], ...patch}; + const f = await mount(view({detail}), locale); + f.element.administration = assignmentRoster(); await f.element.updateComplete; + const select = async (index: number, checked: boolean) => { + const choice = f.root.querySelectorAll('vyp-ha-checkbox')[index]; + await choice.updateComplete; + choice.dispatchEvent(new CustomEvent('ha-check-request', {detail: {checked, reason: 'change'}, bubbles: true, composed: true, cancelable: true})); + await f.element.updateComplete; + }; + return {...f, detail, select}; +} + +test.each([ + ['en', 'Change assignment', 'Save assignment', 'Cancel', 'Unassigned'], + ['es', 'Cambiar asignación', 'Guardar asignación', 'Cancelar', 'Sin asignar'], +] as const)('%s assignment uses named ha-ui choices and explicit save or cancel', async (locale, edit, save, cancel, unassigned) => { + const f = await assignmentFixture(locale); + expect(f.text()).toContain(unassigned); + f.button(edit).click(); await f.element.updateComplete; + const choices = f.root.querySelectorAll('vyp-ha-checkbox'); + await choices[0].updateComplete; + expect(choices[0].state.label).toBe('Owner '); + expect(choices[1].state.label).toBe('Helper & friend'); + expect(f.root.querySelector('img,script')).toBeNull(); + expect(f.root.activeElement).toBe(choices[0]); + await f.select(0, true); await f.select(1, true); + f.button(save).click(); + expect(f.intents).toEqual([{type: 'assign', occurrenceId: 'work-1', revision, assigneeIds: ['private-member-id', 'peer']}]); + 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.querySelectorAll('vyp-ha-checkbox')].map(choice => choice.checked)).toEqual([true, true]); + f.button(cancel).click(); await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')).toBeNull(); + expect(f.root.activeElement).toBe(f.button(edit)); + f.button(edit).click(); await f.element.updateComplete; + expect([...f.root.querySelectorAll('vyp-ha-checkbox')].map(choice => choice.checked)).toEqual([false, false]); +}); + +test('assignment conflict retains the draft and requires review of the current revision before another save', async () => { + const f = await assignmentFixture(); f.button('Change assignment').click(); await f.element.updateComplete; + await f.select(0, true); f.button('Save assignment').click(); + const changed = {...f.detail, revision: revisionValue('2'), assigneeIds: ['peer']}; + f.element.view = view({detail: changed, notice: 'conflict'}); await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')!.checked).toBe(true); + expect(f.button('Save assignment').disabled).toBe(true); + expect(f.root.activeElement).toBe(f.button('Review current assignment')); + f.button('Review current assignment').click(); await f.element.updateComplete; + expect(f.button('Save assignment').disabled).toBe(false); + f.button('Save assignment').click(); + expect(f.intents[1]).toEqual({type: 'assign', occurrenceId: 'work-1', revision: '2', assigneeIds: ['private-member-id']}); + f.element.view = view({detail: {...changed, revision: revisionValue('3'), assigneeIds: ['private-member-id']}, outcome: { + kind: 'receipt', action: 'task.assign', stage: 'committed', operationId: 'assignment-op', occurrenceId: 'work-1', + revision: revisionValue('3'), state: 'assigned', assigneeIds: ['private-member-id'], cycle: null, archivedBy: null}}); + await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')).toBeNull(); + expect(f.text()).toContain('Assignment saved'); +}); + +test('assignment release follows the current task state and stale members require correction', async () => { + const f = await assignmentFixture('en', {assigneeIds: ['peer']}); + f.button('Change assignment').click(); await f.element.updateComplete; + f.button('Clear selection').click(); await f.element.updateComplete; + f.button('Save assignment').click(); + expect(f.intents[0]).toMatchObject({type: 'assign', assigneeIds: []}); + f.element.view = view({detail: {...f.detail, state: 'in_progress'}}); await f.element.updateComplete; + expect(f.button('Save assignment').disabled).toBe(true); + expect(f.text()).toContain('An in-progress task needs at least one assignee.'); + await f.select(0, true); + const roster = assignmentRoster(); + f.element.administration = {...roster, roster: {...roster.roster!, members: roster.roster!.members.slice(1)}}; + await f.element.updateComplete; + expect(f.button('Save assignment').disabled).toBe(true); + expect(f.text()).toContain('Remove unavailable members or refresh the choices.'); + f.button('Remove unavailable member').click(); await f.element.updateComplete; + expect(f.root.querySelector('[data-stale-assignee]')).toBeNull(); +}); + +test.each(['loading', 'empty', 'unavailable', 'denied', 'permission', 'missing'] as const)( + 'assignment discovery %s has distinct feedback and preserves a recoverable selection', async state => { + const f = await assignmentFixture(); f.button('Change assignment').click(); await f.element.updateComplete; + await f.select(0, true); + const roster = assignmentRoster(); + f.element.administration = state === 'missing' ? null : {...roster, + ...state === 'loading' ? {phase: 'loading' as const, roster: null} : {}, + ...state === 'empty' ? {roster: {...roster.roster!, members: []}} : {}, + ...state === 'unavailable' ? {roster: null, errors: {roster: 'unavailable' as const}} : {}, + ...state === 'denied' ? {roster: null, errors: {roster: 'forbidden' as const}} : {}, + ...state === 'permission' ? {roster: null, access: {...roster.access!, permissions: []}} : {}}; + await f.element.updateComplete; + const expected = state === 'loading' || state === 'missing' ? 'Loading household members' + : state === 'empty' ? 'No active household members are available.' : state === 'unavailable' + ? 'Household members could not be loaded.' : 'Your current access does not allow viewing household members.'; + expect(f.text()).toContain(expected); + expect(f.button('Save assignment').disabled).toBe(true); + f.button('Refresh assignment and members').click(); + expect(f.intents).toEqual([{type: 'refresh'}]); + f.element.administration = roster; await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')!.checked).toBe(true); + }); + +test('assignment controls follow current actions and scoped retirement clears their draft', async () => { + const ordinary = await mount(view({detail: work})); + expect(ordinary.button('Change assignment')).toBeUndefined(); + const f = await assignmentFixture(); f.button('Change assignment').click(); await f.element.updateComplete; + await f.select(0, true); + f.element.view = view({detail: f.detail, scopeKey: 'different-household'}); await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')).toBeNull(); + f.button('Change assignment').click(); await f.element.updateComplete; + f.element.retired = true; await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')).toBeNull(); +}); + +test('assignment choices retain canonical IDs when provider names are unavailable and enforce the 32-member bound', async () => { + const f = await assignmentFixture(); const roster = assignmentRoster(), member = roster.roster!.members[0]; + f.element.administration = {...roster, roster: {directoryState: 'denied', members: Array.from({length: 33}, (_, index) => ({ + ...member, member: {...member.member, memberId: 'member-' + index}, + presentation: {...member.presentation, memberId: 'member-' + index, alias: null}, + metadata: {...member.metadata, state: 'denied', name: null}}))}}; + await f.element.updateComplete; + f.button('Change assignment').click(); await f.element.updateComplete; + for (let index = 0; index < 32; index++) await f.select(index, true); + const choices = f.root.querySelectorAll('vyp-ha-checkbox'); + expect(choices[0].state.label).toBe('Household member member-0'); + expect(choices[32].disabled).toBe(true); expect(choices[0].disabled).toBe(false); + await f.select(32, true); + expect(f.text()).toContain('Choose up to 32 different household members.'); + f.button('Save assignment').click(); + expect(f.intents[0]).toMatchObject({type: 'assign', assigneeIds: Array.from({length: 32}, (_, index) => 'member-' + index)}); + await f.select(0, false); await f.select(32, true); + expect(f.text()).not.toContain('Choose up to 32 different household members.'); + f.element.view = view({detail: f.detail, records: [{key: 'pending', command: {action: 'task.assign', occurrenceId: 'work-1', + payload: {expected_revision: revision, assignee_ids: ['member-1']}}, scope: {context, householdId: 'private-home-id', memberId: 'private-member-id'}, + createdAt: 1000, expiresAt: 3601000, stage: 'uncertain', operationId: null}]}); + await f.element.updateComplete; + await f.select(1, false); f.button('Save assignment').click(); + f.root.querySelector('#assignment-editor')!.dispatchEvent(new SubmitEvent('submit', {cancelable: true})); + expect(f.intents).toHaveLength(1); +}); + +test('assignment editor retires on another task or revoked action and guards uncertain or stale submits', async () => { + const f = await assignmentFixture(); f.button('Change assignment').click(); await f.element.updateComplete; + f.element.view = view({detail: {...f.detail, revision: revisionValue('2')}}); await f.element.updateComplete; + f.root.querySelector('#assignment-editor')!.dispatchEvent(new SubmitEvent('submit', {cancelable: true})); + expect(f.intents).toEqual([]); + f.button('Review current assignment').click(); await f.element.updateComplete; + f.element.view = view({detail: {...f.detail, occurrenceId: 'other-work'}}); await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')).toBeNull(); + f.button('Change assignment').click(); await f.element.updateComplete; + f.element.view = view({detail: {...f.detail, occurrenceId: 'other-work', allowedActions: []}}); await f.element.updateComplete; + expect(f.root.querySelector('#assignment-editor')).toBeNull(); + expect(f.button('Change assignment')).toBeUndefined(); +}); + +test('assignment focus survives a pending refresh and opens an unavailable roster at the editor', async () => { + const f = await assignmentFixture(); + f.button('Change assignment').click(); + f.element.view = view({phase: 'loading', busy: true}); await f.element.updateComplete; + expect(f.root.querySelector('#assignment-editor')).toBeNull(); + f.element.administration = null; + f.element.view = view({detail: f.detail}); await f.element.updateComplete; + expect(f.root.activeElement?.id).toBe('assignment-editor'); + f.root.querySelector('#assignment-editor')!.dispatchEvent(new SubmitEvent('submit', {cancelable: true})); + expect(f.intents).toEqual([]); + f.button('Cancel').click(); await f.element.updateComplete; + f.element.administration = assignmentRoster(); await f.element.updateComplete; + f.button('Change assignment').click(); await f.element.updateComplete; + f.button('Save assignment').click(); + f.element.view = view({detail: f.detail, notice: 'invalid_input'}); await f.element.updateComplete; + expect(f.root.activeElement?.id).toBe('assignment-editor'); + f.element.view = view({detail: {...f.detail, revision: revisionValue('2'), state: 'in_progress'}}); await f.element.updateComplete; + f.button('Review current assignment').click(); await f.element.updateComplete; + expect(f.root.activeElement?.id).toBe('assignment-editor'); + expect(f.button('Save assignment').disabled).toBe(true); +}); + +test('a retained older assignment receipt cannot close a newer submitted editor', async () => { + const receipt = {kind: 'receipt' as const, stage: 'committed' as const, action: 'task.assign' as const, + occurrenceId: 'work-1', operationId: 'older-op', revision: revisionValue('2'), state: 'assigned' as const, + cycle: null, archivedBy: null, assigneeIds: ['peer']}; + const f = await assignmentFixture('en', {revision: revisionValue('2'), assigneeIds: ['peer']}); + f.element.view = view({detail: f.detail, outcome: receipt}); await f.element.updateComplete; + f.button('Change assignment').click(); await f.element.updateComplete; + await f.select(0, true); f.button('Save assignment').click(); + f.element.view = view({detail: f.detail, outcome: receipt}); await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')).not.toBeNull(); + f.element.view = view({detail: f.detail, outcome: {...receipt, assigneeIds: undefined}}); await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')).not.toBeNull(); + const matchingIds = ['peer', 'private-member-id']; + f.element.view = view({detail: f.detail, outcome: {...receipt, assigneeIds: matchingIds}}); await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')).not.toBeNull(); + const alreadyRead = {...receipt, revision: revisionValue('3'), assigneeIds: matchingIds}; + f.element.view = view({detail: f.detail, outcome: alreadyRead}); + await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')).toBeNull(); + f.button('Change assignment').click(); await f.element.updateComplete; + f.button('Save assignment').click(); + f.element.view = view({detail: f.detail, outcome: alreadyRead}); await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')).not.toBeNull(); +}); + +test('a rejected assignment keeps the draft and an unresolved conflict requires deliberate review', async () => { + const f = await assignmentFixture(); f.button('Change assignment').click(); await f.element.updateComplete; + await f.select(0, true); f.button('Save assignment').click(); + f.element.view = view({detail: f.detail, outcome: {kind: 'rejected', reason: 'invalid_input', correlationId: 'safe-invalid'}}); + await f.element.updateComplete; + expect(f.root.querySelector('vyp-ha-checkbox')!.checked).toBe(true); + expect(f.button('Review current assignment')).toBeUndefined(); + f.element.view = view({detail: f.detail, outcome: {kind: 'rejected', reason: 'conflict', correlationId: 'safe-conflict'}}); + await f.element.updateComplete; + expect(f.button('Save assignment').disabled).toBe(true); + f.button('Review current assignment').click(); await f.element.updateComplete; + expect(f.button('Save assignment').disabled).toBe(false); +}); + +test.each(['unavailable', 'invalid_response'] as const)('assignment conflict with a %s current read requires a refresh', async notice => { + const f = await assignmentFixture(); f.button('Change assignment').click(); await f.element.updateComplete; + await f.select(0, true); f.button('Save assignment').click(); + f.element.view = view({detail: f.detail, notice, outcome: {kind: 'rejected', reason: 'conflict', correlationId: 'safe-conflict'}}); + await f.element.updateComplete; + expect(f.button('Review current assignment').disabled).toBe(true); + expect(f.button('Save assignment').disabled).toBe(true); + f.button('Refresh assignment and members').click(); + expect(f.intents.at(-1)).toEqual({type: 'refresh'}); + f.element.view = view({detail: {...f.detail, revision: revisionValue('2')}}); await f.element.updateComplete; + f.button('Review current assignment').click(); await f.element.updateComplete; + expect(f.button('Save assignment').disabled).toBe(false); +}); + +test('an exhausted task revision retains the assignment editor when an earlier receipt is recovered', async () => { + const last = revisionValue('9223372036854775807'); + const f = await assignmentFixture('en', {revision: last, assigneeIds: ['peer']}); + f.button('Change assignment').click(); await f.element.updateComplete; + f.button('Save assignment').click(); + f.element.view = view({detail: f.detail, outcome: {kind: 'receipt', action: 'task.assign', stage: 'committed', + occurrenceId: 'work-1', operationId: 'last-operation', revision: last, state: 'assigned', + assigneeIds: ['peer'], cycle: null, archivedBy: null}}); + await f.element.updateComplete; + expect(f.root.querySelector('#assignment-editor')).not.toBeNull(); + expect(f.intents[0]).toMatchObject({type: 'assign', revision: last, assigneeIds: ['peer']}); +}); + +test('a denied assignee retains the selection and offers removal after the authorized roster changes', async () => { + const f = await assignmentFixture(); f.button('Change assignment').click(); await f.element.updateComplete; + await f.select(1, true); f.button('Save assignment').click(); + const roster = assignmentRoster(); + f.element.administration = {...roster, roster: {...roster.roster!, members: roster.roster!.members.map(row => + row.member.memberId === 'peer' ? {...row, member: {...row.member, status: 'suspended'}} : row)}}; + f.element.view = view({detail: f.detail, outcome: {kind: 'rejected', reason: 'assignees_unavailable', correlationId: 'safe-member'}}); + await f.element.updateComplete; + expect(f.text()).toContain('Some selected members are unavailable.'); + expect(f.root.querySelector('[data-stale-assignee]')!.textContent).toContain('Helper & friend'); + expect(f.button('Save assignment').disabled).toBe(true); + f.button('Remove unavailable member').click(); await f.element.updateComplete; + expect(f.button('Save assignment').disabled).toBe(false); +}); test('usable task creation preserves literal input and emits one semantic intent', async () => { const f = await mount(); expect(f.root.querySelector('#task-priority')!.value).toBe('normal'); await f.input('task-title', ' Clean 🧹 '); await f.input('task-description', 'Wipe then dry'); diff --git a/frontend/tests/task-controller.test.ts b/frontend/tests/task-controller.test.ts index 237ec967..51f5b87b 100644 --- a/frontend/tests/task-controller.test.ts +++ b/frontend/tests/task-controller.test.ts @@ -28,6 +28,92 @@ 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('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']); + expect(f.server.send).not.toHaveBeenCalled(); + f.server.detail.mockReturnValue(read({...detail, allowedActions: ['assign']})); + await f.controller.select('work-1'); + f.server.send.mockResolvedValueOnce({kind: 'uncertain'}); + await f.controller.assign('work-1', revision, ['member-2', 'member-1']); + const request = f.server.send.mock.calls[0][0]; + expect(request).toEqual({key: 'key-1', command: {action: 'task.assign', occurrenceId: 'work-1', + payload: {expected_revision: revision, assignee_ids: ['member-2', 'member-1']}}}); + await f.controller.assign('work-1', revision, []); + expect(f.controller.view.notice).toBe('previous_request_unresolved'); + f.server.original.mockReturnValue(read({...saved, action: 'task.assign', assigneeIds: ['member-2', 'member-1']})); + await f.controller.recover('key-1'); + expect(f.server.original).toHaveBeenCalledWith({...request, operationId: null}, context); + expect(f.server.send).toHaveBeenCalledOnce(); +}); + +test('assignment conflict shows fresh details and requires a deliberate current revision', async () => { + const f = fixture(); await f.controller.refresh(); + f.server.detail.mockReturnValue(read({...detail, allowedActions: ['assign']})); + await f.controller.select('work-1'); + f.server.detail.mockReturnValue(read({...detail, allowedActions: ['assign'], revision: revisionValue('2'), assigneeIds: ['peer']})); + await f.controller.assign('work-1', revision, ['member-1']); + expect(f.controller.view.notice).toBe('conflict'); + expect(f.controller.view.detail?.assigneeIds).toEqual(['peer']); + expect(f.server.send).not.toHaveBeenCalled(); + await f.controller.assign('other-work', revisionValue('2'), []); + expect(f.server.send).not.toHaveBeenCalled(); + f.server.send.mockImplementationOnce(async () => { + f.server.detail.mockReturnValue(read({...detail, allowedActions: ['assign'], revision: revisionValue('3'), assigneeIds: ['peer-2']})); + return {kind: 'rejected', reason: 'conflict', correlationId: 'conflict-safe'}; + }); + await f.controller.assign('work-1', revisionValue('2'), ['member-1']); + expect(f.controller.view.outcome).toMatchObject({kind: 'rejected', reason: 'conflict'}); + expect(f.controller.view.detail?.revision).toBe('3'); + expect(f.controller.view.detail?.assigneeIds).toEqual(['peer-2']); + await f.controller.assign('work-1', revisionValue('3'), []); + expect(f.server.send.mock.calls[1][0].command).toMatchObject({payload: {expected_revision: '3', assignee_ids: []}}); +}); + +test('assignment denial, revoked action and changed household cannot send a new effect', async () => { + const f = fixture(); await f.controller.refresh(); await f.controller.select('work-1'); + await f.controller.assign('work-1', revision, ['member-1']); + expect(f.controller.view.notice).toBe('action_not_allowed'); + expect(f.server.send).not.toHaveBeenCalled(); + f.server.access.mockReturnValue(read({...f.controller.view.access!, householdId: 'foreign'})); + await f.controller.assign('work-1', revision, ['member-1']); + expect(f.controller.view.notice).toBe('context_changed'); + expect(f.server.send).not.toHaveBeenCalled(); +}); + +test('a failed assignment conflict read retains the rejected original until a fresh task can be reviewed', async () => { + const f = fixture(); await f.controller.refresh(); + f.server.detail.mockReturnValue(read({...detail, allowedActions: ['assign']})); + await f.controller.select('work-1'); + f.server.send.mockImplementationOnce(async () => { + f.server.detail.mockReturnValue({result: Promise.reject(new EntryReadError('unavailable')), cancel: vi.fn()}); + return {kind: 'rejected', reason: 'conflict', correlationId: 'safe-conflict'}; + }); + await f.controller.assign('work-1', revision, ['member-1']); + expect(f.controller.view.notice).toBe('unavailable'); + expect(f.controller.view.outcome).toMatchObject({kind: 'rejected', reason: 'conflict'}); + const original = f.controller.view.records![0]; + expect(original).toMatchObject({key: 'key-1', stage: 'rejected', command: {payload: {expected_revision: '1', assignee_ids: ['member-1']}}}); + f.server.detail.mockReturnValue(read({...detail, revision: revisionValue('2'), assigneeIds: ['peer'], allowedActions: ['assign']})); + await f.controller.refresh(); + expect(f.controller.view.notice).toBeNull(); + expect(f.controller.view.detail?.revision).toBe('2'); + expect(f.controller.view.records![0]).toEqual(original); + expect(f.server.send).toHaveBeenCalledOnce(); +}); + +test('an unavailable assignee keeps the authorized task and rejected selection available for correction', async () => { + const f = fixture(); await f.controller.refresh(); + f.server.detail.mockReturnValue(read({...detail, allowedActions: ['assign']})); + await f.controller.select('work-1'); + f.server.send.mockResolvedValueOnce({kind: 'rejected', reason: 'assignees_unavailable', correlationId: 'safe-member'}); + await f.controller.assign('work-1', revision, ['stale-member']); + expect(f.controller.view.detail?.occurrenceId).toBe('work-1'); + expect(f.controller.view.outcome).toMatchObject({kind: 'rejected', reason: 'assignees_unavailable'}); + expect(f.controller.view.records![0]).toMatchObject({stage: 'rejected', command: {payload: {assignee_ids: ['stale-member']}}}); + await f.controller.assign('work-1', revision, ['member-1']); + expect(f.server.send.mock.calls[1][0]).toMatchObject({key: 'key-2', command: {payload: {expected_revision: revision, assignee_ids: ['member-1']}}}); +}); test('a real task workspace loads under fresh identity and creates title-only work with a saved original', async () => { const f = fixture(); await f.controller.refresh(); expect(f.controller.view.page?.items[0].title).toBe('Clean 🧹'); await f.controller.create(' New task 🧹 ', '', 'normal'); diff --git a/frontend/tests/task-http.test.ts b/frontend/tests/task-http.test.ts index 9ab7863f..4a576383 100644 --- a/frontend/tests/task-http.test.ts +++ b/frontend/tests/task-http.test.ts @@ -50,6 +50,55 @@ function fixture(mode: 'native' | 'standalone' = 'standalone') { } afterEach(() => vi.useRealTimers()); +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', + payload: {expected_revision: REV, assignee_ids: ['member-2', 'member-1']}})!; + const request = {key: 'assignment-key', command}; + const saved = {...receipt(1), result: {...receipt(1).result, assignee_ids: ['member-1', 'member-2']}}; + f.transport.mockResolvedValueOnce(reply({csrf_token: 'c'.repeat(64)})).mockResolvedValueOnce(reply(saved)); + expect(await f.server.send(request, context)).toMatchObject({kind: 'receipt', action: 'task.assign', + revision: NEXT, assigneeIds: ['member-1', 'member-2']}); + const [path, init] = f.transport.mock.calls[1]; + expect(path).toBe(f.target.applicationBase + 'api/v1/tasks/occurrences/work-1/assignment'); + expect(init.method).toBe('PUT'); + expect(init.body).toBe('{"expected_revision":' + REV + ',"assignee_ids":["member-2","member-1"]}'); + expect(new Headers(init.headers).get('Idempotency-Key')).toBe('assignment-key'); + const original = {...saved, action: 'task.assign', command_key: 'assignment-key', delivery: 'pending'}; + f.transport.mockResolvedValueOnce(reply(original)); + expect(await f.server.original({...request, operationId: 'op-1'}, context).result) + .toMatchObject({kind: 'receipt', assigneeIds: ['member-1', 'member-2']}); + expect(f.transport.mock.calls[2][0]).toBe(f.target.applicationBase + 'api/v1/tasks/requests/task.assign/assignment-key'); + f.transport.mockResolvedValueOnce(reply({...original, result: {...saved.result, assignee_ids: ['member-1']}})); + await expect(f.server.original({...request, operationId: 'op-1'}, context).result).rejects.toThrow('invalid_response'); + f.transport.mockResolvedValueOnce(reply({csrf_token: 'c'.repeat(64)})).mockResolvedValueOnce(reply({...saved, + result: {...saved.result, assignee_ids: ['member-1']}})); + expect(await f.server.send(request, context)).toEqual({kind: 'uncertain'}); +}); + +test('assignment release confirms an empty assignee set', async () => { + const f = fixture(); + const command = taskCommand({action: 'task.assign', occurrenceId: 'work-1', payload: {expected_revision: REV, assignee_ids: []}})!; + f.transport.mockResolvedValueOnce(reply({csrf_token: 'c'.repeat(64)})).mockResolvedValueOnce(reply({...receipt(1), + result: {...receipt(1).result, state: 'available', assignee_ids: []}})); + expect(await f.server.send({key: 'release-key', command}, context)) + .toMatchObject({kind: 'receipt', state: 'available', assigneeIds: []}); +}); + +test.each([ + [403, 'task_assignee_denied', true, 'assignees_unavailable'], + [403, 'permission_denied', true, 'forbidden'], + [422, 'task_assignee_denied', true, 'invalid_input'], + [403, 'task_assignee_denied', false, 'forbidden'], +] as const)('assignment rejection %s/%s retains only its safe semantic outcome', async (status, code, assignment, expected) => { + const f = fixture(); + const command = assignment ? taskCommand({action: 'task.assign', occurrenceId: 'work-1', + payload: {expected_revision: REV, assignee_ids: ['member-1']}})! : commands[0]; + f.transport.mockResolvedValueOnce(reply({csrf_token: 'c'.repeat(64)})).mockResolvedValueOnce(failure(status, code)); + expect(await f.server.send({key: 'selection-key', command}, context)) + .toEqual({kind: 'rejected', reason: expected, correlationId: 'cor_safe'}); +}); + test.each(['fixed', 'relative'] as const)('scheduled %s task uses exact policy and recovers the original operation', async kind => { const f = fixture(); const rawPolicy = {zone: 'Europe/Madrid', data_identity: 'tzdata:2026.6/iana:2026f', diff --git a/frontend/tests/task-journal.test.ts b/frontend/tests/task-journal.test.ts index 81c7d2ef..87212b86 100644 --- a/frontend/tests/task-journal.test.ts +++ b/frontend/tests/task-journal.test.ts @@ -10,6 +10,19 @@ 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('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); + const assignment = taskCommand({action: 'task.assign', occurrenceId: 'work-1', + payload: {expected_revision: '9007199254740993', assignee_ids: ['member-2', 'member-1']}})!; + f.journal.prepare('assignment', assignment, 101); + f.journal.record('assignment', 'uncertain', null, 102); + const records = new TaskSessionJournal(f.storage).open(scope, 103); + expect(records[0].command).toEqual(command); + expect(records[1]).toMatchObject({key: 'assignment', scope, stage: 'uncertain', command: assignment}); + expect(Object.isFrozen((records[1].command.payload as {assignee_ids: readonly string[]}).assignee_ids)).toBe(true); + expect(f.journal.open({...scope, householdId: 'foreign'}, 104)).toEqual([]); +}); test('task originals survive a reload without changing key, text, scope, stage or expiry', () => { const f = fixture(); expect(f.journal.open(scope, 100)).toEqual([]); const original = f.journal.prepare('original', command, 101)[0]; diff --git a/frontend/tests/tasks.test.ts b/frontend/tests/tasks.test.ts index 563f80a5..401bbba5 100644 --- a/frontend/tests/tasks.test.ts +++ b/frontend/tests/tasks.test.ts @@ -7,6 +7,30 @@ 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([[], ['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}}; + const value = taskCommand(raw); + expect(value).toEqual(raw); + if (value?.action !== 'task.assign') throw Error('missing assignment'); + expect(Object.isFrozen(value.payload.assignee_ids)).toBe(true); + expect(value.payload.assignee_ids).not.toBe(assignee_ids); + }); + +test.each([null, 'member-1', ['member-1', 'member-1'], ['../member'], [1], Array(1), + Array.from({length: 33}, (_, index) => 'member-' + index)].map(assignee_ids => ({assignee_ids})))( + 'invalid assignment selection %# cannot become a command', ({assignee_ids}) => { + expect(taskCommand({action: 'task.assign', occurrenceId: 'work-1', + payload: {expected_revision: revision, assignee_ids}})).toBeUndefined(); + }); + +test('assignment rejects injected scope, omitted identities and unsafe revisions', () => { + const raw = {action: 'task.assign', occurrenceId: 'work-1', payload: {expected_revision: revision, assignee_ids: []}}; + for (const value of [{...raw, householdId: 'foreign'}, {...raw, occurrenceId: '../work'}, + {...raw, payload: {expected_revision: revision}}, {...raw, payload: {...raw.payload, expected_revision: 0}}, + {...raw, payload: {...raw.payload, actor_id: 'other'}}]) expect(taskCommand(value)).toBeUndefined(); +}); + test('task creation preserves literal text and supplies no actor, household or permission', () => { const raw = {action: 'task.create', payload: {expected_revision: 0, title: ' Clean 🧹 ', description: 'First\nthen\tsecond', priority: 'normal'}}; diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts index f20be900..e542f0ac 100644 --- a/frontend/vitest.config.ts +++ b/frontend/vitest.config.ts @@ -9,6 +9,7 @@ export default defineConfig({optimizeDeps: {include: [ '@vypdev/ha-ui/feedback-contracts', '@vypdev/ha-ui/feedback', '@vypdev/ha-ui/field-contracts', '@vypdev/ha-ui/field', '@vypdev/ha-ui/select-contracts', '@vypdev/ha-ui/select', + '@vypdev/ha-ui/checkbox-contracts', '@vypdev/ha-ui/checkbox', ]}, test: { include: ['tests/*.test.ts'], browser: {enabled: true, provider: playwright(), headless: true, instances: [{browser: 'chromium'}]}, diff --git a/specs/CATALOG.md b/specs/CATALOG.md index 6ae7c28c..73609161 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 | 53 paths · 2026-11-11 | +| `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 | | `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 | @@ -49,13 +49,13 @@ debt or convert unknown historic intent into a design decision. ### `household-tasks` — Task definitions, occurrences and household execution - Owner: Domus maintainers (review assignment pending) -- Last verified: 2026-11-11 +- 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) - 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) -- Tests: [`tests/backend/test_task_values.py`](../tests/backend/test_task_values.py) · [`tests/backend/test_task_policy.py`](../tests/backend/test_task_policy.py) · [`tests/backend/test_tasks.py`](../tests/backend/test_tasks.py) · [`tests/backend/test_sqlite_task_records.py`](../tests/backend/test_sqlite_task_records.py) · [`tests/backend/test_sqlite_tasks.py`](../tests/backend/test_sqlite_tasks.py) · [`tests/backend/test_sqlite_task_integrity.py`](../tests/backend/test_sqlite_task_integrity.py) · [`tests/backend/test_task_restoration.py`](../tests/backend/test_task_restoration.py) · [`tests/backend/test_task_authorization.py`](../tests/backend/test_task_authorization.py) · [`tests/backend/test_task_commands.py`](../tests/backend/test_task_commands.py) · [`tests/backend/test_task_http.py`](../tests/backend/test_task_http.py) · [`tests/backend/test_schedule_creation_http.py`](../tests/backend/test_schedule_creation_http.py) · [`tests/backend/test_task_execution_commands.py`](../tests/backend/test_task_execution_commands.py) · [`tests/backend/test_task_edit_commands.py`](../tests/backend/test_task_edit_commands.py) · [`tests/backend/test_task_overview.py`](../tests/backend/test_task_overview.py) · [`frontend/tests/task-overview.test.ts`](../frontend/tests/task-overview.test.ts) · [`frontend/tests/task-http.test.ts`](../frontend/tests/task-http.test.ts) · [`frontend/tests/task-component.test.ts`](../frontend/tests/task-component.test.ts) · [`frontend/tests/e2e/workspace-navigation.spec.ts`](../frontend/tests/e2e/workspace-navigation.spec.ts) -- User documentation: [`docs/product-vision.md`](../docs/product-vision.md) · [`docs/architecture.md`](../docs/architecture.md) · [`docs/operations.md`](../docs/operations.md) · [`docs/user-guide.md`](../docs/user-guide.md) · [`docs/contracts/home-assistant.md`](../docs/contracts/home-assistant.md) · [`docs/evidence/task-execution-foundation.json`](../docs/evidence/task-execution-foundation.json) · [`docs/tasks/operator-recovery.md`](../docs/tasks/operator-recovery.md) · [`docs/tasks/migration.md`](../docs/tasks/migration.md) · [`docs/tasks/execution.md`](../docs/tasks/execution.md) · [`docs/evidence/overview-task-qualification.md`](../docs/evidence/overview-task-qualification.md) · [`docs/evidence/overview-deadlines-qualification.md`](../docs/evidence/overview-deadlines-qualification.md) · [`docs/evidence/overview-maintenance-qualification.md`](../docs/evidence/overview-maintenance-qualification.md) · [`docs/evidence/task-base-points-qualification.md`](../docs/evidence/task-base-points-qualification.md) +- 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) +- Tests: [`tests/backend/test_task_values.py`](../tests/backend/test_task_values.py) · [`tests/backend/test_task_policy.py`](../tests/backend/test_task_policy.py) · [`tests/backend/test_tasks.py`](../tests/backend/test_tasks.py) · [`tests/backend/test_sqlite_task_records.py`](../tests/backend/test_sqlite_task_records.py) · [`tests/backend/test_sqlite_tasks.py`](../tests/backend/test_sqlite_tasks.py) · [`tests/backend/test_sqlite_task_integrity.py`](../tests/backend/test_sqlite_task_integrity.py) · [`tests/backend/test_task_restoration.py`](../tests/backend/test_task_restoration.py) · [`tests/backend/test_task_authorization.py`](../tests/backend/test_task_authorization.py) · [`tests/backend/test_task_commands.py`](../tests/backend/test_task_commands.py) · [`tests/backend/test_task_http.py`](../tests/backend/test_task_http.py) · [`tests/backend/test_schedule_creation_http.py`](../tests/backend/test_schedule_creation_http.py) · [`tests/backend/test_task_execution_commands.py`](../tests/backend/test_task_execution_commands.py) · [`tests/backend/test_task_edit_commands.py`](../tests/backend/test_task_edit_commands.py) · [`tests/backend/test_task_overview.py`](../tests/backend/test_task_overview.py) · [`frontend/tests/task-overview.test.ts`](../frontend/tests/task-overview.test.ts) · [`frontend/tests/task-http.test.ts`](../frontend/tests/task-http.test.ts) · [`frontend/tests/task-component.test.ts`](../frontend/tests/task-component.test.ts) · [`frontend/tests/e2e/workspace-navigation.spec.ts`](../frontend/tests/e2e/workspace-navigation.spec.ts) · [`tests/backend/test_task_queries.py`](../tests/backend/test_task_queries.py) · [`tests/backend/test_sqlite_task_history.py`](../tests/backend/test_sqlite_task_history.py) · [`frontend/tests/tasks.test.ts`](../frontend/tests/tasks.test.ts) · [`frontend/tests/task-controller.test.ts`](../frontend/tests/task-controller.test.ts) · [`frontend/tests/task-journal.test.ts`](../frontend/tests/task-journal.test.ts) · [`frontend/tests/e2e/tasks.spec.ts`](../frontend/tests/e2e/tasks.spec.ts) +- User documentation: [`docs/product-vision.md`](../docs/product-vision.md) · [`docs/architecture.md`](../docs/architecture.md) · [`docs/operations.md`](../docs/operations.md) · [`docs/user-guide.md`](../docs/user-guide.md) · [`docs/contracts/home-assistant.md`](../docs/contracts/home-assistant.md) · [`docs/evidence/task-execution-foundation.json`](../docs/evidence/task-execution-foundation.json) · [`docs/tasks/operator-recovery.md`](../docs/tasks/operator-recovery.md) · [`docs/tasks/migration.md`](../docs/tasks/migration.md) · [`docs/tasks/execution.md`](../docs/tasks/execution.md) · [`docs/evidence/overview-task-qualification.md`](../docs/evidence/overview-task-qualification.md) · [`docs/evidence/overview-deadlines-qualification.md`](../docs/evidence/overview-deadlines-qualification.md) · [`docs/evidence/overview-maintenance-qualification.md`](../docs/evidence/overview-maintenance-qualification.md) · [`docs/evidence/task-base-points-qualification.md`](../docs/evidence/task-base-points-qualification.md) · [`docs/evidence/task-assignment-qualification.md`](../docs/evidence/task-assignment-qualification.md) ### `recurrence-calendar` — Recurrence engine and family calendar diff --git a/specs/catalog.json b/specs/catalog.json index 08f783d6..d74615d1 100644 --- a/specs/catalog.json +++ b/specs/catalog.json @@ -477,7 +477,7 @@ "status": "proposed", "scope": "Members create and perform household responsibilities with explicit assignments, actual performers and history. A recurring definition survives completion of each individual occurrence.", "owner": "Domus maintainers (review assignment pending)", - "lastVerified": "2026-11-11", + "lastVerified": "2026-11-19", "specs": [ "specs/household-tasks.md", "specs/task-execution-foundation.md", @@ -510,7 +510,9 @@ "frontend/src/domain/tasks.ts", "frontend/src/application/task-controller.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-journal.ts" ], "tests": [ "tests/backend/test_task_values.py", @@ -530,7 +532,13 @@ "frontend/tests/task-overview.test.ts", "frontend/tests/task-http.test.ts", "frontend/tests/task-component.test.ts", - "frontend/tests/e2e/workspace-navigation.spec.ts" + "frontend/tests/e2e/workspace-navigation.spec.ts", + "tests/backend/test_task_queries.py", + "tests/backend/test_sqlite_task_history.py", + "frontend/tests/tasks.test.ts", + "frontend/tests/task-controller.test.ts", + "frontend/tests/task-journal.test.ts", + "frontend/tests/e2e/tasks.spec.ts" ], "documentation": [ "docs/product-vision.md", @@ -545,11 +553,12 @@ "docs/evidence/overview-task-qualification.md", "docs/evidence/overview-deadlines-qualification.md", "docs/evidence/overview-maintenance-qualification.md", - "docs/evidence/task-base-points-qualification.md" + "docs/evidence/task-base-points-qualification.md", + "docs/evidence/task-assignment-qualification.md" ], "readiness": { "state": "draft", - "implementationEvidence": "partial: task lifecycle/rules, schema-5 storage/restore, shared current authority, typed requests and durable lifecycle/policy/definition/occurrence/dependency editors; 2044 whole-backend tests, 5741 statements and 1624 branches at 100%; public queries/history/HTTP and actual material/consumer/review projections remain incomplete; protected Overview summary exercised in compiled native and standalone browser journeys with exact authorized group counts and task detail navigation; issue #96 adds effective timed and date-only deadlines for due today and overdue work; issue #100 adds bounded upcoming scheduled maintenance in the next seven local days", + "implementationEvidence": "partial: task lifecycle/rules, schema-5 storage/restore, shared current authority, typed requests and durable lifecycle/policy/definition/occurrence/dependency editors; 2044 whole-backend tests, 5741 statements and 1624 branches at 100%; public queries/history/HTTP and actual material/consumer/review projections remain incomplete; protected Overview summary exercised in compiled native and standalone browser journeys with exact authorized group counts and task detail navigation; issue #96 adds effective timed and date-only deadlines for due today and overdue work; issue #100 adds bounded upcoming scheduled maintenance in the next seven local days; issue #141 connects authorized planned assignment, replacement/release, explicit conflict review and frozen original-request recovery to the Tasks workspace, with current-source English keyboard and Spanish touch acceptance in both deployment compositions", "blockingDecisions": "A34 prerequisite gating and A35 same-task points remainder rotation are owner-confirmed. Bounded queries/history/APIs, material intents/settlement, dependency-review projection and actual Inventory/Points/recurrence consumers, task UI and deployment acceptance remain implementation gates; first-release advanced task-type review remains separate.", "copilotChangesAllowed": false } diff --git a/tests/backend/test_task_http.py b/tests/backend/test_task_http.py index 86376d9a..bc19ce02 100644 --- a/tests/backend/test_task_http.py +++ b/tests/backend/test_task_http.py @@ -68,6 +68,40 @@ def test_title_only_create_detail_history_and_own_operation_replay(api): assert "ha_user_id" not in history.text and "payload_fingerprint" not in history.text +def test_assignment_original_read_preserves_the_recorded_members_and_current_authority(api): + created = create(api) + occurrence = created["result"]["occurrence_id"] + member = api.client.get("/api/v1/authorization").json()["member"]["member_id"] + body = {"expected_revision": 1, "assignee_ids": [member]} + denied = api.client.put( + PREFIX + "/occurrences/" + occurrence + "/assignment", + json={**body, "assignee_ids": ["foreign-member"]}, + headers=api.headers("foreign-assignment"), + ) + assert denied.status_code == 403 and denied.json()["code"] == "task_assignee_denied" + assert api.client.get(PREFIX + "/occurrences/" + occurrence).json()["work"]["revision"] == 1 + assigned = checked(api, "put", "/occurrences/" + occurrence + "/assignment", body, "assign") + before = api.client.get(PREFIX + "/occurrences/" + occurrence).json() + original = api.client.get(PREFIX + "/requests/task.assign/assign") + assert original.status_code == 200, original.text + assert original.json() == { + **assigned, + "delivery": "pending", + "action": "task.assign", + "command_key": "assign", + } + assert api.client.get(PREFIX + "/occurrences/" + occurrence).json() == before + assert api.client.get(PREFIX + "/requests/task.assign/missing").status_code == 404 + assert api.client.get(PREFIX + "/requests/task.assign/assign?actor_id=other").status_code == 422 + with api.store.write() as unit: + current = unit.members.get("home", member) + unit.members.save( + replace(current, role=Role.VIEWER, revision=current.revision + 1), current.revision + ) + api.user("a" * 32) + assert api.client.get(PREFIX + "/requests/task.assign/assign").status_code == 403 + + @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 55de5015..86c905ee 100644 --- a/tests/backend/test_task_queries.py +++ b/tests/backend/test_task_queries.py @@ -315,6 +315,7 @@ def test_own_operation_lookup_rechecks_original_authority_without_rerunning_prec if receipt.command.action in { "task.create", "task.claim", + "task.assign", "task.complete", "task.verify", "task.reopen", @@ -637,7 +638,11 @@ def test_workspace_access_uses_current_task_grants_and_canonical_member(tmp_path @pytest.mark.parametrize( "action,permission", - [("claim", Permission.TASKS_CLAIM), ("complete", Permission.TASKS_COMPLETE)], + [ + ("claim", Permission.TASKS_CLAIM), + ("complete", Permission.TASKS_COMPLETE), + ("assign", Permission.TASKS_MANAGE), + ], ) def test_task_original_recovery_uses_current_task_grants_without_separate_operation_browsing( tmp_path, action, permission @@ -648,18 +653,25 @@ def test_task_original_recovery_uses_current_task_grants_without_separate_operat unit.members.save( replace( member, - exceptions=(PermissionRule(Permission.OPERATIONS_READ, False),), + exceptions=( + PermissionRule(Permission.OPERATIONS_READ, False), + *( + (PermissionRule(Permission.TASKS_MANAGE, True),) + if action == "assign" + else () + ), + ), revision=member.revision + 1, ), member.revision, ) if action == "complete": child.claim("assign-to-self", ClaimTask(oid, 1)) - result = ( - child.claim("restricted-original", ClaimTask(oid, 1)) - if action == "claim" - else perform(child, store, oid, ("child",), "restricted-original") - ) + result = perform(child, store, oid, ("child",), "restricted-original") + elif action == "assign": + result = child.assign("restricted-original", AssignTask(oid, 1, ("child",))) + else: + result = child.claim("restricted-original", ClaimTask(oid, 1)) query = queries(store, child.actor.current()) before, allocated = state(store, oid), identifiers.count assert query.original(result.command.action, result.command.key).receipt == result @@ -669,10 +681,11 @@ def test_task_original_recovery_uses_current_task_grants_without_separate_operat queries(store, commands.actor.current()).original(result.command.action, result.command.key) with store.write() as unit: member = unit.members.get("home", "child") + remaining = tuple(rule for rule in member.exceptions if rule.permission != permission) unit.members.save( replace( member, - exceptions=(*member.exceptions, PermissionRule(permission, False)), + exceptions=(*remaining, PermissionRule(permission, False)), revision=member.revision + 1, ), member.revision, diff --git a/tests/backend/test_task_restoration.py b/tests/backend/test_task_restoration.py index a0bd6ce4..3d140617 100644 --- a/tests/backend/test_task_restoration.py +++ b/tests/backend/test_task_restoration.py @@ -91,14 +91,14 @@ def test_restore_keeps_original_task_state_and_retains_later_completion_as_proce again.close() -@pytest.mark.parametrize("action", ["create", "claim"]) +@pytest.mark.parametrize("action", ["create", "claim", "assign"]) def test_real_task_commands_return_historical_receipts_without_reapplying_restored_away_work( tmp_path: Path, action: str ) -> None: from test_task_commands import child_commands, resource from test_task_commands import fixture as task_fixture - from domus.application.task_commands import ClaimTask, CreateTask, TaskCommands + from domus.application.task_commands import AssignTask, ClaimTask, CreateTask, TaskCommands from domus.domain.task_values import TaskContent, TaskOverrides root, archive, target = tmp_path / "source", tmp_path / "checkpoint", tmp_path / "prepared" @@ -107,7 +107,7 @@ def test_real_task_commands_return_historical_receipts_without_reapplying_restor identity_at(root, store.installation) create = CreateTask(TaskContent("Work"), overrides=TaskOverrides(point_value_minor=225)) work_id = None - if action == "claim": + if action != "create": work_id = resource(commands.create("create", create))[1] checkpoint = SQLiteSnapshots(store, archive, store.installation, Clock()).create( "before-command" @@ -116,10 +116,14 @@ def test_real_task_commands_return_historical_receipts_without_reapplying_restor request = create original = commands.create("create", request) proof = actor - else: + elif action == "claim": service, proof = child_commands(store, identifiers=identifiers) request = ClaimTask(work_id, 1) original = service.claim("claim", request) + else: + request = AssignTask(work_id, 1, ("child", "other")) + original = commands.assign("assign", request) + proof = actor count = identifiers.count SQLiteRestorations(store, archive, target, store.installation, Clock(), checkpoint).prepare( "restore-command" diff --git a/tests/browser/entry_server.py b/tests/browser/entry_server.py index 2fbf2dc0..94755772 100644 --- a/tests/browser/entry_server.py +++ b/tests/browser/entry_server.py @@ -231,6 +231,11 @@ def console(self, *arguments: str) -> dict: def operator(self, action: str) -> None: # Real installation-console operations on disposable data only; never a product bypass. + if action == "restart": + self.runtime.close() + self.runtime = None + self.start() + return checkpoint = Path(self.directory.name) / "checkpoint" prepared = Path(self.directory.name) / "prepared" if action == "snapshot": diff --git a/tests/python/test_ci_contract.py b/tests/python/test_ci_contract.py index d3d49989..16f4f5cf 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 fifty-six actual-image household journeys" + if step.get("name") == "Require all sixty actual-image household journeys" ) assert all(field in audit["run"] for field in ["expected", "unexpected", "skipped", "flaky"]) - assert "expected']==56" in audit["run"] + assert "expected']==60" in audit["run"] cleanup = next( step for step in steps if step.get("name") == "Require no surviving image browser fixtures" ) From c98c56d9b90c7a28483966d25351294039291c8c Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 06:21:59 +0100 Subject: [PATCH 3/7] chore(edge): pin qualified task assignment candidate Edge.48 --- addon-edge/CHANGELOG.md | 6 +++++ addon-edge/DOCS.md | 7 +++++- addon-edge/Dockerfile | 8 +++---- addon-edge/artifact.json | 18 +++++++-------- addon-edge/config.yaml | 2 +- .../graceful-shutdown-qualification.md | 2 +- .../evidence/task-assignment-qualification.md | 23 +++++++++++++++++-- frontend/tests/e2e/tasks.spec.ts | 1 + tests/backend/test_app_package.py | 14 +++++------ 9 files changed, 56 insertions(+), 25 deletions(-) diff --git a/addon-edge/CHANGELOG.md b/addon-edge/CHANGELOG.md index 85369b42..28519b7e 100644 --- a/addon-edge/CHANGELOG.md +++ b/addon-edge/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 0.0.0-edge.48 + +- Assign, replace and release planned task assignees through the Tasks workspace. +- Retain selected household members while reviewing a competing update or correcting unavailable choices. +- Recover the original recorded assignment after an interrupted response. + ## 0.0.0-edge.47 - Complete explicit runtime cleanup when SIGTERM requests a stop. diff --git a/addon-edge/DOCS.md b/addon-edge/DOCS.md index ba704f2c..6b8ef10c 100644 --- a/addon-edge/DOCS.md +++ b/addon-edge/DOCS.md @@ -1,6 +1,6 @@ # Installation and operation -Edge 0.0.0-edge.47 packages the immutable runtime declared in +Edge 0.0.0-edge.48 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 @@ -25,6 +25,11 @@ for outstanding items and quantities. The the titles and current states of all open household occurrences. These projections share the private app port `8100` and each requires its own installation grant. +In Tasks, authorized managers can use **Change assignment** to choose active +household members and **Save assignment** to confirm the selection. Clearing it +prepares a state-permitted release. A competing update retains the draft for +explicit review. **Check saved request** recovers an interrupted assignment. + 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 7131e882..ffef6a9f 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=6e35e7e97926753adea78e40b9669f4fd2a01d54 -ARG DOMUS_SOURCE_SHA256=d1bfb1c259bcf87c3531da91ed7faebf75272c66f24ec69c05ab357f5bbd88dc +ARG DOMUS_SOURCE_COMMIT=95fff8ab5ff0a5a85872596447c314e365813d1b +ARG DOMUS_SOURCE_SHA256=c1b43ec66442834ca7f2093660ab6700ddc18dd31496ef982c0df564305faa5f 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.47 +ARG BUILD_VERSION=0.0.0-edge.48 ARG BUILD_ARCH -ARG DOMUS_SOURCE_COMMIT=6e35e7e97926753adea78e40b9669f4fd2a01d54 +ARG DOMUS_SOURCE_COMMIT=95fff8ab5ff0a5a85872596447c314e365813d1b LABEL io.hass.type="app" \ io.hass.version="${BUILD_VERSION}" \ io.hass.arch="${BUILD_ARCH}" \ diff --git a/addon-edge/artifact.json b/addon-edge/artifact.json index edaad5ad..73a83e00 100644 --- a/addon-edge/artifact.json +++ b/addon-edge/artifact.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, - "version": "0.0.0-edge.47", - "sourceCommit": "6e35e7e97926753adea78e40b9669f4fd2a01d54", - "sourceArchiveSHA256": "d1bfb1c259bcf87c3531da91ed7faebf75272c66f24ec69c05ab357f5bbd88dc", + "version": "0.0.0-edge.48", + "sourceCommit": "95fff8ab5ff0a5a85872596447c314e365813d1b", + "sourceArchiveSHA256": "c1b43ec66442834ca7f2093660ab6700ddc18dd31496ef982c0df564305faa5f", "storageSchema": 34, - "wheelSHA256": "7695249a943695ab603f753c4976cd0d953dd6c3e945e0bba61ec7960423a12c", + "wheelSHA256": "498b3840ca22370da8a77822027d3332240e9c0d4e5827dcad8b7e122b329bfb", "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": "24dd8792df559bc55725343a0c55f65158f4fbfec41808046a207af01e30d99d", + "domus/application/task_queries.py": "f5cf1da6bbb86386b05844d24a021ff8935fa92882c1261c650da2e3b3ee7347", "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": "f83fb816f00becfb23fc28e953499803aadf43d229e17a5aca23a8147170fc76", + "domus/entrypoints/task_http.py": "fffefb1542eb545b45efe0e14467015e61babed51a6bc09a5978fc9c2673ab51", "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": "857ddac99d888617f414cda4fbcedd4133a187b6d292750460dd8f66a732e588", - "assets/index-C5UQqRgD.js": "a7c554c95e87f2923fc82efcb873353ccf217241a0043375e9b58c09df6361fd", + ".vite/manifest.json": "57bca827cf42675475c7e61c7d04d0f4115d5a590a6e1b4adba5a77c842095fb", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "index.html": "d795e3f20dc09de365a1427689e9474dc1e7fa284c43664724902d96a1620c0d" + "assets/index-CyP_LOPa.js": "4bd9bde4488b5736d19b4e4f8223faeebbd3249c847f28b201ac5c79f04f0de2", + "index.html": "2915734b7044319908e14097bbb74bce54a77a39b7e0fde850996d63f27c02ca" } } diff --git a/addon-edge/config.yaml b/addon-edge/config.yaml index 0e4e4277..6eb1417a 100644 --- a/addon-edge/config.yaml +++ b/addon-edge/config.yaml @@ -1,5 +1,5 @@ name: Domus Edge -version: "0.0.0-edge.47" +version: "0.0.0-edge.48" slug: domus_edge description: Development preview of the local Domus household application url: https://github.com/vypdev/domus diff --git a/docs/evidence/graceful-shutdown-qualification.md b/docs/evidence/graceful-shutdown-qualification.md index 500631bb..adb81352 100644 --- a/docs/evidence/graceful-shutdown-qualification.md +++ b/docs/evidence/graceful-shutdown-qualification.md @@ -54,7 +54,7 @@ The wheel SHA-256 is The local ARM64 image is `sha256:fa0964010fe5b0420bed3268084e7080356b208852467e5cfb780541396085a3`. Its 231 Python files and four UI files match the -[artifact declaration](../../addon-edge/artifact.json) exactly. +[artifact declaration](https://github.com/vypdev/domus/blob/1237fbb9a8de2a4049056caef6f26f2be94e982a/addon-edge/artifact.json) exactly. The signal scope has 21 statements and two branches. The focused CLI campaign passed 28 cases, including the startup and listener-handoff regressions. The full diff --git a/docs/evidence/task-assignment-qualification.md b/docs/evidence/task-assignment-qualification.md index 865693e9..478702a3 100644 --- a/docs/evidence/task-assignment-qualification.md +++ b/docs/evidence/task-assignment-qualification.md @@ -38,5 +38,24 @@ assignment, receipt and restoration formats. The selected ha-ui version is Current-source Chromium qualification passes all four new compiled journeys. The full frontend suite passes 1,833 cases with 100% of all four supported metrics -globally and per authored runtime file. Immutable candidate packaging, both image -architectures, installed Edge acceptance and exact-head PR gates are pending. +globally and per authored runtime file. Both image architectures, installed Edge +acceptance and exact-head PR gates are pending. + +## Immutable candidate + +Edge.48 uses runtime source `95fff8ab5ff0a5a85872596447c314e365813d1b`. +Its source archive SHA-256 is +`c1b43ec66442834ca7f2093660ab6700ddc18dd31496ef982c0df564305faa5f`. +The measured Linux wheel SHA-256 is +`498b3840ca22370da8a77822027d3332240e9c0d4e5827dcad8b7e122b329bfb`. +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 ARM64 image is +`sha256:08f426df9f0bc9d0c3441eb0505b55a47fd0b507c5f3932d7e5952d94b296e9a`. +Nine actual-image cases passed, covering every declared Python/UI file, native +authority and restart, private standalone delivery, an actual Edge.5 upgrade and +restore, repeated SIGTERM cleanup, and all four real-Core deployment compositions. +The four assignment browser journeys also passed against this exact installed +image in Ingress and standalone, with English keyboard and Spanish native touch. diff --git a/frontend/tests/e2e/tasks.spec.ts b/frontend/tests/e2e/tasks.spec.ts index 4e2b452e..60a3aed7 100644 --- a/frontend/tests/e2e/tasks.spec.ts +++ b/frontend/tests/e2e/tasks.spec.ts @@ -288,6 +288,7 @@ for (const mode of ['native', 'standalone'] as const) test.describe('tasks ' + m await participant.getByRole('link', {name: 'Tasks', exact: true}).click(); const memberTasks = participant.locator('domus-tasks'); await memberTasks.getByRole('button', {name: title, exact: true}).click(); await expect(memberTasks.getByRole('button', {name: 'Create task', exact: true})).toHaveCount(0); + await expect(memberTasks.getByRole('button', {name: 'Change assignment', exact: true})).toHaveCount(0); await memberTasks.getByRole('button', {name: 'Claim task', exact: true}).click(); await memberTasks.locator('summary').filter({hasText: 'Saved requests'}).click(); await memberTasks.getByRole('button', {name: 'Dismiss saved request', exact: true}).click(); diff --git a/tests/backend/test_app_package.py b/tests/backend/test_app_package.py index 357ff3e4..9ec0bca9 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.47" + assert manifest["boot"] == "manual" and manifest["version"] == "0.0.0-edge.48" 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] == "6e35e7e97926753adea78e40b9669f4fd2a01d54" + assert commits[0] == "95fff8ab5ff0a5a85872596447c314e365813d1b" assert ( - "DOMUS_SOURCE_SHA256=d1bfb1c259bcf87c3531da91ed7faebf75272c66f24ec69c05ab357f5bbd88dc" + "DOMUS_SOURCE_SHA256=c1b43ec66442834ca7f2093660ab6700ddc18dd31496ef982c0df564305faa5f" in source ) - assert "ARG BUILD_VERSION=0.0.0-edge.47" in source + assert "ARG BUILD_VERSION=0.0.0-edge.48" in source candidate = json.loads((ROOT / "addon-edge/artifact.json").read_text()) assert candidate["sourceCommit"] == commits[0] - assert candidate["version"] == "0.0.0-edge.47" + assert candidate["version"] == "0.0.0-edge.48" 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.47" - assert artifact["sourceCommit"] == "6e35e7e97926753adea78e40b9669f4fd2a01d54" + assert artifact["schemaVersion"] == 1 and artifact["version"] == "0.0.0-edge.48" + assert artifact["sourceCommit"] == "95fff8ab5ff0a5a85872596447c314e365813d1b" assert artifact["storageSchema"] == 34 for field in ["sourceArchiveSHA256", "wheelSHA256"]: assert re.fullmatch("[a-f0-9]{64}", artifact[field]) From 71cf53c480865279cb76dde281b043abae3a577a Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 06:24:35 +0100 Subject: [PATCH 4/7] ci: budget complete browser acceptance on shared runners --- .github/workflows/ci_check.yml | 2 +- frontend/playwright.entry.config.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci_check.yml b/.github/workflows/ci_check.yml index f2d6ad84..a65b4dae 100644 --- a/.github/workflows/ci_check.yml +++ b/.github/workflows/ci_check.yml @@ -163,7 +163,7 @@ jobs: runs-on: group: vypdev labels: [self-hosted, codex, Linux] - timeout-minutes: 15 + timeout-minutes: 25 env: CI: "1" steps: diff --git a/frontend/playwright.entry.config.ts b/frontend/playwright.entry.config.ts index 08307ddd..a54a1d39 100644 --- a/frontend/playwright.entry.config.ts +++ b/frontend/playwright.entry.config.ts @@ -3,7 +3,7 @@ import {defineConfig} from '@playwright/test'; export default defineConfig({ testDir: 'tests/e2e', testMatch: ['entry.spec.ts','administration.spec.ts','tasks.spec.ts','workspace-navigation.spec.ts'], forbidOnly: true, retries: 0, workers: 1, // Include both workspace journeys, fixture startup and cleanup on slower self-hosted runners. - globalTimeout: 450_000, outputDir: 'test-results/entry-artifacts', + globalTimeout: 600_000, outputDir: 'test-results/entry-artifacts', reporter: [['list'], ['json', {outputFile: 'test-results/entry-results.json'}]], // Playwright normally disables BFCache. Exercise the real production page lifecycle instead. use: {headless: true, launchOptions: {ignoreDefaultArgs: ['--disable-back-forward-cache']}, From 9f2d2588e1ba829a7b4d1b9b1917cc5ed703e56b Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 07:09:39 +0100 Subject: [PATCH 5/7] test(tasks): await authenticated navigation after runtime restart --- addon-edge/README.md | 4 +++ .../evidence/task-assignment-qualification.md | 27 +++++++++++++++++-- frontend/tests/e2e/tasks.spec.ts | 1 + 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/addon-edge/README.md b/addon-edge/README.md index 3c757f02..36bbe832 100644 --- a/addon-edge/README.md +++ b/addon-edge/README.md @@ -16,6 +16,10 @@ original outcome after an interruption and open the created task from its receip Edge.47 completes requested stops through explicit runtime cleanup. Restarting the app retains its installation identity and original household operations. +Edge.48 lets task managers assign active household members, replace the selected +people and release eligible work from Tasks. A competing update retains the draft +for explicit review. Saved requests recover an interrupted assignment response. + 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 diff --git a/docs/evidence/task-assignment-qualification.md b/docs/evidence/task-assignment-qualification.md index 478702a3..5405838b 100644 --- a/docs/evidence/task-assignment-qualification.md +++ b/docs/evidence/task-assignment-qualification.md @@ -38,8 +38,10 @@ assignment, receipt and restoration formats. The selected ha-ui version is Current-source Chromium qualification passes all four new compiled journeys. The full frontend suite passes 1,833 cases with 100% of all four supported metrics -globally and per authored runtime file. Both image architectures, installed Edge -acceptance and exact-head PR gates are pending. +globally and per authored runtime file. The backend passes 5,513 cases with 100% +statement and branch coverage globally and across all 231 modules, independently +audited per file. Architecture-specific CI and final review are tracked in +[PR #142](https://github.com/vypdev/domus/pull/142). ## Immutable candidate @@ -59,3 +61,24 @@ authority and restart, private standalone delivery, an actual Edge.5 upgrade and restore, repeated SIGTERM cleanup, and all four real-Core deployment compositions. The four assignment browser journeys also passed against this exact installed image in Ingress and standalone, with English keyboard and Spanish native touch. + +The first CI campaign exposed a browser-test bootstrap race after standalone +restart. The test selected Spanish while authentication was still loading, then +waited for Spanish navigation after the completed bootstrap selected English. +The journey now waits for authenticated navigation before changing language. +All four actual-image assignment journeys passed three consecutive repetitions. + +## Installed Home Assistant acceptance + +Chrome verified installed version `0.0.0-edge.48` using the Action-managed issue +branch and the synthetic household `Domus QA 141 Edge48`. English keyboard input +assigned a task, retained an empty draft across two competing updates, focused +explicit current-assignment review and deliberately released the task. The +390 px Spanish touch journey assigned, cancelled an edit, released and reassigned +another task. Dark-theme text, focus and the assignment controls were legible. + +The app stopped with Home Assistant's `Detenido` state and restarted successfully. +Both task identities persisted. The released desktop task retained revision 5 +and the assigned mobile task retained revision 4. Checking the saved assignment +after restart recovered its recorded operation. The isolated-image SIGTERM cases +also require a zero exit status. diff --git a/frontend/tests/e2e/tasks.spec.ts b/frontend/tests/e2e/tasks.spec.ts index 60a3aed7..26c0b292 100644 --- a/frontend/tests/e2e/tasks.spec.ts +++ b/frontend/tests/e2e/tasks.spec.ts @@ -505,6 +505,7 @@ for (const mode of ['native', 'standalone'] as const) { 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 expect(page.getByRole('link', {name: 'Tasks', exact: true})).toBeVisible(); await page.getByRole('combobox', {name: /^(Language|Idioma)$/u}).selectOption(locale); await page.getByRole('link', {name: t('Tasks', 'Tareas'), exact: true}).click(); }; From 0a95702a5f53911cc12c645bf7f6f2e8dcd626cd Mon Sep 17 00:00:00 2001 From: Efra Espada Date: Thu, 19 Nov 2026 07:47:51 +0100 Subject: [PATCH 6/7] fix(tasks): require a changed assignment before saving --- .../evidence/task-assignment-qualification.md | 16 +++++++- .../evidence/task-navigation-integration.json | 6 +-- docs/user-guide.md | 1 + frontend/src/presentation/domus-tasks.ts | 5 ++- frontend/src/presentation/task-messages.ts | 2 + frontend/tests/e2e/tasks.spec.ts | 13 +++++- frontend/tests/task-component.test.ts | 40 ++++++++++++++++++- 7 files changed, 74 insertions(+), 9 deletions(-) diff --git a/docs/evidence/task-assignment-qualification.md b/docs/evidence/task-assignment-qualification.md index 5405838b..697224e6 100644 --- a/docs/evidence/task-assignment-qualification.md +++ b/docs/evidence/task-assignment-qualification.md @@ -37,7 +37,7 @@ assignment, receipt and restoration formats. The selected ha-ui version is `0.1.0-next.2`. Current-source Chromium qualification passes all four new compiled journeys. -The full frontend suite passes 1,833 cases with 100% of all four supported metrics +The full frontend suite passes 1,840 cases with 100% of all four supported metrics globally and per authored runtime file. The backend passes 5,513 cases with 100% statement and branch coverage globally and across all 231 modules, independently audited per file. Architecture-specific CI and final review are tracked in @@ -82,3 +82,17 @@ Both task identities persisted. The released desktop task retained revision 5 and the assigned mobile task retained revision 4. Checking the saved assignment after restart recovered its recorded operation. The isolated-image SIGTERM cases also require a zero exit status. + +## Unchanged assignment correction + +Review found that saving the current selection reached the existing backend's +`task_unchanged` conflict and showed current-version review unnecessarily. The +editor now compares canonical member sets, disables an unchanged save and explains +how to enable it in English and Spanish. Reordering the same selected members +keeps that guard. A competing update that already applies the retained selection +also leaves save disabled after explicit review. + +Seven component regressions reproduced the issue before the correction. The four +compiled assignment journeys now check the initial unchanged state and changing +the selection back to its original set. Edge.49 packaging and installed acceptance +will qualify the correction independently of the earlier Edge.48 observation. diff --git a/docs/evidence/task-navigation-integration.json b/docs/evidence/task-navigation-integration.json index 3fb7a02a..9d9b281d 100644 --- a/docs/evidence/task-navigation-integration.json +++ b/docs/evidence/task-navigation-integration.json @@ -5,10 +5,10 @@ "command": "pnpm build:frontend", "scope": "Compiled household workspace with protected manual automation preview, saved revisions, explicit runs and scoped run history, 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.", "actualProductFiles": { - ".vite/manifest.json": "57bca827cf42675475c7e61c7d04d0f4115d5a590a6e1b4adba5a77c842095fb", + ".vite/manifest.json": "f4fdf822c622f2e96f1b01bf5c1cdbec895eb99b7fc118f8d4df54e4fd7d87b0", + "assets/index-BYTTreHd.js": "2eb864558eeff849ff8abb5aaab2409a1c6589ba3dc4d7cb09385ab9175fc001", "assets/index-CjJnHZzV.css": "0f2c8c2e31576c0b64fe60373150f09390dafb896df6c07777b2a220ad430e48", - "assets/index-CyP_LOPa.js": "4bd9bde4488b5736d19b4e4f8223faeebbd3249c847f28b201ac5c79f04f0de2", - "index.html": "2915734b7044319908e14097bbb74bce54a77a39b7e0fde850996d63f27c02ca" + "index.html": "eb9cf14a75ac42e824649a406b7d388978547a14d2d712251b92663b6954532b" }, "localValidation": { "commit": "9a10d8114869be754962953903e773fe8e12c723", diff --git a/docs/user-guide.md b/docs/user-guide.md index 530622cd..777bc99f 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -55,6 +55,7 @@ actions your role allows. Use **Retry inventory summary** if the summary could n - Select a task to inspect it. **Claim task** assigns eligible work to your own verified membership. **Mark done now** records you as the performer at the current server-anchored time. - When task management is allowed, **Change assignment** opens the current planned assignees. Select up to 32 active household members and choose **Save assignment**. + Saving becomes available when the selected members differ from the current assignment. **Clear selection** prepares a release where the task state permits it. A task in progress needs at least one assignee. **Cancel** closes the editor. If someone else changes the task, your selection remains available. Use diff --git a/frontend/src/presentation/domus-tasks.ts b/frontend/src/presentation/domus-tasks.ts index fd85079c..bc457aa4 100644 --- a/frontend/src/presentation/domus-tasks.ts +++ b/frontend/src/presentation/domus-tasks.ts @@ -403,9 +403,11 @@ export class DomusTasks extends LitElement { const choices = discovery === 'ready' ? this.administration!.roster!.members.filter(row => row.member.status === 'active') : []; const stale = draft?.assigneeIds.filter(id => !choices.some(row => row.member.memberId === id)) ?? []; const needsReview = this.assignmentNeedsReview(work); + const unchanged = draft !== null + && JSON.stringify([...draft.assigneeIds].sort()) === JSON.stringify([...work.assigneeIds].sort()); const requiresAssignee = work.state === 'in_progress' && draft?.assigneeIds.length === 0; const currentUnavailable = this.view!.notice === 'unavailable' || this.view!.notice === 'invalid_response'; - const invalid = discovery !== 'ready' || stale.length > 0 || requiresAssignee || currentUnavailable; + const invalid = discovery !== 'ready' || stale.length > 0 || requiresAssignee || currentUnavailable || unchanged; return html`

${this.text('assignmentTitle')}

${discovery === 'ready' ? html`

${work.assigneeIds.length ? work.assigneeIds.map(id => this.assignmentName(id)).join(', ') : this.text('assignmentEmpty')}

` : html`

${this.text(discovery)}

`} @@ -430,6 +432,7 @@ export class DomusTasks extends LitElement { aria-label=${this.text('assignmentRemove')}>${this.text('assignmentRemove')}`)}` : nothing} ${requiresAssignee ? html`` : nothing} ${this.assignmentError ? html`` : nothing} + ${unchanged && discovery === 'ready' && !needsReview ? html`

${this.text('assignmentUnchanged')}

` : nothing} ${needsReview ? html`

${this.text('assignmentChanged')}