You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@causeway.apache.org by da...@apache.org on 2026/08/24 21:10:50 UTC
(causeway) branch htmx updated (18f0a783d24 -> 8743abdacd1)
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a change to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
from 18f0a783d24 archives input value semantics hardening
new 9b1994930d4 plans web component action dispatch correction
new bb612cda335 fixes web component action dispatch correctness
new 745c42364fd archives web component action dispatch correction
new 1df0857c476 plans versionless web component identity correction
new 7b9a7a2510d fixes versionless web component identity preparation
new 7237730fb43 archives versionless web component identity correction
new 7600721f28d plans web component union projection correction
new d0ea6ad465e fixes polymorphic GraphQL projections
new e7e2c9a5052 archives union projection correctness change
new 3b64c1793ab plans opaque bookmark route correction
new 1557ae96ff3 fixes long opaque bookmark routing
new e208807dd55 archives opaque bookmark route correction
new 2706330e906 plans paged reference autocomplete
new a50a842c00a adds paged GraphQL reference autocomplete
new 8743abdacd1 archives paged reference autocomplete change
The 15 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../core/config/CausewayConfiguration.java | 27 ++
.../.openspec.yaml | 2 +-
.../design.md | 119 ++++++
.../evidence/REPRODUCING.md | 62 +++
.../evidence/final-gate-results.md | 33 ++
.../evidence/implementation-report.md | 40 ++
.../evidence/production-isolation.md | 19 +
.../evidence/window-shape-matrix.md | 46 ++
.../proposal.md | 36 ++
.../specs/domain-web-components/spec.md | 35 ++
.../spec.md | 30 ++
.../spec.md | 71 +++
.../specs/vaadin-reference-widget-pilot/spec.md | 30 ++
.../tasks.md | 113 +++++
.../.openspec.yaml | 2 +-
.../design.md | 119 ++++++
.../evidence/REPRODUCING.md | 42 ++
.../evidence/final-gate-results.md | 25 ++
.../evidence/implementation-report.md | 37 ++
.../evidence/operation-shape-matrix.md | 44 ++
.../evidence/production-isolation.md | 15 +
.../proposal.md | 29 ++
.../specs/domain-web-components/spec.md | 97 +++++
.../tasks.md | 74 ++++
.../.openspec.yaml | 2 +-
.../design.md | 79 ++++
.../evidence/REPRODUCING.md | 52 +++
.../evidence/final-gate-results.md | 28 ++
.../evidence/implementation-report.md | 29 ++
.../evidence/production-isolation.md | 13 +
.../evidence/route-bound-matrix.md | 33 ++
.../proposal.md | 29 ++
.../generic-htmx-web-component-viewer/spec.md | 30 ++
.../spec.md | 25 ++
.../tasks.md | 66 +++
.../.openspec.yaml | 2 +-
.../design.md | 109 +++++
.../evidence/REPRODUCING.md | 60 +++
.../evidence/final-gate-results.md | 28 ++
.../evidence/implementation-report.md | 28 ++
.../evidence/production-isolation.md | 13 +
.../evidence/union-shape-matrix.md | 31 ++
.../proposal.md | 34 ++
.../specs/domain-web-components/spec.md | 45 ++
.../spec.md | 35 ++
.../spec.md | 20 +
.../tasks.md | 78 ++++
.../.openspec.yaml | 2 +-
.../design.md | 79 ++++
.../evidence/REPRODUCING.md | 53 +++
.../evidence/final-gate-results.md | 30 ++
.../evidence/implementation-report.md | 28 ++
.../evidence/metadata-shape-matrix.md | 47 ++
.../evidence/production-isolation.md | 11 +
.../proposal.md | 29 ++
.../specs/domain-web-components/spec.md | 35 ++
.../spec.md | 25 ++
.../tasks.md | 62 +++
.../planned-changes/web-component-viewer/README.md | 8 +-
.../web-component-viewer/vaadin-default-roadmap.md | 18 +-
openspec/specs/domain-web-components/spec.md | 187 +++++++-
.../generic-htmx-web-component-viewer/spec.md | 14 +-
.../spec.md | 111 +++++
.../spec.md | 19 +
.../spec.md | 77 ++++
.../specs/vaadin-reference-widget-pilot/spec.md | 35 +-
.../htmx/src/main/resources/application.properties | 4 +-
.../htmx/ReferenceAppHtmxPlaywrightTest.java | 161 +++++--
.../ReferenceAppCapabilityInventory_IntegTest.java | 10 +-
.../ReferenceAppHtmxApplication_IntegTest.java | 323 ++++++++++++++
.../inventory/ReferenceAppCapabilityInventory.java | 7 +
.../referenceapp/referenceapp-targets.json | 9 +-
.../ROOT/pages/setup-and-configuration.adoc | 12 +
.../viewer/graphql/model/domain/TypeNames.java | 14 +
...dering.java => AutoCompleteWindowOrdering.java} | 5 +-
.../domain/rich/query/RichActionParamsParam.java | 8 +
...> RichActionParamsParamAutoCompleteWindow.java} | 57 +--
.../domain/rich/query/RichAutoCompleteWindow.java | 167 ++++++++
.../model/domain/rich/query/RichProperty.java | 8 +
.../query/RichPropertyAutoCompleteWindow.java} | 61 ++-
...ava => InvalidAutoCompleteWindowException.java} | 4 +-
.../model/registry/GraphQLTypeRegistry.java | 38 +-
.../graphql/model/types/TypeMapperDefault.java | 18 +-
...va => AutoCompleteWindowConfigurationTest.java} | 15 +-
.../registry/GraphQLTypeRegistryUnionTest.java | 74 ++++
viewers/webcomponents/foundation/USAGE.adoc | 27 +-
.../foundation/src/action-dispatch.mjs | 217 ++++++++++
.../foundation/src/editor-registry.mjs | 5 +-
.../foundation/src/graphql-client.mjs | 5 +-
.../src/interaction-controller-element.mjs | 92 +++-
.../foundation/src/interaction-operations.mjs | 159 ++++++-
.../foundation/src/object-context-controller.mjs | 474 ++++++++++++++++-----
.../foundation/src/property-element.mjs | 77 +++-
.../foundation/src/reference-widget.mjs | 62 ++-
viewers/webcomponents/foundation/src/selection.mjs | 72 +++-
.../foundation/src/service-action-context.mjs | 206 ++++++---
.../foundation/test/action-dispatch.test.mjs | 218 ++++++++++
.../test/application-menu-client.test.mjs | 35 ++
.../foundation/test/collection.test.mjs | 270 +++++++++++-
.../test/fixtures/menu-graphql-fixture.mjs | 53 ++-
.../test/fixtures/rich-schema-fixture.mjs | 55 +++
.../foundation/test/graphql-client.test.mjs | 20 +
.../foundation/test/identity-selection.test.mjs | 109 +++++
.../foundation/test/interaction-command.test.mjs | 215 ++++++++++
.../foundation/test/interaction.test.mjs | 161 +++++++
.../foundation/test/object-context.test.mjs | 25 ++
.../foundation/test/selection.test.mjs | 49 ++-
viewers/webcomponents/htmx/README.adoc | 10 +-
.../viewer/webcomponents/htmx/HtmxRouteCodec.java | 8 +-
.../resources/causeway-htmx/route-policy.mjs | 45 +-
.../webcomponents/htmx/HtmxRouteCodecTest.java | 33 +-
.../htmx/HtmxViewerControllerTest.java | 24 ++
.../webcomponents/htmx/test/route-policy.test.mjs | 15 +-
.../petclinic/PetClinicHtmxPlaywrightTest.java | 10 +-
114 files changed, 6213 insertions(+), 419 deletions(-)
copy openspec/changes/archive/{2026-08-04-reconcile-command-recording-core-policy => 2026-08-24-add-paged-graphql-reference-autocomplete}/.openspec.yaml (50%)
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/design.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/implementation-report.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/production-isolation.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/proposal.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/domain-web-components/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/reference-application-viewer-regression-suite/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/vaadin-reference-widget-pilot/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/tasks.md
copy openspec/changes/archive/{2026-08-04-reconcile-command-recording-core-policy => 2026-08-24-fix-webcomponent-action-dispatch-correctness}/.openspec.yaml (50%)
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/design.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/REPRODUCING.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/final-gate-results.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/implementation-report.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/operation-shape-matrix.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/production-isolation.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/proposal.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/specs/domain-web-components/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/tasks.md
copy openspec/changes/archive/{2026-08-04-reconcile-command-recording-core-policy => 2026-08-24-fix-webcomponent-opaque-route-correctness}/.openspec.yaml (50%)
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/design.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/REPRODUCING.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/final-gate-results.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/implementation-report.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/production-isolation.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/route-bound-matrix.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/proposal.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/specs/generic-htmx-web-component-viewer/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/specs/reference-application-viewer-regression-suite/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/tasks.md
copy openspec/changes/archive/{2026-08-04-reconcile-command-recording-core-policy => 2026-08-24-fix-webcomponent-union-projection-correctness}/.openspec.yaml (50%)
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/design.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/REPRODUCING.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/final-gate-results.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/implementation-report.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/production-isolation.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/union-shape-matrix.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/proposal.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/specs/domain-web-components/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/specs/rich-graphql-object-interaction-correctness/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/tasks.md
copy openspec/changes/archive/{2026-08-04-reconcile-command-recording-core-policy => 2026-08-24-fix-webcomponent-versionless-identity-preparation}/.openspec.yaml (50%)
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/design.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/REPRODUCING.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/final-gate-results.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/implementation-report.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/metadata-shape-matrix.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/production-isolation.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/proposal.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/specs/domain-web-components/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/specs/reference-application-viewer-regression-suite/spec.md
create mode 100644 openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/tasks.md
create mode 100644 openspec/specs/rich-graphql-reference-autocomplete-windowing/spec.md
copy viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/{CollectionWindowOrdering.java => AutoCompleteWindowOrdering.java} (93%)
copy viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/{RichActionParamsParamDefault.java => RichActionParamsParamAutoCompleteWindow.java} (61%)
create mode 100644 viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichAutoCompleteWindow.java
copy viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/{simple/query/SimplePropertyLobAbstract.java => rich/query/RichPropertyAutoCompleteWindow.java} (56%)
copy viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/exceptions/{InvalidCollectionWindowException.java => InvalidAutoCompleteWindowException.java} (86%)
copy viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/{CollectionWindowConfigurationTest.java => AutoCompleteWindowConfigurationTest.java} (78%)
create mode 100644 viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java
create mode 100644 viewers/webcomponents/foundation/src/action-dispatch.mjs
create mode 100644 viewers/webcomponents/foundation/test/action-dispatch.test.mjs
create mode 100644 viewers/webcomponents/foundation/test/identity-selection.test.mjs
(causeway) 07/15: plans web component union projection correction
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit 7600721f28da606150c98cbfd68900518115623c
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 12:31:20 2026 +0100
plans web component union projection correction
---
.../.openspec.yaml | 2 +
.../design.md | 91 ++++++++++++++++++++++
.../proposal.md | 31 ++++++++
.../specs/domain-web-components/spec.md | 45 +++++++++++
.../spec.md | 30 +++++++
.../tasks.md | 76 ++++++++++++++++++
6 files changed, 275 insertions(+)
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/.openspec.yaml b/openspec/changes/fix-webcomponent-union-projection-correctness/.openspec.yaml
new file mode 100644
index 00000000000..4102db8a47b
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-08-24
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/design.md b/openspec/changes/fix-webcomponent-union-projection-correctness/design.md
new file mode 100644
index 00000000000..5cac1a39934
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/design.md
@@ -0,0 +1,91 @@
+## Context
+
+Rich GraphQL represents values declared by abstract domain types as GraphQL unions with advertised `possibleTypes`.
+GraphQL permits `__typename` directly on a union, but concrete metadata and members must be selected inside `... on ConcreteType` fragments.
+The foundation selection tree and executable renderer currently represent fields and arguments only, so `resultSelectionForType(...)` falls back to `__typename` and abstract collections are rejected locally.
+
+The pinned Reference Application exposes raw-list collection fixtures through `rich__demo_ValueHolder__gqlv_union`.
+The runtime rows are concrete `demo.CollectionTypeOfChildVm` objects with valid metadata, but the viewer cannot select that metadata without fragments.
+A broad union can advertise many possible domain types, so blindly expanding every possible type would create large operations and excessive introspection.
+Mutating actions must never be executed once to discover a result type and again to obtain its value.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- Render schema-validated inline fragments through the internal selection model.
+- Describe advertised concrete possible types and their metadata without application-specific type lists.
+- Project bounded small unions directly.
+- Probe broad abstract collection rows with `__typename` and replay the same side-effect-free window or list read once using fragments for observed concrete types.
+- Merge concrete row metadata and supported requested columns and preserve hydration coverage.
+- Retain cancellation, stale-response, lazy activation, windowing, partial errors, and bounded operation policy.
+- Prove the Reference Application polymorphic collection without changing public GraphQL or component contracts.
+
+**Non-Goals:**
+
+- Repeating mutating actions or property mutations to discover result types.
+- Adding GraphQL schema fields, changing union membership, or changing Causeway metamodel type inference.
+- Providing sorting, filtering, paging beyond existing windows, or unbounded fragment expansion.
+- Correcting opaque route encoding or long composite bookmark handling.
+- Changing action dispatch, value codecs, Vaadin adapters, dependencies, CSP, or public events.
+
+## Decisions
+
+### Add a reserved inline-fragment selection node
+
+Internal selections will represent fragments under a reserved `__fragments` map keyed by advertised concrete GraphQL type name.
+Each fragment contains an ordinary nested selection and the renderer always includes `__typename` alongside fragments.
+The renderer validates that the parent is an interface or union, the fragment name is advertised by `possibleTypes`, the concrete type is described, and every nested field is valid before emitting `... on Type { ... }`.
+
+The rejected alternative is accepting raw GraphQL fragment strings, because that would bypass name validation, type validation, deterministic rendering, merge logic, and operation diagnostics.
+
+### Bound direct expansion
+
+`resultSelectionForType(...)` may directly expand an abstract type only when the advertised possible-type count is within a documented internal limit and the required concrete descriptions are available.
+The fragment for each concrete object uses the existing advertised metadata-selection policy, with `__typename` retained when metadata is unavailable.
+A larger or incomplete union remains typename-only unless a side-effect-free collection planner can narrow it from observed rows.
+
+The rejected alternative is expanding every possible type, because broad domain unions can make request and introspection cost proportional to the complete metamodel.
+
+### Probe and replay broad collection reads once
+
+An activated abstract collection first performs the same bounded list or window operation with `__typename` only.
+The context collects the distinct observed type names, rejects names not advertised by the union, enforces a maximum observed-type count, describes those concrete types and required metadata or column wrappers, and then reissues the same side-effect-free collection operation once with concrete fragments.
+Only the second result becomes the published row state.
+Existing request generations, abort signals, window arguments, ordering, and stale-response checks cover both stages.
+
+If the replay contains a row type not observed by the probe, that row remains typename-only and is reported as a bounded partial projection rather than triggering an unbounded retry loop.
+The rejected alternative is recursive probing until all races disappear, because changing collections could produce unbounded requests.
+
+### Build concrete row fragments from advertised fields
+
+Each observed concrete row fragment selects its advertised metadata subset and only requested semantic column wrappers present on that concrete type.
+Wrapper and nested output types are described through the existing one-type introspection cache before operation rendering.
+Rows with `id` and `logicalTypeName` use existing object-link and hydrated-context behavior.
+Columns absent from one concrete type become local missing cells rather than invalidating other types.
+
+### Keep non-repeatable outcomes bounded
+
+Small action or property union outputs can use direct advertised fragments when their type closure is already bounded and described.
+A broad mutating action result remains typename-only and successful rather than being invoked twice.
+The semantic result does not invent identity when the returned projection lacks metadata.
+
+### Preserve opaque-route separation
+
+Concrete union rows may expose long opaque identifiers.
+This change publishes the existing semantic navigation event with the exact returned identifier but does not alter route encoding, decoding, limits, or the retained `invalid-route` assertion.
+
+## Risks / Trade-offs
+
+- [Probe and replay observe different collection contents] → Reuse identical window arguments, limit execution to one replay, and mark unprojected replay types locally.
+- [A broad union creates excessive introspection] → Introspect only distinct observed types and enforce fixed type and fragment limits.
+- [Fragment selections break selection merging or hydration coverage] → Extend merge, difference, and coverage helpers with focused nested-fragment tests.
+- [One concrete type lacks a requested column] → Omit that column from its fragment and preserve rows from other concrete types.
+- [A malicious or stale typename is returned] → Require exact membership in the introspected possible-type set before constructing a fragment.
+- [Action semantics are accidentally repeated] → Restrict probe/replay to side-effect-free object and collection reads and test that mutation execution remains single-shot.
+
+## Migration Plan
+
+The change is an internal operation-planning correction with no persisted-data or server-schema migration.
+Deploy through the existing same-origin foundation artifact and qualify ordinary concrete collections, small unions, broad polymorphic collections, and mutating action outcomes.
+Rollback is a source revert with no route, configuration, dependency, or asset migration.
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/proposal.md b/openspec/changes/fix-webcomponent-union-projection-correctness/proposal.md
new file mode 100644
index 00000000000..4d9669ea854
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/proposal.md
@@ -0,0 +1,31 @@
+## Why
+
+The pinned Reference Application exposes abstract property and collection values through GraphQL unions such as `rich__demo_ValueHolder__gqlv_union`.
+The generic web-component viewer cannot currently render valid inline fragments for those unions, so it either submits invalid `_meta` selections or stops at a bounded abstract-row error instead of presenting the concrete objects returned by GraphQL.
+
+## What Changes
+
+- Extend targeted introspection to retain advertised union and interface possible types and describe only the concrete types needed by an executable projection.
+- Add an internal selection representation and renderer for validated GraphQL inline fragments with `__typename` discrimination.
+- Project small bounded abstract result sets directly through advertised concrete fragments.
+- Resolve broad abstract collection reads through a bounded side-effect-free typename probe followed by one concrete-fragment read for observed types.
+- Preserve a bounded typename-only outcome when a safe concrete projection cannot be planned, and never repeat a mutating action to discover its result type.
+- Normalize concrete rows and values through existing metadata, identity, hydration, rendering, error, cancellation, and stale-response contracts.
+- Add focused foundation and pinned Reference Application coverage while retaining the separate opaque-route gap.
+- Keep GraphQL schema changes, action placement, paging, Vaadin policy, and route encoding outside this change.
+
+## Capabilities
+
+### New Capabilities
+
+None.
+
+### Modified Capabilities
+
+- `domain-web-components`: Require valid bounded inline-fragment projection and concrete semantic normalization for advertised union and interface values.
+- `reference-application-viewer-regression-suite`: Require successful representative polymorphic property and collection journeys without invalid direct union metadata selection.
+
+## Impact
+
+The change affects internal targeted introspection, executable selection rendering, abstract property and collection read planning, action-result projection policy, row hydration coverage, and the pinned Reference Application regression suite.
+Public Causeway elements, semantic events, GraphQL fields and generated names, canonical routes, HTMX lifecycle, dependencies, Vaadin qualification policy, CSP inputs, and production asset URLs remain unchanged.
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/specs/domain-web-components/spec.md b/openspec/changes/fix-webcomponent-union-projection-correctness/specs/domain-web-components/spec.md
new file mode 100644
index 00000000000..dc5a87a8201
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/specs/domain-web-components/spec.md
@@ -0,0 +1,45 @@
+## ADDED Requirements
+
+### Requirement: Bounded polymorphic value projection
+The component library SHALL derive valid inline-fragment selections for advertised GraphQL interface and union values without selecting concrete fields directly on the abstract type.
+It MUST validate fragment membership and nested fields through targeted introspection, MUST bound fragment and introspection cost, and MUST NOT repeat a mutating interaction to discover its result type.
+
+#### Scenario: Small abstract result has described possible types
+- **WHEN** an interface or union advertises a bounded set of described concrete object types
+- **THEN** the operation selects `__typename` and valid inline fragments for those advertised types
+- **AND** each fragment requests only metadata and children valid for its concrete type
+
+#### Scenario: Broad collection union is activated
+- **WHEN** an activated side-effect-free collection exposes an abstract row type whose complete possible-type set exceeds the direct expansion limit
+- **THEN** the context issues one bounded typename-only probe and describes only distinct observed advertised concrete types
+- **AND** reissues the same list or window read once with valid fragments for those types
+
+#### Scenario: Polymorphic rows expose common identity
+- **WHEN** concrete fragment results contain `id` and `logicalTypeName`
+- **THEN** each row retains its exact typename, metadata, semantic object link, and hydrated row context
+- **AND** optional title and version behavior follows the concrete metadata type
+
+#### Scenario: Requested column differs by concrete type
+- **WHEN** a declared semantic column is present on some observed concrete types and absent on another
+- **THEN** each fragment includes the column only where its wrapper and child selection are advertised
+- **AND** the missing cell remains local without invalidating successfully projected rows
+
+#### Scenario: Replay returns an unobserved concrete type
+- **WHEN** a collection changes between typename probe and fragment replay and returns an advertised type not included in the replay fragments
+- **THEN** that row remains bounded to its available typename projection and is reported locally
+- **AND** the context does not enter an unbounded probe loop
+
+#### Scenario: Returned typename is not advertised
+- **WHEN** a response typename is not an advertised possible type of the abstract field
+- **THEN** the context rejects it as a bounded schema mismatch
+- **AND** does not construct or submit a fragment from that value
+
+#### Scenario: Broad mutating action result
+- **WHEN** a mutating action returns an abstract type that cannot be projected within the direct fragment bound
+- **THEN** the action executes exactly once and retains its successful bounded typename-only outcome
+- **AND** the controller does not invent navigable identity or repeat the mutation
+
+#### Scenario: Polymorphic request becomes obsolete
+- **WHEN** a probe or fragment replay belongs to a disconnected, cancelled, or superseded collection generation
+- **THEN** its remaining work is aborted or discarded
+- **AND** it cannot replace the current row state
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md b/openspec/changes/fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md
new file mode 100644
index 00000000000..ab25a67ef97
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md
@@ -0,0 +1,30 @@
+## ADDED Requirements
+
+### Requirement: Polymorphic projection regression coverage
+The pinned Reference Application suite SHALL exercise representative abstract property and collection values through valid concrete GraphQL fragments.
+It MUST preserve deterministic concrete-row identity and member evidence, bounded partial behavior, and the separate opaque-route gap.
+
+#### Scenario: Type-of collection is activated
+- **WHEN** the browser activates the representative `demo.CollectionTypeOfPage` collection exposed through `rich__demo_ValueHolder__gqlv_union`
+- **THEN** the viewer reaches a supported ready or documented partial state without selecting `_meta` directly on the union
+- **AND** concrete `demo.CollectionTypeOfChildVm` rows render their semantic identities and advertised values
+
+#### Scenario: Raw collection lacks a declared Java generic
+- **WHEN** the companion collection relies on runtime union typenames rather than a Java generic signature
+- **THEN** the same bounded probe and fragment policy applies
+- **AND** no application-specific concrete-type list is embedded in the viewer
+
+#### Scenario: Polymorphic operation remains bounded
+- **WHEN** the Reference Application union advertises more possible types than are present in one collection window
+- **THEN** evidence records the advertised count, observed concrete types, introspection operations, and final fragment operation
+- **AND** the viewer describes and selects only the bounded required concrete closure
+
+#### Scenario: Existing collection behavior remains stable
+- **WHEN** the full collection journey also reaches concrete versionless rows, configured columns, lazy tabs, stale windows, partial errors, and route replacement
+- **THEN** those established behaviors retain their passing assertions
+- **AND** polymorphic probing does not make inactive collections eager
+
+#### Scenario: Opaque composite route remains separate
+- **WHEN** a projected concrete result carries the long opaque identifier retained by the corpus
+- **THEN** the suite continues to assert the focused `invalid-route` gap
+- **AND** does not attribute route rejection to union projection
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/tasks.md b/openspec/changes/fix-webcomponent-union-projection-correctness/tasks.md
new file mode 100644
index 00000000000..bd4de36f1ae
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/tasks.md
@@ -0,0 +1,76 @@
+## 1. Capture executable union evidence
+
+- [ ] 1.1 Capture targeted introspection for `rich__demo_ValueHolder__gqlv_union`, its advertised possible-type count, and representative concrete metadata.
+- [ ] 1.2 Execute typename-only and concrete-fragment operations for both `demo.CollectionTypeOfPage` collections.
+- [ ] 1.3 Record invalid direct union metadata selection and the retained opaque-route gap.
+
+## 2. Extend the internal selection model
+
+- [ ] 2.1 Define a reserved deterministic inline-fragment selection node.
+- [ ] 2.2 Render `__typename` and sorted `... on Type` fragments with GraphQL-name validation.
+- [ ] 2.3 Reject fragment names not advertised by a union or interface.
+- [ ] 2.4 Validate each fragment against its described concrete type and nested fields.
+- [ ] 2.5 Extend selection merge, difference, emptiness, and coverage helpers for fragments.
+- [ ] 2.6 Preserve scalar, enum, concrete object, resource, and argument rendering behavior.
+
+## 3. Describe bounded concrete type closures
+
+- [ ] 3.1 Add helpers that expose advertised abstract possible-type names deterministically.
+- [ ] 3.2 Describe observed concrete object types and metadata through cached one-type introspection.
+- [ ] 3.3 Describe only requested concrete member wrappers and nested result types needed by row columns.
+- [ ] 3.4 Enforce fixed direct-fragment and observed-type limits.
+- [ ] 3.5 Reject returned typenames absent from the advertised possible-type set.
+- [ ] 3.6 Preserve GraphQL Java good-faith introspection behavior.
+
+## 4. Plan abstract result selections
+
+- [ ] 4.1 Build direct inline fragments for bounded fully described unions and interfaces.
+- [ ] 4.2 Retain typename-only projection when direct expansion is incomplete or exceeds the bound.
+- [ ] 4.3 Select each concrete metadata subset through the existing version-aware helper.
+- [ ] 4.4 Preserve single-shot execution for mutating action results.
+- [ ] 4.5 Normalize concrete fragment results without inventing identity for typename-only values.
+
+## 5. Add polymorphic collection probe and replay
+
+- [ ] 5.1 Replace the abstract-row rejection with a typename-only list or window probe.
+- [ ] 5.2 Collect distinct observed advertised concrete types under the configured bound.
+- [ ] 5.3 Build and execute one concrete-fragment replay with identical collection arguments.
+- [ ] 5.4 Include requested columns only where each concrete type advertises the member wrapper.
+- [ ] 5.5 Publish only the replay result while retaining probe and replay operation evidence.
+- [ ] 5.6 Preserve lazy activation, caching, window state, ordering, cancellation, stale generations, and route disposal.
+- [ ] 5.7 Report replay rows with unobserved typenames as bounded partial projections without retry loops.
+- [ ] 5.8 Preserve hydrated-row coverage using the matching concrete fragment selection.
+
+## 6. Add focused foundation coverage
+
+- [ ] 6.1 Add inline-fragment rendering, ordering, validation, merge, and difference tests.
+- [ ] 6.2 Add small-union direct selection and broad-union typename fallback tests.
+- [ ] 6.3 Add abstract legacy-list and bounded-window probe and replay tests.
+- [ ] 6.4 Add mixed concrete row, missing column, unadvertised typename, and changed replay type tests.
+- [ ] 6.5 Add cancellation, stale response, cache, and inactive collection tests for two-stage reads.
+- [ ] 6.6 Add single-shot mutating abstract action-result coverage.
+
+## 7. Qualify against the pinned Reference Application
+
+- [ ] 7.1 Add or refine deterministic target-catalogue entries for declared and runtime polymorphic collections.
+- [ ] 7.2 Add integration assertions for union possible types, invalid direct selection, probe typenames, and valid observed fragments.
+- [ ] 7.3 Convert polymorphic browser assertions to successful concrete row identity and value behavior where supported.
+- [ ] 7.4 Preserve concrete versionless rows, configured collections, partial errors, lazy tabs, stale windows, and route replacement.
+- [ ] 7.5 Preserve the explicit opaque composite `invalid-route` assertion.
+- [ ] 7.6 Update capability inventory classifications only where executable evidence changes.
+- [ ] 7.7 Verify clean and incremental inventory generation remain byte-identical.
+
+## 8. Document compatibility and isolation
+
+- [ ] 8.1 Document fragment selection grammar, bounds, probe/replay behavior, and non-repeatable outcome policy.
+- [ ] 8.2 Record representative introspection and operation evidence with reproducible commands.
+- [ ] 8.3 Verify no public GraphQL, Causeway element, event, route, HTMX, Vaadin, dependency, CSP, or asset-policy contract changes.
+
+## 9. Run final qualification gates
+
+- [ ] 9.1 Run the complete foundation Node suite and web-component foundation and HTMX Maven tests.
+- [ ] 9.2 Run relevant GraphQL model and integration tests.
+- [ ] 9.3 Run the full Petclinic integration and Playwright suites.
+- [ ] 9.4 Run the Reference Application clean package, integration, capability inventory, and Playwright suites.
+- [ ] 9.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
+- [ ] 9.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
(causeway) 13/15: plans paged reference autocomplete
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit 2706330e9066dd2b144a6718a22015c0e6feaf4f
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 15:01:33 2026 +0100
plans paged reference autocomplete
---
.../.openspec.yaml | 2 +
.../design.md | 119 +++++++++++++++++++++
.../proposal.md | 36 +++++++
.../specs/domain-web-components/spec.md | 35 ++++++
.../spec.md | 30 ++++++
.../spec.md | 71 ++++++++++++
.../specs/vaadin-reference-widget-pilot/spec.md | 30 ++++++
.../tasks.md | 113 +++++++++++++++++++
.../planned-changes/web-component-viewer/README.md | 2 +-
.../web-component-viewer/vaadin-default-roadmap.md | 2 +-
10 files changed, 438 insertions(+), 2 deletions(-)
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/.openspec.yaml b/openspec/changes/add-paged-graphql-reference-autocomplete/.openspec.yaml
new file mode 100644
index 00000000000..4102db8a47b
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-08-24
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/design.md b/openspec/changes/add-paged-graphql-reference-autocomplete/design.md
new file mode 100644
index 00000000000..0c14b4da6da
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/design.md
@@ -0,0 +1,119 @@
+## Context
+
+Rich property and action-parameter wrappers currently expose `autoComplete(search)` as an unbounded list-valued field.
+Causeway's metamodel autocomplete semantics return an authoritative ordered collection but do not expose persistence-level offset, cursor, count, or snapshot APIs.
+The foundation client therefore downloads the complete list, and property and action controllers reject it when it exceeds `referenceMaximumResults`.
+The internal Vaadin adapter assigns a finite `items` array and locally slices it, which is correctly documented as presentation bounding rather than server paging.
+
+This change adds a public GraphQL response-window contract without pretending that domain autocomplete itself performs query pushdown.
+Each request invokes the existing authorized Causeway semantic once, materializes that request's result, preserves its encounter order, and returns only the requested response slice plus count and continuation metadata.
+That bounds browser transfer and enables Vaadin's lazy data-provider protocol while preserving backward compatibility.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- Add discoverable bounded offset windows beside existing property and action-parameter autocomplete fields.
+- Bound every response using GraphQL configuration and validate offset and size before invoking autocomplete.
+- Preserve authorized application encounter order, argument dependencies, semantic identity, cancellation, and per-request consistency.
+- Let object and service contexts prefer windows and normalize legacy fallback honestly.
+- Let Vaadin Combo Box request later pages without application-facing Vaadin APIs or local truncation.
+- Keep native editors usable with a bounded first page and an explicit additional-results/refine indication.
+- Exercise later-window selection against deterministic Reference Application data.
+
+**Non-Goals:**
+
+- Do not claim database query pushdown, cursor stability, transaction snapshots across requests, or stable ordering across domain-state changes.
+- Do not remove or alter `autoComplete(search)`.
+- Do not introduce collection Grid sorting/filtering, Flow, Binder, Java `DataProvider`, Pro components, telemetry, CDN assets, or raw application-facing Vaadin elements.
+- Do not change validation, mutation, action invocation, routes, identity, CSP, native fallback, or default toolkit policy.
+
+## Decisions
+
+### Add sibling `autoCompleteWindow` fields
+
+Every rich property or action parameter that advertises `autoComplete` also advertises:
+
+`autoCompleteWindow(search: String!, offset: Int! = 0, size: Int! = <configured default>)`.
+
+The result is a generated member-specific object containing `items`, `offset`, `requestedSize`, `returnedCount`, `totalCount`, `maximumSize`, `hasPrevious`, `hasNext`, and `ordering`.
+Member-specific output types preserve the exact existing item output type, including concrete, abstract, enum, scalar, and versionless metadata behavior.
+The existing list field remains byte-for-byte compatible.
+
+A top-level generic autocomplete endpoint was rejected because property and action-parameter semantics require their current source object, authorization, and preceding arguments.
+Replacing the old field was rejected because it would break existing documents.
+
+### Use bounded offset windows and application encounter order
+
+GraphQL configuration gains `autocomplete.default-window-size` and `autocomplete.max-window-size`, defaulting to 20 and 100.
+Offset must be non-negative, size positive, and size no greater than the configured maximum.
+Validation occurs before invoking the domain autocomplete semantic.
+
+One request invokes the existing autocomplete semantic once, copies its encounter order, calculates total count, and returns an immutable sub-list.
+`ordering` is `APPLICATION`, meaning the application-provided encounter order is authoritative for that execution.
+No cross-request snapshot is promised; clients restart at offset zero whenever filter text or dependent arguments change.
+
+Sorting by title or bookmark was rejected because it would destroy application relevance ordering and may invoke additional semantics.
+Cursor tokens were rejected because the metamodel provides neither a stable cursor nor a snapshot from which an honest token could be derived.
+Calling the domain method repeatedly to skip rows was rejected because it would add cost without improving consistency.
+
+### Share server construction and result normalization
+
+Property and action-parameter window elements use one package-local builder and slicing utility for arguments, result type fields, validation, metadata, and immutable result maps.
+Generated type names extend the existing property or parameter type name with `_autocomplete_window`.
+A dedicated safe exception reports invalid windows without including search text, preceding arguments, identities, or returned values.
+
+Foundation contexts add window methods rather than changing list-returning methods.
+They inspect `autoCompleteWindow`, describe its generated result and `items` type, issue only advertised fields, and normalize the result to one immutable semantic window shape.
+When the sibling field is absent they invoke legacy autocomplete once and return a marked legacy window only if the existing result bound is respected.
+
+### Separate filter generations from page requests
+
+A filter generation owns one search text and current dependent-argument snapshot.
+Changing either aborts every outstanding page request, clears accumulated pages, and starts at offset zero.
+Pages in one generation may complete out of order but are applied only to their requested offsets after generation, connection, route, prompt, and abort checks.
+Duplicate page requests share or supersede an offset-scoped request rather than appending duplicate items.
+Selection is reconciled by semantic identity and is not discarded merely because its page is not currently loaded.
+
+The normalized window includes total and continuation metadata, so native presentation can state that more matches exist without pretending its first-page datalist is complete.
+
+### Use Vaadin's lazy data-provider callback internally
+
+When window capability is advertised, the internal reference editor configures Combo Box page size and data provider.
+The callback dispatches an internal composed request carrying filter, offset, size, and a one-shot responder.
+The owning Causeway property or action controller performs the semantic context command and returns normalized items and total count.
+The adapter invokes Vaadin's callback only while connected and within the same filter generation.
+
+When only legacy autocomplete is available, the adapter retains the established finite-items behavior and visible over-bound refine/fallback policy.
+Applications continue to see Causeway pending values and semantic events only.
+
+Local slicing under a Vaadin callback was rejected because it would recreate the false paging behavior this change removes.
+Exposing the Vaadin data provider to applications was rejected because it would breach the stable Causeway boundary.
+
+### Qualify with bounded deterministic Reference Application pages
+
+The Reference Application uses its existing deterministic 13-character autocomplete set with a qualification page size below the total.
+Integration tests request at least three windows, verify non-overlap, order, counts, boundaries, dependent arguments, invalid sizes, and selection identity.
+Browser tests search, request a later page through the internal adapter, select an item not present in the first page, validate or submit it, and exercise filter supersession and route disposal.
+
+This is deliberately larger than the configured qualification page, not represented as a large persistence query benchmark.
+
+## Risks / Trade-offs
+
+- [The server still materializes the complete domain result per page request] → State this explicitly, bound response transfer, preserve the application semantic, and defer backend pushdown until a public metamodel contract exists.
+- [Application order can change between page requests] → Declare request consistency rather than snapshot consistency and restart paging when filter or dependent arguments change.
+- [Window metadata adds generated schema types] → Use deterministic member-specific names, registry deduplication, and targeted introspection.
+- [Vaadin callback races route or prompt disposal] → Use abort signals, filter generations, offset request keys, connection checks, and one-shot responders.
+- [Legacy servers remain unpaged] → Preserve the current bound and honest refine/fallback state without truncation.
+- [A low configured maximum could make the UI chatty] → Provide separate default and maximum values and let the adapter request an accepted page size.
+
+## Migration Plan
+
+Ship additive GraphQL fields and client discovery together.
+Existing clients continue using `autoComplete` unchanged.
+New clients prefer windows when advertised and degrade to legacy bounded behavior otherwise.
+Rollback removes client preference and new fields without data, route, application, or persisted-state migration.
+
+## Open Questions
+
+None.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/proposal.md b/openspec/changes/add-paged-graphql-reference-autocomplete/proposal.md
new file mode 100644
index 00000000000..0de9514c0a9
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/proposal.md
@@ -0,0 +1,36 @@
+## Why
+
+The current public rich GraphQL autocomplete field returns one unpaged list with no requested size, total, continuation, or ordering metadata.
+The web-component client correctly rejects responses above its configured bound, but that safe failure prevents reference selection from scaling beyond small result sets and blocks a truthful Vaadin-default rollout.
+
+## What Changes
+
+- Add backward-compatible `autoCompleteWindow(search, offset, size)` fields beside existing property and action-parameter `autoComplete(search)` fields.
+- Return bounded window metadata including items, requested offset and size, returned count, total count, configured maximum, previous/next availability, and the declared application encounter-order policy.
+- Configure a GraphQL default window size and hard maximum, validate requests before slicing, and keep every response bounded.
+- Invoke the authoritative Causeway autocomplete semantic once per request, preserve its authorized encounter order, and slice only the response window; explicitly do not claim persistence/query pushdown or a cross-request snapshot.
+- Preserve preceding action-parameter dependencies, object identity, advertised metadata, protected-value handling, cancellation, and per-request consistency.
+- Keep existing non-window autocomplete fields unchanged for current clients.
+- Make semantic property, object-action, and service-action contexts discover and prefer the window capability while retaining the old bounded refine-search fallback on older servers.
+- Add generation-safe overlapping search and page requests so filter changes, route replacement, prompt closure, and disconnect cannot publish stale items.
+- Connect the internal Vaadin Combo Box data-provider callback to real GraphQL windows instead of locally slicing a complete result.
+- Keep native editors functional with a bounded first window and an honest refine-search indication when additional results exist.
+- Qualify deterministic Reference Application result sets larger than the configured client page and verify selection from a later window.
+
+## Capabilities
+
+### New Capabilities
+
+- `rich-graphql-reference-autocomplete-windowing`: Defines discoverable bounded server-side response windows for property and action-parameter reference autocomplete.
+
+### Modified Capabilities
+
+- `domain-web-components`: Allows semantic reference editors to request and consume authoritative autocomplete windows while preserving Causeway-owned pending values, validation, events, cancellation, and fallback.
+- `vaadin-reference-widget-pilot`: Replaces local presentation slicing with a lazy internal data provider backed by advertised GraphQL windows.
+- `reference-application-viewer-regression-suite`: Adds deterministic multi-window property or parameter autocomplete coverage and later-window selection.
+
+## Impact
+
+The change affects GraphQL configuration, generated rich property and action-parameter types, output type naming and discovery, autocomplete data fetchers, foundation object and service contexts, property and action controllers, the internal Vaadin adapter, native fallback presentation, documentation, and regression fixtures.
+It adds public GraphQL fields and types without changing existing operation shapes.
+It adds no dependency, Pro component, Flow API, application-facing Vaadin element, collection Grid sorting/filtering contract, or persistence query-pushdown claim.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/specs/domain-web-components/spec.md b/openspec/changes/add-paged-graphql-reference-autocomplete/specs/domain-web-components/spec.md
new file mode 100644
index 00000000000..5beb6b8e8e7
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/specs/domain-web-components/spec.md
@@ -0,0 +1,35 @@
+## ADDED Requirements
+
+### Requirement: Semantic autocomplete window consumption
+Semantic property and action-parameter editors SHALL prefer an advertised rich GraphQL autocomplete window while preserving Causeway-owned pending values, validation, semantic events, cancellation, and toolkit neutrality.
+They MUST retain a bounded honest fallback when the server exposes only legacy autocomplete.
+
+#### Scenario: Windowed property search begins
+- **WHEN** an editable reference property advertises `autoCompleteWindow` and the search reaches its minimum length
+- **THEN** the property context requests offset zero with a bounded page size
+- **AND** publishes the returned items and continuation metadata only for the current filter generation
+
+#### Scenario: Windowed action parameter depends on earlier values
+- **WHEN** an object or service action parameter requests a page using current preceding arguments
+- **THEN** the semantic context sends only arguments declared by the advertised window field
+- **AND** changing an earlier value invalidates outstanding pages and restarts the affected search at offset zero
+
+#### Scenario: Later page is requested
+- **WHEN** the active semantic editor requests an offset not yet loaded for the current filter
+- **THEN** the context obtains that authoritative server window without downloading or locally slicing the complete result
+- **AND** semantic identities deduplicate items at their requested positions
+
+#### Scenario: Window request becomes obsolete
+- **WHEN** filter text, dependent arguments, prompt state, route generation, connection, or component lifetime supersedes an outstanding page
+- **THEN** the request is aborted or ignored
+- **AND** stale items, totals, validation, selection, focus, and errors cannot replace current state
+
+#### Scenario: Native editor receives a partial first window
+- **WHEN** native fallback presentation has items with `hasNext` true
+- **THEN** it exposes the bounded current choices and an accessible additional-results or refine-search indication
+- **AND** does not claim the first window is the complete result
+
+#### Scenario: Server has only legacy autocomplete
+- **WHEN** targeted introspection finds `autoComplete` but no `autoCompleteWindow`
+- **THEN** the context uses the existing single-response operation within its configured bound
+- **AND** an over-bound response retains the established visible limitation state without silent truncation
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/specs/reference-application-viewer-regression-suite/spec.md b/openspec/changes/add-paged-graphql-reference-autocomplete/specs/reference-application-viewer-regression-suite/spec.md
new file mode 100644
index 00000000000..f1f6c170631
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/specs/reference-application-viewer-regression-suite/spec.md
@@ -0,0 +1,30 @@
+## ADDED Requirements
+
+### Requirement: Multi-window reference autocomplete regression coverage
+The pinned Reference Application suite SHALL exercise deterministic rich autocomplete results larger than its configured qualification page for property or action-parameter reference selection.
+It MUST cover GraphQL metadata, later-window selection, argument dependencies, cancellation, legacy compatibility, and toolkit-neutral outcomes.
+
+#### Scenario: GraphQL autocomplete spans several windows
+- **WHEN** a deterministic search returns more references than the configured page size
+- **THEN** adjacent windows report accurate items, offsets, counts, totals, maximum, ordering, and continuation state
+- **AND** their combined authoritative encounter order contains no omitted or duplicated position
+
+#### Scenario: Invalid window is requested
+- **WHEN** qualification requests a negative offset, non-positive size, or size above the configured maximum
+- **THEN** GraphQL returns a bounded non-disclosing error
+- **AND** existing legacy autocomplete remains executable
+
+#### Scenario: Browser selects a later-window reference
+- **WHEN** the reference editor searches and requests an item absent from the first window
+- **THEN** the internal adapter obtains the later server window and selection preserves the item's semantic identity
+- **AND** validation or submission uses the existing Causeway interaction contract
+
+#### Scenario: Search generation is superseded
+- **WHEN** the browser changes filter or dependent parameter values while a page is in flight or replaces the route
+- **THEN** obsolete pages cannot alter suggestions, total count, selection, error, focus, or current route state
+- **AND** no unexpected GraphQL, console, page, CSP, external-request, accessibility, or overflow failure occurs
+
+#### Scenario: Native and candidate modes are qualified
+- **WHEN** the same semantic autocomplete target runs with native fallback and explicitly enabled Vaadin reference widgets
+- **THEN** both modes preserve authoritative values and honest continuation or refinement behavior
+- **AND** unaffected routes retain zero Vaadin asset requests
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md b/openspec/changes/add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md
new file mode 100644
index 00000000000..d10da5bcd32
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md
@@ -0,0 +1,71 @@
+## ADDED Requirements
+
+### Requirement: Additive rich autocomplete windows
+Rich GraphQL SHALL expose `autoCompleteWindow` beside every advertised rich property or action-parameter `autoComplete` field.
+The existing autocomplete field, arguments, output, authorization, and execution behavior MUST remain compatible.
+
+#### Scenario: Property advertises autocomplete
+- **WHEN** a rich property wrapper exposes `autoComplete(search)`
+- **THEN** it also exposes `autoCompleteWindow(search, offset, size)`
+- **AND** the window items use the same output type and authorized Causeway autocomplete semantic
+
+#### Scenario: Action parameter advertises autocomplete
+- **WHEN** a rich object or service action parameter exposes autocomplete with preceding dependent arguments
+- **THEN** its window field declares the same preceding arguments plus search, offset, and size
+- **AND** evaluates those arguments through the same parameter negotiation model
+
+#### Scenario: Existing client submits legacy autocomplete
+- **WHEN** a client executes a previously valid `autoComplete(search)` document
+- **THEN** its operation shape and semantic list result remain unchanged
+- **AND** the client is not required to select window metadata
+
+### Requirement: Bounded window request contract
+Autocomplete windows SHALL accept zero-based offset and positive requested size and SHALL enforce configured default and maximum sizes before invoking domain autocomplete.
+Invalid requests MUST fail with bounded errors that omit search text, pending arguments, object identities, and result values.
+
+#### Scenario: Window arguments are omitted
+- **WHEN** a client omits offset or size
+- **THEN** offset defaults to zero and size defaults to the configured autocomplete window size
+- **AND** the result reports the effective requested values
+
+#### Scenario: Window request is valid
+- **WHEN** offset is non-negative and size is within the configured maximum
+- **THEN** the server returns at most the requested number of items
+- **AND** no response exceeds the configured maximum
+
+#### Scenario: Window request is invalid
+- **WHEN** offset is negative, size is non-positive, or size exceeds the configured maximum
+- **THEN** GraphQL returns a bounded autocomplete-window error before invoking the domain semantic
+- **AND** does not echo protected or submitted values
+
+### Requirement: Authoritative request-consistent window metadata
+Each autocomplete window SHALL invoke the authorized Causeway autocomplete semantic once for that request, preserve its application encounter order, and report enough metadata to continue bounded offset paging.
+The contract MUST NOT claim persistence query pushdown, a cursor, or a stable snapshot across requests.
+
+#### Scenario: Result spans several windows
+- **WHEN** the authoritative result contains more items than the requested size
+- **THEN** the result reports items, offset, requested size, returned count, total count, configured maximum, previous and next availability, and `APPLICATION` ordering
+- **AND** adjacent windows preserve the encounter order observed by their respective executions
+
+#### Scenario: Offset reaches or exceeds total count
+- **WHEN** a valid offset is at or beyond the materialized result size
+- **THEN** the server returns an empty item list with accurate count and continuation metadata
+- **AND** does not treat the empty window as an error
+
+#### Scenario: Domain state changes between requests
+- **WHEN** authoritative autocomplete order or membership changes between page requests
+- **THEN** each response remains internally consistent for its own execution
+- **AND** no cross-request snapshot or cursor stability is implied
+
+### Requirement: Semantic identity and value-shape preservation
+Window items SHALL use the same rich output mapping as existing autocomplete results and SHALL request or expose only fields valid for their advertised concrete types.
+
+#### Scenario: Window returns domain references
+- **WHEN** autocomplete items are object references
+- **THEN** their advertised semantic identity, optional title, optional version, and polymorphic projection behavior remain available
+- **AND** no bookmark or concurrency token is fabricated
+
+#### Scenario: Window returns scalar or enum values
+- **WHEN** an advertised autocomplete semantic returns a supported scalar or enum item type
+- **THEN** the window preserves that item type and encounter order
+- **AND** does not require object metadata
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/specs/vaadin-reference-widget-pilot/spec.md b/openspec/changes/add-paged-graphql-reference-autocomplete/specs/vaadin-reference-widget-pilot/spec.md
new file mode 100644
index 00000000000..d06e52956ca
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/specs/vaadin-reference-widget-pilot/spec.md
@@ -0,0 +1,30 @@
+## MODIFIED Requirements
+
+### Requirement: Honest bounded autocomplete behavior
+The pilot SHALL prefer advertised public GraphQL autocomplete windows and SHALL connect its internal lazy data-provider callback to bounded server response pages.
+It MUST retain an explicit maximum search policy for legacy non-paged autocomplete, and local slicing MUST NOT be represented as server paging.
+
+#### Scenario: Window capability is advertised
+- **WHEN** an eligible reference editor advertises `autoCompleteWindow`
+- **THEN** the internal Vaadin data provider requests bounded offset pages using current filter text and Causeway argument context
+- **AND** supplies returned items and authoritative total count to the control without exposing a Vaadin API to the application
+
+#### Scenario: User scrolls beyond the first page
+- **WHEN** Vaadin requests a later page for the current filter generation
+- **THEN** the adapter obtains that page from the semantic Causeway context
+- **AND** does not locally slice a previously downloaded complete result
+
+#### Scenario: Filter changes while pages are in flight
+- **WHEN** newer filter text, dependent arguments, route navigation, fragment replacement, prompt closure, or disconnection supersedes page requests
+- **THEN** the adapter cancels or ignores stale callbacks and items
+- **AND** retains Causeway-owned selection, focus, validation, and pending-value state
+
+#### Scenario: Only bounded legacy autocomplete is available
+- **WHEN** the server does not advertise a window field and GraphQL returns a stable choice set within the configured bound
+- **THEN** the adapter may use the complete finite result while retaining cancellation and generation checks
+- **AND** records that the response is legacy and not server paging
+
+#### Scenario: Legacy autocomplete bound is exceeded
+- **WHEN** a legacy server response exceeds the configured maximum or cannot provide stable identities
+- **THEN** the editor presents a Causeway-owned limitation state or activates the documented fallback
+- **AND** does not truncate the choices while claiming a complete match set
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md b/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md
new file mode 100644
index 00000000000..7bc32dceb28
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md
@@ -0,0 +1,113 @@
+## 1. Establish current and target contracts
+
+- [ ] 1.1 Capture existing property and action-parameter autocomplete field shapes and legacy client limits.
+- [ ] 1.2 Record deterministic Reference Application autocomplete order, total, and configured qualification page size.
+- [ ] 1.3 Define property, object-action, service-action, scalar, enum, object, versionless, and polymorphic window shapes.
+- [ ] 1.4 Define valid, defaulted, boundary, empty, overflow, dependent-argument, and changing-result vectors.
+
+## 2. Add GraphQL configuration and window types
+
+- [ ] 2.1 Add GraphQL autocomplete default-window-size and max-window-size configuration with validated defaults.
+- [ ] 2.2 Add deterministic generated type names for property and action-parameter autocomplete windows.
+- [ ] 2.3 Add a dedicated bounded autocomplete-window exception that omits submitted values.
+- [ ] 2.4 Add the `APPLICATION` ordering enum and deduplicated registry construction.
+- [ ] 2.5 Build member-specific window result types with items and complete paging metadata.
+- [ ] 2.6 Validate offset and size before invoking domain autocomplete.
+- [ ] 2.7 Materialize one authoritative result per request, preserve encounter order, and return an immutable slice.
+
+## 3. Expose additive property windows
+
+- [ ] 3.1 Add `autoCompleteWindow` beside each advertised rich property `autoComplete` field.
+- [ ] 3.2 Preserve the existing property autocomplete field and data fetcher unchanged.
+- [ ] 3.3 Use the same source object, authorization, search text, item output mapping, and Causeway autocomplete semantic.
+- [ ] 3.4 Register the generated field, result type, item type, and data fetcher deterministically.
+
+## 4. Expose additive action-parameter windows
+
+- [ ] 4.1 Add `autoCompleteWindow` beside each advertised rich action-parameter autocomplete field.
+- [ ] 4.2 Preserve preceding declared parameter arguments and append search, offset, and size.
+- [ ] 4.3 Reuse parameter negotiation, conversion, authorization, and item output mapping.
+- [ ] 4.4 Preserve existing object and service action autocomplete documents unchanged.
+- [ ] 4.5 Register action-parameter window result types and data fetchers deterministically.
+
+## 5. Add GraphQL model and integration verification
+
+- [ ] 5.1 Test autocomplete configuration defaults, valid overrides, and default-not-greater-than-maximum validation.
+- [ ] 5.2 Test deterministic result type naming and registry deduplication.
+- [ ] 5.3 Test valid first, middle, final, empty, exact-maximum, and defaulted windows.
+- [ ] 5.4 Test negative offset, zero size, and above-maximum requests fail before domain invocation.
+- [ ] 5.5 Test action dependent arguments remain declared and authoritative.
+- [ ] 5.6 Test legacy fields retain their previous schema and result behavior.
+- [ ] 5.7 Test item output mapping for object identity and supported non-object values.
+
+## 6. Extend targeted client discovery and semantic contexts
+
+- [ ] 6.1 Follow advertised autocomplete-window result and item types through targeted introspection.
+- [ ] 6.2 Describe window defaults, maximum metadata fields, and item output shape without speculative selections.
+- [ ] 6.3 Add one immutable normalized semantic autocomplete-window result shape.
+- [ ] 6.4 Add object-context property window execution that emits only advertised arguments and fields.
+- [ ] 6.5 Add object-action parameter window execution with current preceding values.
+- [ ] 6.6 Add service-action parameter window execution with current preceding values.
+- [ ] 6.7 Preserve existing list-returning context methods for compatibility.
+- [ ] 6.8 Normalize legacy list fallback only within the existing accepted bound and mark it non-windowed.
+- [ ] 6.9 Add cancellation, request-key, filter-generation, and stale-response tests across overlapping pages.
+
+## 7. Integrate toolkit-neutral property and action controllers
+
+- [ ] 7.1 Prefer window capability for property searches and reset paging when filter text changes.
+- [ ] 7.2 Prefer window capability for object and service action parameter searches.
+- [ ] 7.3 Reset dependent parameter paging when preceding pending values change.
+- [ ] 7.4 Preserve pending value, semantic identity, validation, focus, cancellation, and prompt contracts.
+- [ ] 7.5 Expose an accessible additional-results or refine indication for native first-window presentation.
+- [ ] 7.6 Retain visible legacy over-bound failure without silent slicing.
+- [ ] 7.7 Add controller tests for later pages, out-of-order completion, supersession, prompt closure, route replacement, and disconnect.
+
+## 8. Connect the internal Vaadin lazy data provider
+
+- [ ] 8.1 Confirm current Vaadin Combo Box data-provider and callback semantics from pinned-version documentation.
+- [ ] 8.2 Add an internal page-request bridge carrying filter, offset, size, and a one-shot responder.
+- [ ] 8.3 Configure Combo Box page size and lazy data provider only when window capability is advertised.
+- [ ] 8.4 Return authoritative items and total count without assigning or slicing a complete local item array.
+- [ ] 8.5 Cancel or ignore stale provider callbacks after filter change, rerender, route replacement, or disconnect.
+- [ ] 8.6 Reconcile selected single and multi-reference identities even when their pages are not loaded.
+- [ ] 8.7 Preserve finite-items behavior and fallback for choices and legacy autocomplete.
+- [ ] 8.8 Add adapter tests for first and later pages, empty results, changed totals, stale callbacks, selection, and fallback.
+
+## 9. Qualify the pinned Reference Application
+
+- [ ] 9.1 Configure a deterministic qualification page smaller than the existing autocomplete result set.
+- [ ] 9.2 Add target-catalogue and inventory coverage for multi-window autocomplete.
+- [ ] 9.3 Verify property or action-parameter first, middle, final, and empty windows through real GraphQL.
+- [ ] 9.4 Verify counts, continuation, encounter order, requested maximum, and invalid-window errors.
+- [ ] 9.5 Verify legacy autocomplete still returns its established complete result.
+- [ ] 9.6 Add a browser journey that obtains and selects a reference absent from the first window.
+- [ ] 9.7 Verify dependent values, validation or submission, semantic identity, cancellation, and stale-filter behavior.
+- [ ] 9.8 Qualify native fallback and explicitly enabled Vaadin modes without external requests or policy regressions.
+- [ ] 9.9 Verify clean and incremental capability inventory generation remain byte-identical.
+
+## 10. Preserve compatibility and production isolation
+
+- [ ] 10.1 Verify no existing GraphQL field, route, component, semantic event, context result, or operation placement is removed or renamed.
+- [ ] 10.2 Verify no Flow, Binder, Java DataProvider, Pro component, telemetry, CDN, or application-facing Vaadin API is introduced.
+- [ ] 10.3 Verify unaffected routes remain route-lazy with zero Vaadin requests.
+- [ ] 10.4 Verify exact CSP hashes, `style-src-attr 'none'`, bundle checksum, native rollback, and package dependencies remain unchanged.
+- [ ] 10.5 Verify errors and evidence omit search text, protected pending arguments, identifiers, and returned values.
+- [ ] 10.6 Verify documentation does not claim database pushdown, cursor stability, or cross-request snapshots.
+
+## 11. Document the capability
+
+- [ ] 11.1 Update GraphQL setup documentation with fields, result metadata, configuration, ordering, and consistency limits.
+- [ ] 11.2 Update foundation and HTMX reference-editor documentation with window preference and legacy fallback.
+- [ ] 11.3 Add an operation-shape and window-bound matrix with safe Reference Application counts.
+- [ ] 11.4 Add reproducible focused and full qualification commands.
+- [ ] 11.5 Add implementation, compatibility, security, rollback, and retained-limit evidence.
+- [ ] 11.6 Record final gate results and the next recommended Vaadin editor-family change.
+
+## 12. Run final qualification gates
+
+- [ ] 12.1 Run GraphQL configuration, model, schema, and focused integration suites.
+- [ ] 12.2 Run foundation Node and web-component Maven suites.
+- [ ] 12.3 Run full Petclinic integration and Playwright suites in native and applicable candidate modes.
+- [ ] 12.4 Run Reference Application clean package, integration, inventory, and Playwright suites.
+- [ ] 12.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
+- [ ] 12.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
diff --git a/openspec/planned-changes/web-component-viewer/README.md b/openspec/planned-changes/web-component-viewer/README.md
index d6b17ec15ed..ad2efceecf8 100644
--- a/openspec/planned-changes/web-component-viewer/README.md
+++ b/openspec/planned-changes/web-component-viewer/README.md
@@ -8,7 +8,7 @@ The action-dispatch correctness change is archived, completing the remaining Pri
The versionless-identity and preparation correction is archived.
The union-projection correction is archived.
The opaque-route correction is archived.
-The next change should add paged GraphQL reference autocomplete before the Vaadin expansion and default sequence in `vaadin-default-roadmap.md`.
+The active `add-paged-graphql-reference-autocomplete` change adds honest bounded server response windows before the Vaadin expansion and default sequence in `vaadin-default-roadmap.md`.
The older Vue, Svelte, metadata, diagnostics, performance-analysis, catalogue, and designer drafts remain queued behind that higher-priority qualification and default-adoption work.
Complete child directories contain `.openspec.yaml`, `proposal.md`, `design.md`, `tasks.md`, and delta specifications and can be promoted verbatim after review.
diff --git a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
index 43da121f83c..c743032c67e 100644
--- a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
+++ b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
@@ -17,7 +17,7 @@ Proposal-only drafts must be refined against checked-in capability evidence befo
| 2 | `harden-webcomponent-input-value-semantics` *(archived)* | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Completed against stable Reference Application fixtures. |
| 3 | `fix-webcomponent-action-dispatch-correctness` *(archived)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Completed with successful typed Reference Application interactions and unchanged public operations. |
| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, `fix-webcomponent-union-projection-correctness` *(archived)*, `fix-webcomponent-opaque-route-correctness` *(archived)* | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
-| 5 | `add-paged-graphql-reference-autocomplete` | Add honest server-side reference windows for large datasets. | Public GraphQL operation, identity, preparation, and ordering contracts are accepted. |
+| 5 | `add-paged-graphql-reference-autocomplete` *(active)* | Add honest bounded server response windows for reference autocomplete without claiming persistence query pushdown. | Public GraphQL operation, identity, preparation, ordering, continuation, and consistency contracts are accepted. |
| 6 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
| 7 | `make-vaadin-default-for-webcomponent-viewer` | Flip the supported selection policy to Vaadin-first and remove pilot status. | All prerequisite suites pass in default and explicit native modes. |
(causeway) 14/15: adds paged GraphQL reference autocomplete
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit a50a842c00a187e9b71b08743d76d5e0685b23fd
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 21:55:16 2026 +0100
adds paged GraphQL reference autocomplete
---
.../core/config/CausewayConfiguration.java | 27 ++++
.../evidence/REPRODUCING.md | 62 ++++++++
.../evidence/final-gate-results.md | 33 ++++
.../evidence/implementation-report.md | 40 +++++
.../evidence/production-isolation.md | 19 +++
.../evidence/window-shape-matrix.md | 46 ++++++
.../tasks.md | 156 +++++++++----------
.../htmx/src/main/resources/application.properties | 4 +-
.../htmx/ReferenceAppHtmxPlaywrightTest.java | 58 +++++--
.../ReferenceAppCapabilityInventory_IntegTest.java | 3 +-
.../ReferenceAppHtmxApplication_IntegTest.java | 124 +++++++++++++++
.../inventory/ReferenceAppCapabilityInventory.java | 7 +
.../referenceapp/referenceapp-targets.json | 1 +
.../ROOT/pages/setup-and-configuration.adoc | 12 ++
.../viewer/graphql/model/domain/TypeNames.java | 14 ++
.../rich/query/AutoCompleteWindowOrdering.java | 23 +++
.../domain/rich/query/RichActionParamsParam.java | 8 +
.../RichActionParamsParamAutoCompleteWindow.java | 83 ++++++++++
.../domain/rich/query/RichAutoCompleteWindow.java | 167 +++++++++++++++++++++
.../model/domain/rich/query/RichProperty.java | 8 +
.../rich/query/RichPropertyAutoCompleteWindow.java | 68 +++++++++
.../InvalidAutoCompleteWindowException.java | 26 ++++
.../model/registry/GraphQLTypeRegistry.java | 20 +--
.../query/AutoCompleteWindowConfigurationTest.java | 40 +++++
.../registry/GraphQLTypeRegistryUnionTest.java | 12 ++
viewers/webcomponents/foundation/USAGE.adoc | 8 +-
.../foundation/src/editor-registry.mjs | 5 +-
.../foundation/src/graphql-client.mjs | 4 +-
.../src/interaction-controller-element.mjs | 92 +++++++++---
.../foundation/src/interaction-operations.mjs | 68 +++++++++
.../foundation/src/object-context-controller.mjs | 90 ++++++++++-
.../foundation/src/property-element.mjs | 77 ++++++++--
.../foundation/src/reference-widget.mjs | 62 +++++++-
.../foundation/src/service-action-context.mjs | 62 +++++++-
.../test/application-menu-client.test.mjs | 17 +++
.../test/fixtures/menu-graphql-fixture.mjs | 27 +++-
.../test/fixtures/rich-schema-fixture.mjs | 47 ++++++
.../foundation/test/graphql-client.test.mjs | 20 +++
.../foundation/test/interaction-command.test.mjs | 109 ++++++++++++++
.../foundation/test/interaction.test.mjs | 128 ++++++++++++++++
viewers/webcomponents/htmx/README.adoc | 3 +-
.../petclinic/PetClinicHtmxPlaywrightTest.java | 10 +-
42 files changed, 1744 insertions(+), 146 deletions(-)
diff --git a/core/config/src/main/java/org/apache/causeway/core/config/CausewayConfiguration.java b/core/config/src/main/java/org/apache/causeway/core/config/CausewayConfiguration.java
index 6cb2c9b3f83..2065b1cbb04 100644
--- a/core/config/src/main/java/org/apache/causeway/core/config/CausewayConfiguration.java
+++ b/core/config/src/main/java/org/apache/causeway/core/config/CausewayConfiguration.java
@@ -2388,6 +2388,8 @@ public record Graphql(
@DefaultValue
Collections collections,
@DefaultValue
+ Autocomplete autocomplete,
+ @DefaultValue
Resources resources,
@DefaultValue
Authentication authentication
@@ -2645,6 +2647,31 @@ public record Collections(
}
}
+ /**
+ * Controls bounded rich GraphQL autocomplete response windows.
+ */
+ public record Autocomplete(
+ /**
+ * Default item count used when an autocomplete window omits its size.
+ */
+ @Min(value = 1)
+ @DefaultValue("20")
+ int defaultWindowSize,
+ /**
+ * Hard maximum item count accepted for one autocomplete window.
+ */
+ @Min(value = 1)
+ @DefaultValue("100")
+ int maxWindowSize) {
+
+ public Autocomplete {
+ if (defaultWindowSize > maxWindowSize) {
+ throw new IllegalArgumentException(
+ "causeway.viewer.graphql.autocomplete.default-window-size must not exceed max-window-size");
+ }
+ }
+ }
+
/**
* The different ways in which resources ({@link org.apache.causeway.applib.value.Blob} bytes,
* {@link org.apache.causeway.applib.value.Clob} chars, grids and icons) are made available.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md
new file mode 100644
index 00000000000..15ac69d8479
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md
@@ -0,0 +1,62 @@
+# Reproducing paged reference autocomplete
+
+Use Temurin 25 for Maven commands.
+Install the changed core configuration, GraphQL model, and web-component artifacts before running the separate Reference Application reactor.
+
+## Configuration and GraphQL model
+
+```shell
+mvn -pl core/config -am test
+mvn -f viewers/graphql/pom.xml -pl model -am test
+mvn -f viewers/graphql/pom.xml -pl model -am -DskipTests install
+```
+
+The model suite covers configuration validation and existing schema behavior.
+The Reference Application integration below proves generated property-independent action-parameter fields, type metadata, all window boundaries, legacy compatibility, ordering, and non-disclosing errors against the real metamodel.
+
+## Foundation
+
+```shell
+cd viewers/webcomponents/foundation
+node --test
+cd ../../..
+mvn -f viewers/webcomponents/pom.xml -pl foundation,htmx -am test
+```
+
+Focused tests cover targeted window and item discovery, advertised selection, immutable normalization, property, object-action, and service-action execution, dependent arguments, legacy fallback, native search handling, Vaadin later-page callbacks, and stale-filter rejection.
+
+## Reference Application GraphQL
+
+```shell
+mvn -f viewers/webcomponents/pom.xml -pl foundation,htmx -am -DskipTests install
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Dtest=ReferenceAppHtmxApplication_IntegTest#actionReferenceAutocompleteExposesBoundedServerWindowsAndLegacyCompatibility \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+## Reference Application candidate and native browser modes
+
+```shell
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest#menusChoicesAutocompleteCancellationAndRouteDisposal \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest#menusChoicesAutocompleteCancellationAndRouteDisposal \
+ -Dsurefire.failIfNoSpecifiedTests=false \
+ -Dcauseway.viewer.webcomponents.htmx.vaadin-reference-widgets=false test
+```
+
+## Full qualification
+
+```shell
+mvn -f viewers/webcomponents/pom.xml -pl sample-htmx-petclinic -am -Pplaywright test
+mvn -f regressiontests/referenceapp/pom.xml clean package
+mvn -f regressiontests/referenceapp/pom.xml -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+openspec validate add-paged-graphql-reference-autocomplete --strict
+git diff --check
+```
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md
new file mode 100644
index 00000000000..a653c5bcaf5
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md
@@ -0,0 +1,33 @@
+# Final gate results
+
+## Passed
+
+- Core configuration reactor and autocomplete validation tests: `BUILD SUCCESS`.
+- GraphQL model reactor, concurrent registry test, and existing model tests: `BUILD SUCCESS`.
+- Foundation Node suite: 154 tests passed with zero failures.
+- Web-component foundation and HTMX Maven reactor: `BUILD SUCCESS`.
+- Focused Reference Application window and legacy GraphQL integration: `BUILD SUCCESS`.
+- Petclinic candidate Playwright: 4 tests passed with zero failures, errors, or skips.
+- Petclinic explicit native Playwright: 4 tests passed with zero failures, errors, or skips.
+- Reference Application ordinary clean package, integration tests, inventory tests, and deterministic fixtures: `BUILD SUCCESS`.
+- Reference Application candidate Playwright: 9 tests passed with zero failures, errors, or skips.
+- Reference Application focused explicit native autocomplete journey: passed.
+- Clean and incremental capability inventory retained SHA-256 `75ef904a0d4fbc9c915c74866cdbd503743dab589f7525bbab126baf1eaa024a` byte-for-byte.
+- Vaadin production-like pilot: 5 scenarios with zero axe, CSP, console, page, external-request, or overflow failures.
+- Core configuration, GraphQL model, HTMX, and Reference Application RAT checks: `BUILD SUCCESS`.
+- Strict OpenSpec validation, `git diff --check`, and production-isolation review: passed.
+
+## Corrected executable outcomes
+
+Property and action-parameter wrappers retain legacy autocomplete and advertise bounded response windows.
+The Reference Application seven-result filter returns a five-item first page and two-item later page with accurate count and continuation metadata.
+The unchanged legacy list exactly matches concatenated window order.
+The internal Vaadin data provider selects an item absent from page zero and submits it through the existing action contract.
+Native mode obtains the first page, reports additional matches honestly, selects an authoritative reference, and submits without sending raw search text as an object input.
+Invalid windows are rejected without exposing the search value.
+
+## Retained limits and next step
+
+Each page request materializes one authoritative application autocomplete result before slicing; persistence query pushdown, cursors, and cross-request snapshots remain outside the public metamodel contract.
+The standalone foundation RAT goal still reports the same pre-existing `vaadin-reference/README.adoc` and generated `vaadin-reference.js` resources, neither introduced nor modified here.
+The next recommended change is `expand-vaadin-semantic-editor-families`.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/implementation-report.md b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/implementation-report.md
new file mode 100644
index 00000000000..bd2d32f508e
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/implementation-report.md
@@ -0,0 +1,40 @@
+# Paged reference autocomplete implementation report
+
+## GraphQL model
+
+GraphQL configuration now supplies autocomplete default and maximum response-window sizes with validated defaults of 20 and 100.
+Rich properties and action parameters that already expose `autoComplete` additionally expose `autoCompleteWindow`.
+Existing field names, arguments, result types, and data fetchers remain unchanged.
+
+A shared server element validates offset and size, invokes the existing authorized Causeway autocomplete semantic once, copies application encounter order, and returns an immutable response slice with complete count and continuation metadata.
+Member-specific generated result types retain exact item output mapping.
+Object and service action parameters retain only advertised preceding arguments through the existing negotiation and conversion model.
+Errors are bounded and omit search text, pending arguments, identities, and values.
+GraphQL type registration is synchronized and returns snapshots so parallel metamodel discovery cannot lose a generated type while the additive window types are registered.
+
+## Semantic client
+
+Targeted introspection follows window, item, abstract/concrete, and metadata types.
+Object and service contexts add immutable window-returning methods while retaining every list-returning method.
+Window operations select only advertised arguments and fields.
+Servers without the additive field are normalized as marked legacy results and remain subject to the established complete-response bound.
+
+Filter changes, dependent argument changes, prompt closure, route replacement, disconnect, and request generations abort or reject stale work.
+Native autocomplete no longer submits raw search text as a domain-object pending value while the user is still filtering.
+It renders the bounded first window and an accessible refinement message when `hasNext` is true.
+
+## Internal Vaadin adapter
+
+Pinned Vaadin 25.2.8 documentation and package metadata confirm the lazy callback contract `dataProvider({filter, page, pageSize}, callback)` and `callback(items, totalSize)`.
+The internal Causeway adapter uses the introspected default page size, maps pages to semantic offset requests, normalizes rich object metadata to stable identities, and supplies authoritative total count.
+Outdated filter callbacks are ignored.
+Finite choices and legacy autocomplete retain the established items and fallback behavior.
+No Vaadin API crosses the public Causeway component boundary.
+
+## Reference Application
+
+The qualification page and maximum are five against an existing deterministic seven-result filter.
+The inventory normalizes the conditionally advertised abstract `ValueHolder.name` wrapper so clean and incremental schema traversals remain byte-identical without hiding a capability change.
+GraphQL covers first, later, defaulted, empty, invalid, and legacy operations.
+The candidate browser journey requests page one directly through the internal data provider and submits a reference absent from page zero.
+Native mode obtains the first window, exposes the refinement message, selects an authoritative item, and submits through the same action contract.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/production-isolation.md b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/production-isolation.md
new file mode 100644
index 00000000000..ccc9531effa
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/production-isolation.md
@@ -0,0 +1,19 @@
+# Production isolation verification
+
+The change adds rich GraphQL fields and generated result types but removes or renames no existing field, argument, type, operation, route, semantic event, context method, or result kind.
+Legacy `autoComplete(search)` remains executable and unchanged.
+The server invokes the same Causeway property or parameter autocomplete semantic, authorization context, pending preceding arguments, and output mapper.
+
+No dependency, Maven coordinate, npm package, lock file, Vaadin version, generated Vaadin bundle, checksum, exact CSP hash, asset URL, CDN source, telemetry, Flow, Binder, Java DataProvider, Pro component, or application-facing Vaadin element changed.
+The JavaScript data-provider callback is contained within `<causeway-reference-editor>`.
+Causeway contexts continue to own GraphQL, pending values, identity, validation, cancellation, events, routes, and state.
+
+Candidate delivery remains route-lazy.
+Unqualified routes make zero Vaadin requests.
+Native fallback remains available through the existing viewer property and does not require the candidate bundle.
+`style-src-attr 'none'` and the four exact style hashes remain unchanged.
+
+The public window bounds browser transfer only.
+Documentation and diagnostics explicitly avoid claims of database query pushdown, cursor stability, or cross-request snapshots.
+Search text, protected pending arguments, identifiers, result values, and raw exception details are absent from evidence and bounded errors.
+Rollback returns new clients to legacy bounded autocomplete and requires no application, route, data, or asset migration.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md
new file mode 100644
index 00000000000..9ca5ade1323
--- /dev/null
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md
@@ -0,0 +1,46 @@
+# Autocomplete window shape matrix
+
+## Public GraphQL fields
+
+| Context | Existing field | Additive field |
+|---|---|---|
+| Rich property wrapper | `autoComplete(search): [Item]` | `autoCompleteWindow(search, offset = 0, size = configuredDefault): Window` |
+| Rich object-action parameter wrapper | Existing declared preceding arguments plus `search` | Same declared preceding arguments plus `search`, `offset`, and `size` |
+| Rich service-action parameter wrapper | Existing declared preceding arguments plus `search` | Same declared preceding arguments plus `search`, `offset`, and `size` |
+
+Every generated window contains `items`, `offset`, `requestedSize`, `returnedCount`, `totalCount`, `maximumSize`, `hasPrevious`, `hasNext`, and `ordering`.
+`items` uses the same advertised output type as legacy autocomplete.
+`ordering` is `APPLICATION`, meaning the authoritative application encounter order for that execution.
+No cursor, persistence query pushdown, or cross-request snapshot is claimed.
+
+## Bounds
+
+| Request | Result |
+|---|---|
+| Offset omitted | Uses zero. |
+| Size omitted | Uses `causeway.viewer.graphql.autocomplete.default-window-size`. |
+| Valid offset and size | Invokes domain autocomplete once and returns at most `size` items. |
+| Offset at or beyond total | Returns an empty successful window with accurate total and continuation metadata. |
+| Negative offset | Bounded error before domain invocation. |
+| Zero or negative size | Bounded error before domain invocation. |
+| Size above configured maximum | Bounded error before domain invocation. |
+
+Defaults are 20 items and a 100-item hard maximum.
+The Reference Application qualification overrides both values to five.
+
+## Safe deterministic Reference Application evidence
+
+The search text itself and returned identifiers are omitted from evidence.
+The approved one-character filter yields seven deterministic `TvCharacter` references in application encounter order.
+The first five-item window reports five items and `hasNext=true`.
+The second window at offset five reports two items, `hasPrevious=true`, and `hasNext=false`.
+The concatenated window identities exactly match the unchanged seven-item legacy result.
+An offset of 100 returns zero items and retains total count seven.
+
+## Client behavior
+
+Targeted introspection follows the generated window type, item type, concrete metadata type, defaults, and advertised scalar metadata.
+Object and service contexts return one immutable semantic shape and retain existing list-returning methods.
+Vaadin receives `{filter, page, pageSize}` and calls the semantic context with `offset = page * pageSize`; its callback receives normalized items and authoritative total count.
+Native presentation renders the first bounded window and states when more matches require refinement.
+Legacy-only servers retain the existing complete-response bound and visible over-bound failure.
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md b/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md
index 7bc32dceb28..c1fbd651121 100644
--- a/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md
+++ b/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md
@@ -1,113 +1,113 @@
## 1. Establish current and target contracts
-- [ ] 1.1 Capture existing property and action-parameter autocomplete field shapes and legacy client limits.
-- [ ] 1.2 Record deterministic Reference Application autocomplete order, total, and configured qualification page size.
-- [ ] 1.3 Define property, object-action, service-action, scalar, enum, object, versionless, and polymorphic window shapes.
-- [ ] 1.4 Define valid, defaulted, boundary, empty, overflow, dependent-argument, and changing-result vectors.
+- [x] 1.1 Capture existing property and action-parameter autocomplete field shapes and legacy client limits.
+- [x] 1.2 Record deterministic Reference Application autocomplete order, total, and configured qualification page size.
+- [x] 1.3 Define property, object-action, service-action, scalar, enum, object, versionless, and polymorphic window shapes.
+- [x] 1.4 Define valid, defaulted, boundary, empty, overflow, dependent-argument, and changing-result vectors.
## 2. Add GraphQL configuration and window types
-- [ ] 2.1 Add GraphQL autocomplete default-window-size and max-window-size configuration with validated defaults.
-- [ ] 2.2 Add deterministic generated type names for property and action-parameter autocomplete windows.
-- [ ] 2.3 Add a dedicated bounded autocomplete-window exception that omits submitted values.
-- [ ] 2.4 Add the `APPLICATION` ordering enum and deduplicated registry construction.
-- [ ] 2.5 Build member-specific window result types with items and complete paging metadata.
-- [ ] 2.6 Validate offset and size before invoking domain autocomplete.
-- [ ] 2.7 Materialize one authoritative result per request, preserve encounter order, and return an immutable slice.
+- [x] 2.1 Add GraphQL autocomplete default-window-size and max-window-size configuration with validated defaults.
+- [x] 2.2 Add deterministic generated type names for property and action-parameter autocomplete windows.
+- [x] 2.3 Add a dedicated bounded autocomplete-window exception that omits submitted values.
+- [x] 2.4 Add the `APPLICATION` ordering enum and deduplicated registry construction.
+- [x] 2.5 Build member-specific window result types with items and complete paging metadata.
+- [x] 2.6 Validate offset and size before invoking domain autocomplete.
+- [x] 2.7 Materialize one authoritative result per request, preserve encounter order, and return an immutable slice.
## 3. Expose additive property windows
-- [ ] 3.1 Add `autoCompleteWindow` beside each advertised rich property `autoComplete` field.
-- [ ] 3.2 Preserve the existing property autocomplete field and data fetcher unchanged.
-- [ ] 3.3 Use the same source object, authorization, search text, item output mapping, and Causeway autocomplete semantic.
-- [ ] 3.4 Register the generated field, result type, item type, and data fetcher deterministically.
+- [x] 3.1 Add `autoCompleteWindow` beside each advertised rich property `autoComplete` field.
+- [x] 3.2 Preserve the existing property autocomplete field and data fetcher unchanged.
+- [x] 3.3 Use the same source object, authorization, search text, item output mapping, and Causeway autocomplete semantic.
+- [x] 3.4 Register the generated field, result type, item type, and data fetcher deterministically.
## 4. Expose additive action-parameter windows
-- [ ] 4.1 Add `autoCompleteWindow` beside each advertised rich action-parameter autocomplete field.
-- [ ] 4.2 Preserve preceding declared parameter arguments and append search, offset, and size.
-- [ ] 4.3 Reuse parameter negotiation, conversion, authorization, and item output mapping.
-- [ ] 4.4 Preserve existing object and service action autocomplete documents unchanged.
-- [ ] 4.5 Register action-parameter window result types and data fetchers deterministically.
+- [x] 4.1 Add `autoCompleteWindow` beside each advertised rich action-parameter autocomplete field.
+- [x] 4.2 Preserve preceding declared parameter arguments and append search, offset, and size.
+- [x] 4.3 Reuse parameter negotiation, conversion, authorization, and item output mapping.
+- [x] 4.4 Preserve existing object and service action autocomplete documents unchanged.
+- [x] 4.5 Register action-parameter window result types and data fetchers deterministically.
## 5. Add GraphQL model and integration verification
-- [ ] 5.1 Test autocomplete configuration defaults, valid overrides, and default-not-greater-than-maximum validation.
-- [ ] 5.2 Test deterministic result type naming and registry deduplication.
-- [ ] 5.3 Test valid first, middle, final, empty, exact-maximum, and defaulted windows.
-- [ ] 5.4 Test negative offset, zero size, and above-maximum requests fail before domain invocation.
-- [ ] 5.5 Test action dependent arguments remain declared and authoritative.
-- [ ] 5.6 Test legacy fields retain their previous schema and result behavior.
-- [ ] 5.7 Test item output mapping for object identity and supported non-object values.
+- [x] 5.1 Test autocomplete configuration defaults, valid overrides, and default-not-greater-than-maximum validation.
+- [x] 5.2 Test deterministic result type naming and registry deduplication.
+- [x] 5.3 Test valid first, middle, final, empty, exact-maximum, and defaulted windows.
+- [x] 5.4 Test negative offset, zero size, and above-maximum requests fail before domain invocation.
+- [x] 5.5 Test action dependent arguments remain declared and authoritative.
+- [x] 5.6 Test legacy fields retain their previous schema and result behavior.
+- [x] 5.7 Test item output mapping for object identity and supported non-object values.
## 6. Extend targeted client discovery and semantic contexts
-- [ ] 6.1 Follow advertised autocomplete-window result and item types through targeted introspection.
-- [ ] 6.2 Describe window defaults, maximum metadata fields, and item output shape without speculative selections.
-- [ ] 6.3 Add one immutable normalized semantic autocomplete-window result shape.
-- [ ] 6.4 Add object-context property window execution that emits only advertised arguments and fields.
-- [ ] 6.5 Add object-action parameter window execution with current preceding values.
-- [ ] 6.6 Add service-action parameter window execution with current preceding values.
-- [ ] 6.7 Preserve existing list-returning context methods for compatibility.
-- [ ] 6.8 Normalize legacy list fallback only within the existing accepted bound and mark it non-windowed.
-- [ ] 6.9 Add cancellation, request-key, filter-generation, and stale-response tests across overlapping pages.
+- [x] 6.1 Follow advertised autocomplete-window result and item types through targeted introspection.
+- [x] 6.2 Describe window defaults, maximum metadata fields, and item output shape without speculative selections.
+- [x] 6.3 Add one immutable normalized semantic autocomplete-window result shape.
+- [x] 6.4 Add object-context property window execution that emits only advertised arguments and fields.
+- [x] 6.5 Add object-action parameter window execution with current preceding values.
+- [x] 6.6 Add service-action parameter window execution with current preceding values.
+- [x] 6.7 Preserve existing list-returning context methods for compatibility.
+- [x] 6.8 Normalize legacy list fallback only within the existing accepted bound and mark it non-windowed.
+- [x] 6.9 Add cancellation, request-key, filter-generation, and stale-response tests across overlapping pages.
## 7. Integrate toolkit-neutral property and action controllers
-- [ ] 7.1 Prefer window capability for property searches and reset paging when filter text changes.
-- [ ] 7.2 Prefer window capability for object and service action parameter searches.
-- [ ] 7.3 Reset dependent parameter paging when preceding pending values change.
-- [ ] 7.4 Preserve pending value, semantic identity, validation, focus, cancellation, and prompt contracts.
-- [ ] 7.5 Expose an accessible additional-results or refine indication for native first-window presentation.
-- [ ] 7.6 Retain visible legacy over-bound failure without silent slicing.
-- [ ] 7.7 Add controller tests for later pages, out-of-order completion, supersession, prompt closure, route replacement, and disconnect.
+- [x] 7.1 Prefer window capability for property searches and reset paging when filter text changes.
+- [x] 7.2 Prefer window capability for object and service action parameter searches.
+- [x] 7.3 Reset dependent parameter paging when preceding pending values change.
+- [x] 7.4 Preserve pending value, semantic identity, validation, focus, cancellation, and prompt contracts.
+- [x] 7.5 Expose an accessible additional-results or refine indication for native first-window presentation.
+- [x] 7.6 Retain visible legacy over-bound failure without silent slicing.
+- [x] 7.7 Add controller tests for later pages, out-of-order completion, supersession, prompt closure, route replacement, and disconnect.
## 8. Connect the internal Vaadin lazy data provider
-- [ ] 8.1 Confirm current Vaadin Combo Box data-provider and callback semantics from pinned-version documentation.
-- [ ] 8.2 Add an internal page-request bridge carrying filter, offset, size, and a one-shot responder.
-- [ ] 8.3 Configure Combo Box page size and lazy data provider only when window capability is advertised.
-- [ ] 8.4 Return authoritative items and total count without assigning or slicing a complete local item array.
-- [ ] 8.5 Cancel or ignore stale provider callbacks after filter change, rerender, route replacement, or disconnect.
-- [ ] 8.6 Reconcile selected single and multi-reference identities even when their pages are not loaded.
-- [ ] 8.7 Preserve finite-items behavior and fallback for choices and legacy autocomplete.
-- [ ] 8.8 Add adapter tests for first and later pages, empty results, changed totals, stale callbacks, selection, and fallback.
+- [x] 8.1 Confirm current Vaadin Combo Box data-provider and callback semantics from pinned-version documentation.
+- [x] 8.2 Add an internal page-request bridge carrying filter, offset, size, and a one-shot responder.
+- [x] 8.3 Configure Combo Box page size and lazy data provider only when window capability is advertised.
+- [x] 8.4 Return authoritative items and total count without assigning or slicing a complete local item array.
+- [x] 8.5 Cancel or ignore stale provider callbacks after filter change, rerender, route replacement, or disconnect.
+- [x] 8.6 Reconcile selected single and multi-reference identities even when their pages are not loaded.
+- [x] 8.7 Preserve finite-items behavior and fallback for choices and legacy autocomplete.
+- [x] 8.8 Add adapter tests for first and later pages, empty results, changed totals, stale callbacks, selection, and fallback.
## 9. Qualify the pinned Reference Application
-- [ ] 9.1 Configure a deterministic qualification page smaller than the existing autocomplete result set.
-- [ ] 9.2 Add target-catalogue and inventory coverage for multi-window autocomplete.
-- [ ] 9.3 Verify property or action-parameter first, middle, final, and empty windows through real GraphQL.
-- [ ] 9.4 Verify counts, continuation, encounter order, requested maximum, and invalid-window errors.
-- [ ] 9.5 Verify legacy autocomplete still returns its established complete result.
-- [ ] 9.6 Add a browser journey that obtains and selects a reference absent from the first window.
-- [ ] 9.7 Verify dependent values, validation or submission, semantic identity, cancellation, and stale-filter behavior.
-- [ ] 9.8 Qualify native fallback and explicitly enabled Vaadin modes without external requests or policy regressions.
-- [ ] 9.9 Verify clean and incremental capability inventory generation remain byte-identical.
+- [x] 9.1 Configure a deterministic qualification page smaller than the existing autocomplete result set.
+- [x] 9.2 Add target-catalogue and inventory coverage for multi-window autocomplete.
+- [x] 9.3 Verify property or action-parameter first, middle, final, and empty windows through real GraphQL.
+- [x] 9.4 Verify counts, continuation, encounter order, requested maximum, and invalid-window errors.
+- [x] 9.5 Verify legacy autocomplete still returns its established complete result.
+- [x] 9.6 Add a browser journey that obtains and selects a reference absent from the first window.
+- [x] 9.7 Verify dependent values, validation or submission, semantic identity, cancellation, and stale-filter behavior.
+- [x] 9.8 Qualify native fallback and explicitly enabled Vaadin modes without external requests or policy regressions.
+- [x] 9.9 Verify clean and incremental capability inventory generation remain byte-identical.
## 10. Preserve compatibility and production isolation
-- [ ] 10.1 Verify no existing GraphQL field, route, component, semantic event, context result, or operation placement is removed or renamed.
-- [ ] 10.2 Verify no Flow, Binder, Java DataProvider, Pro component, telemetry, CDN, or application-facing Vaadin API is introduced.
-- [ ] 10.3 Verify unaffected routes remain route-lazy with zero Vaadin requests.
-- [ ] 10.4 Verify exact CSP hashes, `style-src-attr 'none'`, bundle checksum, native rollback, and package dependencies remain unchanged.
-- [ ] 10.5 Verify errors and evidence omit search text, protected pending arguments, identifiers, and returned values.
-- [ ] 10.6 Verify documentation does not claim database pushdown, cursor stability, or cross-request snapshots.
+- [x] 10.1 Verify no existing GraphQL field, route, component, semantic event, context result, or operation placement is removed or renamed.
+- [x] 10.2 Verify no Flow, Binder, Java DataProvider, Pro component, telemetry, CDN, or application-facing Vaadin API is introduced.
+- [x] 10.3 Verify unaffected routes remain route-lazy with zero Vaadin requests.
+- [x] 10.4 Verify exact CSP hashes, `style-src-attr 'none'`, bundle checksum, native rollback, and package dependencies remain unchanged.
+- [x] 10.5 Verify errors and evidence omit search text, protected pending arguments, identifiers, and returned values.
+- [x] 10.6 Verify documentation does not claim database pushdown, cursor stability, or cross-request snapshots.
## 11. Document the capability
-- [ ] 11.1 Update GraphQL setup documentation with fields, result metadata, configuration, ordering, and consistency limits.
-- [ ] 11.2 Update foundation and HTMX reference-editor documentation with window preference and legacy fallback.
-- [ ] 11.3 Add an operation-shape and window-bound matrix with safe Reference Application counts.
-- [ ] 11.4 Add reproducible focused and full qualification commands.
-- [ ] 11.5 Add implementation, compatibility, security, rollback, and retained-limit evidence.
-- [ ] 11.6 Record final gate results and the next recommended Vaadin editor-family change.
+- [x] 11.1 Update GraphQL setup documentation with fields, result metadata, configuration, ordering, and consistency limits.
+- [x] 11.2 Update foundation and HTMX reference-editor documentation with window preference and legacy fallback.
+- [x] 11.3 Add an operation-shape and window-bound matrix with safe Reference Application counts.
+- [x] 11.4 Add reproducible focused and full qualification commands.
+- [x] 11.5 Add implementation, compatibility, security, rollback, and retained-limit evidence.
+- [x] 11.6 Record final gate results and the next recommended Vaadin editor-family change.
## 12. Run final qualification gates
-- [ ] 12.1 Run GraphQL configuration, model, schema, and focused integration suites.
-- [ ] 12.2 Run foundation Node and web-component Maven suites.
-- [ ] 12.3 Run full Petclinic integration and Playwright suites in native and applicable candidate modes.
-- [ ] 12.4 Run Reference Application clean package, integration, inventory, and Playwright suites.
-- [ ] 12.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
-- [ ] 12.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
+- [x] 12.1 Run GraphQL configuration, model, schema, and focused integration suites.
+- [x] 12.2 Run foundation Node and web-component Maven suites.
+- [x] 12.3 Run full Petclinic integration and Playwright suites in native and applicable candidate modes.
+- [x] 12.4 Run Reference Application clean package, integration, inventory, and Playwright suites.
+- [x] 12.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
+- [x] 12.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
diff --git a/regressiontests/referenceapp/htmx/src/main/resources/application.properties b/regressiontests/referenceapp/htmx/src/main/resources/application.properties
index 96d35d96671..e3e18fd82ac 100644
--- a/regressiontests/referenceapp/htmx/src/main/resources/application.properties
+++ b/regressiontests/referenceapp/htmx/src/main/resources/application.properties
@@ -19,6 +19,8 @@ causeway.viewer.webcomponents.htmx.brand=Causeway Reference Application
causeway.viewer.webcomponents.htmx.wicket-comparison-path=/wicket/
causeway.viewer.webcomponents.htmx.application-stylesheet=/css/application.css
causeway.viewer.webcomponents.htmx.vaadin-reference-widgets=true
-causeway.viewer.webcomponents.htmx.reference-minimum-search-length=2
+causeway.viewer.webcomponents.htmx.reference-minimum-search-length=1
causeway.viewer.webcomponents.htmx.reference-maximum-results=50
+causeway.viewer.graphql.autocomplete.default-window-size=5
+causeway.viewer.graphql.autocomplete.max-window-size=5
causeway.value-types.kroki.backend-url=
diff --git a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
index 7644561a53e..cbf3b64b5b4 100644
--- a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
+++ b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
@@ -131,7 +131,7 @@ void menusChoicesAutocompleteCancellationAndRouteDisposal() {
"demo_ActionAutoCompleteMenu", "autoComplete", "rich__demo_ActionAutoCompletePage"));
objectAction("selectTvCharacter").click();
waitForPrompt("selectTvCharacter");
- selectFirstAutocompleteChoice("tvCharacter", "Tom");
+ selectLaterAutocompleteChoice("tvCharacter", "o");
submitPrompt();
page.locator(PROMPT).waitFor(new Locator.WaitForOptions()
.setState(com.microsoft.playwright.options.WaitForSelectorState.DETACHED));
@@ -552,6 +552,11 @@ private void waitForPrompt(final String actionId) {
private void selectFirstAvailableChoice(final String parameterId) {
final Locator control = page.locator(parameter(parameterId));
+ if (Boolean.TRUE.equals(control.evaluate("element => element.localName === 'select'"))) {
+ control.evaluate("element => { element.selectedIndex = 0; "
+ + "element.dispatchEvent(new Event('change', {bubbles: true, composed: true})); }");
+ return;
+ }
try {
page.waitForFunction("selector => document.querySelector(selector)?.dataset.widgetState === 'ready'", parameter(parameterId));
} catch (com.microsoft.playwright.TimeoutError cause) {
@@ -567,16 +572,49 @@ private void selectFirstAvailableChoice(final String parameterId) {
page.waitForFunction("selector => document.querySelector(selector)?.value?.id", parameter(parameterId));
}
- private void selectFirstAutocompleteChoice(final String parameterId, final String search) {
+ private void selectLaterAutocompleteChoice(final String parameterId, final String search) {
final Locator control = page.locator(parameter(parameterId));
- final Locator input = control.locator("vaadin-combo-box input");
- input.fill(search);
- page.waitForFunction("selector => { const element = document.querySelector(selector); return element?.dataset.widgetState === 'ready' && element.querySelector('vaadin-combo-box')?.items?.length > 0; }", parameter(parameterId));
- final String label = (String) control.evaluate("element => element.querySelector('vaadin-combo-box').items[0].title");
- input.fill(label);
- input.focus();
- page.keyboard().press("ArrowDown");
- page.keyboard().press("Enter");
+ final Locator parameterContainer = page.locator("[data-parameter='" + parameterId + "']");
+ try {
+ page.waitForFunction("selector => { const editor = document.querySelector(selector); "
+ + "return editor?.matches('causeway-reference-editor, input[list]') "
+ + "|| editor?.querySelector('causeway-reference-editor, input[list]'); }", parameter(parameterId));
+ } catch (final com.microsoft.playwright.TimeoutError cause) {
+ throw new AssertionError("Autocomplete editor was unavailable: " + page.locator(PROMPT).innerHTML(), cause);
+ }
+ if (!Boolean.TRUE.equals(control.evaluate("element => element.localName === 'causeway-reference-editor'"))) {
+ final Locator input = control;
+ input.fill(search);
+ try {
+ page.waitForFunction("selector => document.querySelector(selector)?.querySelectorAll('datalist option').length > 0",
+ "[data-parameter='" + parameterId + "']");
+ } catch (final com.microsoft.playwright.TimeoutError cause) {
+ throw new AssertionError("Native autocomplete did not receive its first window: "
+ + page.locator(PROMPT).innerHTML(), cause);
+ }
+ assertThat(parameterContainer.locator(".causeway-autocomplete-continuation").innerText())
+ .containsIgnoringCase("more matches");
+ final String encoded = parameterContainer.locator("datalist option").first().getAttribute("value");
+ input.evaluate("(element, value) => { element.value = value; "
+ + "element.dispatchEvent(new Event('change', {bubbles: true, composed: true})); }", encoded);
+ page.waitForFunction("() => document.querySelector('[data-testid=action-prompt-submit]')?.disabled === false");
+ return;
+ }
+ control.locator("vaadin-combo-box").waitFor();
+ final JsonNode pageResult = OBJECT_MAPPER.valueToTree(control.evaluate("async (element, search) => {\n"
+ + " const combo = element.querySelector('vaadin-combo-box');\n"
+ + " if (typeof combo?.dataProvider !== 'function') throw new Error('Windowed data provider is unavailable');\n"
+ + " return await new Promise(resolve => combo.dataProvider(\n"
+ + " {filter: search, page: 1, pageSize: 5},\n"
+ + " (items, total) => {\n"
+ + " const selected = items[0];\n"
+ + " combo.dispatchEvent(new CustomEvent('selected-item-changed', {detail: {value: selected}}));\n"
+ + " resolve({count: items.length, total, selected, error: element.dataset.widgetError || null});\n"
+ + " }));\n"
+ + "}", search));
+ assertThat(pageResult.path("count").asInt()).as(pageResult.toPrettyString()).isGreaterThan(0);
+ assertThat(pageResult.path("total").asInt()).isGreaterThan(5);
+ assertThat(pageResult.at("/selected/id").asText()).isNotBlank();
page.waitForFunction("selector => document.querySelector(selector)?.value?.id", parameter(parameterId));
}
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
index 6eec2ca7468..e0d74bbe7fd 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
@@ -107,7 +107,8 @@ private void assertJourneyTargetsExist(final JsonNode introspection) throws Exce
.contains(target.path("member").asText());
}
assertThat(families).contains(
- "action-choices", "action-autocomplete", "action-defaults", "action-validation",
+ "action-choices", "action-autocomplete", "reference-autocomplete-window",
+ "action-defaults", "action-validation",
"action-parameterless", "action-parameterized", "action-scalar-outcome",
"action-object-outcome", "action-cancel-stale-concurrency",
"versionless-preparation", "versionless-action-result", "versionless-collection-row",
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
index 045b16b9758..09419f92cad 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
@@ -17,8 +17,10 @@
import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.util.Base64;
+import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
+import java.util.stream.Stream;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -318,6 +320,128 @@ void polymorphicCollectionsCompleteUnionMembershipAndAcceptFragments() throws Ex
assertThat(first.at("/name/get").asText()).isNotBlank();
}
+ @Test
+ void actionReferenceAutocompleteExposesBoundedServerWindowsAndLegacyCompatibility() throws Exception {
+ final JsonNode opened = graphQL("""
+ mutation {
+ demo_ActionAutoCompleteMenu__autoComplete {
+ _meta { id logicalTypeName title }
+ }
+ }
+ """);
+ assertNoGraphQLErrors(opened);
+ final String pageId = opened.at("/data/demo_ActionAutoCompleteMenu__autoComplete/_meta/id").asText();
+ assertThat(pageId).isNotBlank();
+
+ final String target = "demo_ActionAutoCompletePage(object: {id: "
+ + OBJECT_MAPPER.writeValueAsString(pageId) + "})";
+ final JsonNode described = graphQL("""
+ { __type(name: "rich__demo_ActionAutoCompletePage__selectTvCharacter__tvCharacter__gqlv_action_parameter") {
+ fields { name args { name defaultValue } type { kind name ofType { kind name } } }
+ } }
+ """);
+ assertNoGraphQLErrors(described);
+ assertThat(described.at("/data/__type/fields").findValuesAsText("name"))
+ .contains("autoComplete", "autoCompleteWindow");
+ final JsonNode retainedLegacyType = graphQL("""
+ { __type(name: "rich__demo_ValueHolder__name__gqlv_property") { name } }
+ """);
+ assertNoGraphQLErrors(retainedLegacyType);
+ assertThat(retainedLegacyType.at("/data/__type/name").asText()).isNotBlank();
+
+ final JsonNode first = graphQL("""
+ { rich { %s { selectTvCharacter { params { tvCharacter {
+ autoCompleteWindow(search: "o", offset: 0, size: 5) {
+ items { _meta { id logicalTypeName title } }
+ offset requestedSize returnedCount totalCount maximumSize
+ hasPrevious hasNext ordering
+ }
+ } } } } } }
+ """.formatted(target));
+ assertNoGraphQLErrors(first);
+ final JsonNode firstWindow = first.at(
+ "/data/rich/demo_ActionAutoCompletePage/selectTvCharacter/params/tvCharacter/autoCompleteWindow");
+ assertThat(firstWindow.path("offset").asInt()).isZero();
+ assertThat(firstWindow.path("requestedSize").asInt()).isEqualTo(5);
+ assertThat(firstWindow.path("returnedCount").asInt()).isEqualTo(5);
+ assertThat(firstWindow.path("totalCount").asInt()).isEqualTo(7);
+ assertThat(firstWindow.path("maximumSize").asInt()).isEqualTo(5);
+ assertThat(firstWindow.path("hasPrevious").asBoolean()).isFalse();
+ assertThat(firstWindow.path("hasNext").asBoolean()).isTrue();
+ assertThat(firstWindow.path("ordering").asText()).isEqualTo("APPLICATION");
+
+ final JsonNode later = graphQL("""
+ { rich { %s { selectTvCharacter { params { tvCharacter {
+ autoCompleteWindow(search: "o", offset: 5, size: 5) {
+ items { _meta { id logicalTypeName title } }
+ offset returnedCount totalCount hasPrevious hasNext
+ }
+ } } } } } }
+ """.formatted(target));
+ assertNoGraphQLErrors(later);
+ final JsonNode laterWindow = later.at(
+ "/data/rich/demo_ActionAutoCompletePage/selectTvCharacter/params/tvCharacter/autoCompleteWindow");
+ assertThat(laterWindow.path("offset").asInt()).isEqualTo(5);
+ assertThat(laterWindow.path("returnedCount").asInt()).isGreaterThan(0);
+ assertThat(laterWindow.path("totalCount").asInt()).isEqualTo(firstWindow.path("totalCount").asInt());
+ assertThat(laterWindow.path("hasPrevious").asBoolean()).isTrue();
+ assertThat(firstWindow.at("/items").findValuesAsText("id"))
+ .doesNotContainAnyElementsOf(laterWindow.at("/items").findValuesAsText("id"));
+
+ final JsonNode boundaries = graphQL("""
+ { rich { %s { selectTvCharacter { params { tvCharacter {
+ defaulted: autoCompleteWindow(search: "o") {
+ offset requestedSize returnedCount totalCount
+ }
+ empty: autoCompleteWindow(search: "o", offset: 100, size: 5) {
+ items { _meta { id } } offset returnedCount totalCount hasPrevious hasNext
+ }
+ } } } } } }
+ """.formatted(target));
+ assertNoGraphQLErrors(boundaries);
+ final JsonNode defaulted = boundaries.at(
+ "/data/rich/demo_ActionAutoCompletePage/selectTvCharacter/params/tvCharacter/defaulted");
+ assertThat(defaulted.path("offset").asInt()).isZero();
+ assertThat(defaulted.path("requestedSize").asInt()).isEqualTo(5);
+ assertThat(defaulted.path("returnedCount").asInt()).isEqualTo(5);
+ final JsonNode empty = boundaries.at(
+ "/data/rich/demo_ActionAutoCompletePage/selectTvCharacter/params/tvCharacter/empty");
+ assertThat(empty.path("items").size()).isZero();
+ assertThat(empty.path("offset").asInt()).isEqualTo(100);
+ assertThat(empty.path("returnedCount").asInt()).isZero();
+ assertThat(empty.path("totalCount").asInt()).isEqualTo(firstWindow.path("totalCount").asInt());
+ assertThat(empty.path("hasPrevious").asBoolean()).isTrue();
+ assertThat(empty.path("hasNext").asBoolean()).isFalse();
+
+ final JsonNode legacy = graphQL("""
+ { rich { %s { selectTvCharacter { params { tvCharacter {
+ autoComplete(search: "o") { _meta { id logicalTypeName title } }
+ } } } } } }
+ """.formatted(target));
+ assertNoGraphQLErrors(legacy);
+ final JsonNode legacyItems = legacy.at(
+ "/data/rich/demo_ActionAutoCompletePage/selectTvCharacter/params/tvCharacter/autoComplete");
+ assertThat(legacyItems.size()).isEqualTo(firstWindow.path("totalCount").asInt());
+ assertThat(Stream.concat(
+ firstWindow.at("/items").findValuesAsText("id").stream(),
+ laterWindow.at("/items").findValuesAsText("id").stream()).toList())
+ .containsExactlyElementsOf(legacyItems.findValuesAsText("id"));
+
+ for (String arguments : List.of(
+ "offset: 0, size: 6",
+ "offset: -1, size: 5",
+ "offset: 0, size: 0")) {
+ final JsonNode invalid = graphQL("""
+ { rich { %s { selectTvCharacter { params { tvCharacter {
+ autoCompleteWindow(search: "protected-search", %s) { totalCount }
+ } } } } } }
+ """.formatted(target, arguments));
+ assertThat(invalid.at("/errors/0/message").asText())
+ .containsIgnoringCase("autocomplete window")
+ .doesNotContain("protected-search");
+ }
+ }
+
@Test
void compositeViewModelIdentityRoundTripsThroughTheBoundedCanonicalRoute() throws Exception {
final JsonNode opened = graphQL("""
diff --git a/regressiontests/referenceapp/support-jpa/src/main/java/org/apache/causeway/regressiontests/referenceapp/inventory/ReferenceAppCapabilityInventory.java b/regressiontests/referenceapp/support-jpa/src/main/java/org/apache/causeway/regressiontests/referenceapp/inventory/ReferenceAppCapabilityInventory.java
index 89f98790fec..b7f153fc8b9 100644
--- a/regressiontests/referenceapp/support-jpa/src/main/java/org/apache/causeway/regressiontests/referenceapp/inventory/ReferenceAppCapabilityInventory.java
+++ b/regressiontests/referenceapp/support-jpa/src/main/java/org/apache/causeway/regressiontests/referenceapp/inventory/ReferenceAppCapabilityInventory.java
@@ -174,6 +174,7 @@ private void normalizeConditionalValueHolderMembers(final List<Item> items, fina
}
final Set<String> conditionalIds = Set.of(
+ "rich__demo_ValueHolder__name__gqlv_property",
"rich__demo_ValueHolder__blob__gqlv_property",
"rich__demo_ValueHolder__count__gqlv_property",
"rich__demo_ValueHolder__incrementRedirectEvenIfSame__gqlv_action",
@@ -181,6 +182,12 @@ private void normalizeConditionalValueHolderMembers(final List<Item> items, fina
items.removeIf(item -> conditionalIds.contains(item.id()));
final String reason = "The effective metamodel conditionally advertises this abstract ValueHolder member; "
+ "the reviewed inventory retains it explicitly without claiming deterministic runtime support.";
+ items.add(new Item(
+ "rich__demo_ValueHolder__name__gqlv_property",
+ "PROPERTY",
+ "String",
+ Classification.SUPPORTED,
+ "The value shape has an existing scalar, enum, reference, collection, or resource presentation contract."));
items.add(new Item(
"rich__demo_ValueHolder__blob__gqlv_property",
"PROPERTY",
diff --git a/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json b/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
index 60631a164dc..a6ccaaea1ee 100644
--- a/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
+++ b/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
@@ -4,6 +4,7 @@
"targets": [
{"family": "action-choices", "rootField": "demo_ActionChoices", "member": "selectTvCharacter"},
{"family": "action-autocomplete", "rootField": "demo_ActionAutoCompletePage", "member": "selectTvCharacter"},
+ {"family": "reference-autocomplete-window", "rootField": "demo_ActionAutoCompletePage", "member": "selectTvCharacter"},
{"family": "action-defaults", "rootField": "demo_ActionDefaults", "member": "selectTvCharacterByShow"},
{"family": "action-validation", "rootField": "demo_ActionValidatePage", "member": "selectTvCharactersByShowAndSexUsingName"},
{"family": "action-parameterless", "rootField": "demo_ActionSemanticsVm", "member": "reportPropertyForSafe"},
diff --git a/viewers/graphql/adoc/modules/ROOT/pages/setup-and-configuration.adoc b/viewers/graphql/adoc/modules/ROOT/pages/setup-and-configuration.adoc
index cdadfeeca47..61ef0720362 100644
--- a/viewers/graphql/adoc/modules/ROOT/pages/setup-and-configuration.adoc
+++ b/viewers/graphql/adoc/modules/ROOT/pages/setup-and-configuration.adoc
@@ -107,6 +107,18 @@ It defaults to "`_target`".
+=== Bounded autocomplete response windows
+
+Every rich property or action parameter that advertises `autoComplete(search)` also advertises the additive `autoCompleteWindow(search, offset, size)` field.
+The window returns `items`, offset and requested size, returned and total counts, configured maximum, previous and next availability, and `APPLICATION` ordering.
+One request invokes the authoritative application autocomplete semantic once, preserves that execution's encounter order, and returns only the requested response slice.
+This bounds GraphQL response transfer but does not claim persistence query pushdown, cursor stability, or a cross-request snapshot.
+
+`autocomplete.default-window-size` defaults to `20` and supplies an omitted size.
+`autocomplete.max-window-size` defaults to `100` and rejects larger requests before invoking autocomplete.
+The default must not exceed the maximum.
+Existing `autoComplete(search)` documents remain compatible.
+
The remaining configuration properties are explained in more detail elsewhere:
* xref:refguide:config:sections/causeway.viewer.graphql.adoc#causeway.viewer.graphql.resources.response-type[resources.response-type]
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/TypeNames.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/TypeNames.java
index 914b42e435a..05ca54de53a 100644
--- a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/TypeNames.java
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/TypeNames.java
@@ -112,6 +112,20 @@ public String propertyTypeNameFor(
return objectTypeNameFor(owningType, schemaType) + "__" + otoa.asciiId() + "__gqlv_property";
}
+ public String propertyAutocompleteWindowTypeNameFor(
+ final ObjectSpecification owningType,
+ final OneToOneAssociation otoa,
+ final SchemaType schemaType) {
+ return propertyTypeNameFor(owningType, otoa, schemaType) + "_autocomplete_window";
+ }
+
+ public String actionParamAutocompleteWindowTypeNameFor(
+ final ObjectSpecification owningType,
+ final ObjectActionParameter oap,
+ final SchemaType schemaType) {
+ return actionParamTypeNameFor(owningType, oap, schemaType) + "_autocomplete_window";
+ }
+
public String propertyLobTypeNameFor(
final ObjectSpecification owningType,
final OneToOneAssociation otoa,
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowOrdering.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowOrdering.java
new file mode 100644
index 00000000000..af958a9220d
--- /dev/null
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowOrdering.java
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.causeway.viewer.graphql.model.domain.rich.query;
+
+enum AutoCompleteWindowOrdering {
+ APPLICATION
+}
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParam.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParam.java
index 670ddcdc81b..3fd5650eff0 100644
--- a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParam.java
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParam.java
@@ -63,6 +63,7 @@ public class RichActionParamsParam
* Populated iff there is an autocomplete for this param
*/
private final RichActionParamsParamAutoComplete autoComplete;
+ private final RichActionParamsParamAutoCompleteWindow autoCompleteWindow;
/**
* Populated iff there is a default for this param
*/
@@ -88,6 +89,7 @@ public RichActionParamsParam(
this.disabled = null;
this.choices = null;
this.autoComplete = null;
+ this.autoCompleteWindow = null;
this.default_ = null;
this.validate = null;
this.datatype = null;
@@ -103,6 +105,9 @@ public RichActionParamsParam(
addChildFieldFor(this.disabled = new RichActionParamsParamDisabled(this, context));
addChildFieldFor(this.choices = new RichActionParamsParamChoices(this, context));
addChildFieldFor(this.autoComplete = new RichActionParamsParamAutoComplete(this, context));
+ addChildFieldFor(this.autoCompleteWindow = oap.hasAutoComplete()
+ ? new RichActionParamsParamAutoCompleteWindow(this, context)
+ : null);
addChildFieldFor(this.default_ = new RichActionParamsParamDefault(this, context));
addChildFieldFor(this.validate = new RichActionParamsParamValidate(this, context));
addChildFieldFor(this.datatype = new RichActionParamsParamDatatype(this, context));
@@ -160,6 +165,9 @@ protected void addDataFetchersForChildren() {
if (autoComplete != null) {
autoComplete.addDataFetcher(this);
}
+ if (autoCompleteWindow != null) {
+ autoCompleteWindow.addDataFetcher(this);
+ }
if (default_ != null) {
default_.addDataFetcher(this);
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParamAutoCompleteWindow.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParamAutoCompleteWindow.java
new file mode 100644
index 00000000000..abefd5c8f90
--- /dev/null
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichActionParamsParamAutoCompleteWindow.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.causeway.viewer.graphql.model.domain.rich.query;
+
+import java.util.List;
+
+import graphql.schema.DataFetchingEnvironment;
+
+import org.apache.causeway.applib.annotation.Where;
+import org.apache.causeway.core.metamodel.consent.InteractionInitiatedBy;
+import org.apache.causeway.core.metamodel.interactions.managed.ManagedAction;
+import org.apache.causeway.core.metamodel.interactions.managed.ParameterNegotiationModel;
+import org.apache.causeway.core.metamodel.object.ManagedObject;
+import org.apache.causeway.core.metamodel.spec.feature.ObjectFeature;
+import org.apache.causeway.viewer.graphql.model.context.Context;
+import org.apache.causeway.viewer.graphql.model.domain.Environment;
+import org.apache.causeway.viewer.graphql.model.domain.TypeNames;
+import org.apache.causeway.viewer.graphql.model.domain.common.interactors.ActionParamInteractor;
+import org.apache.causeway.viewer.graphql.model.fetcher.BookmarkedPojo;
+import org.apache.causeway.viewer.graphql.model.types.TypeMapper;
+
+final class RichActionParamsParamAutoCompleteWindow extends RichAutoCompleteWindow {
+
+ private final ActionParamInteractor actionParamInteractor;
+
+ RichActionParamsParamAutoCompleteWindow(
+ final ActionParamInteractor actionParamInteractor,
+ final Context context) {
+ super(
+ context,
+ TypeNames.actionParamAutocompleteWindowTypeNameFor(
+ actionParamInteractor.getObjectSpecification(),
+ actionParamInteractor.getObjectActionParameter(),
+ actionParamInteractor.getSchemaType()),
+ context.typeMapper.outputTypeFor(
+ actionParamInteractor.getObjectActionParameter().getElementType(),
+ actionParamInteractor.getSchemaType()),
+ builder -> actionParamInteractor.addGqlArguments(
+ actionParamInteractor.getObjectMember(),
+ builder,
+ TypeMapper.InputContext.AUTOCOMPLETE,
+ actionParamInteractor.getParamNum()));
+ this.actionParamInteractor = actionParamInteractor;
+ }
+
+ @Override
+ protected List<Object> autocompleteItems(final DataFetchingEnvironment environment) {
+ var sourcePojo = BookmarkedPojo.sourceFrom(environment);
+ var objectSpecification = context.specificationLoader.loadSpecification(sourcePojo.getClass());
+ if (objectSpecification == null) {
+ return List.of();
+ }
+
+ var objectAction = actionParamInteractor.getObjectMember();
+ var managedObject = ManagedObject.adaptSingular(objectSpecification, sourcePojo);
+ final ObjectFeature objectFeature = actionParamInteractor.getObjectActionParameter();
+ var objectActionParameter = objectAction.getParameterById(objectFeature.asciiId());
+ var argumentManagedObjects = actionParamInteractor.argumentManagedObjectsFor(
+ new Environment.For(environment), objectAction, context.bookmarkService);
+ var managedAction = ManagedAction.of(managedObject, objectAction, Where.ANYWHERE);
+ var pendingArgs = ParameterNegotiationModel.of(managedAction, argumentManagedObjects);
+ var search = environment.<String>getArgument(SEARCH_ARGUMENT);
+ return objectActionParameter.getAutoComplete(pendingArgs, search, InteractionInitiatedBy.USER).stream()
+ .map(ManagedObject::getPojo)
+ .toList();
+ }
+}
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichAutoCompleteWindow.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichAutoCompleteWindow.java
new file mode 100644
index 00000000000..1073ad3c42b
--- /dev/null
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichAutoCompleteWindow.java
@@ -0,0 +1,167 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.causeway.viewer.graphql.model.domain.rich.query;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
+
+import graphql.Scalars;
+import graphql.schema.DataFetchingEnvironment;
+import graphql.schema.GraphQLArgument;
+import graphql.schema.GraphQLEnumType;
+import graphql.schema.GraphQLFieldDefinition;
+import graphql.schema.GraphQLObjectType;
+import graphql.schema.GraphQLOutputType;
+
+import static graphql.schema.GraphQLEnumType.newEnum;
+import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
+import static graphql.schema.GraphQLList.list;
+import static graphql.schema.GraphQLNonNull.nonNull;
+import static graphql.schema.GraphQLObjectType.newObject;
+
+import org.apache.causeway.viewer.graphql.model.context.Context;
+import org.apache.causeway.viewer.graphql.model.domain.Element;
+import org.apache.causeway.viewer.graphql.model.exceptions.InvalidAutoCompleteWindowException;
+
+abstract class RichAutoCompleteWindow extends Element {
+
+ static final String SEARCH_ARGUMENT = "search";
+ static final String OFFSET_ARGUMENT = "offset";
+ static final String SIZE_ARGUMENT = "size";
+
+ private static final String ORDERING_TYPE_NAME = "rich__gqlv_autocomplete_window_ordering";
+
+ private final int defaultWindowSize;
+ private final int maxWindowSize;
+
+ RichAutoCompleteWindow(
+ final Context context,
+ final String resultTypeName,
+ final GraphQLOutputType itemType,
+ final Consumer<GraphQLFieldDefinition.Builder> dependentArguments) {
+ super(context);
+ this.defaultWindowSize = graphqlConfiguration.autocomplete().defaultWindowSize();
+ this.maxWindowSize = graphqlConfiguration.autocomplete().maxWindowSize();
+
+ var resultType = resultType(context, resultTypeName, itemType, orderingType(context));
+ var fieldBuilder = newFieldDefinition()
+ .name("autoCompleteWindow")
+ .description("Returns a bounded response window over one authoritative autocomplete execution; "
+ + "the configured maximum size is " + maxWindowSize + ".")
+ .type(resultType);
+ dependentArguments.accept(fieldBuilder);
+ fieldBuilder
+ .argument(GraphQLArgument.newArgument()
+ .name(SEARCH_ARGUMENT)
+ .type(nonNull(context.typeMapper.outputTypeFor(String.class))))
+ .argument(GraphQLArgument.newArgument()
+ .name(OFFSET_ARGUMENT)
+ .type(nonNull(Scalars.GraphQLInt))
+ .defaultValueProgrammatic(0))
+ .argument(GraphQLArgument.newArgument()
+ .name(SIZE_ARGUMENT)
+ .type(nonNull(Scalars.GraphQLInt))
+ .defaultValueProgrammatic(defaultWindowSize));
+ setField(fieldBuilder.build());
+ }
+
+ @Override
+ protected final Object fetchData(final DataFetchingEnvironment environment) {
+ var offset = environment.<Integer>getArgument(OFFSET_ARGUMENT);
+ var size = environment.<Integer>getArgument(SIZE_ARGUMENT);
+ validate(offset, size);
+
+ var items = autocompleteItems(environment);
+ var safeItems = items == null ? List.of() : List.copyOf(items);
+ var totalCount = safeItems.size();
+ var fromIndex = Math.min(offset, totalCount);
+ var toIndex = (int) Math.min(totalCount, (long) offset + size);
+ var selectedItems = List.copyOf(safeItems.subList(fromIndex, toIndex));
+
+ Map<String, Object> result = new LinkedHashMap<>();
+ result.put("items", selectedItems);
+ result.put("offset", offset);
+ result.put("requestedSize", size);
+ result.put("returnedCount", selectedItems.size());
+ result.put("totalCount", totalCount);
+ result.put("maximumSize", maxWindowSize);
+ result.put("hasPrevious", offset > 0 && totalCount > 0);
+ result.put("hasNext", (long) offset + selectedItems.size() < totalCount);
+ result.put("ordering", AutoCompleteWindowOrdering.APPLICATION);
+ return Map.copyOf(result);
+ }
+
+ protected abstract List<Object> autocompleteItems(DataFetchingEnvironment environment);
+
+ private void validate(final Integer offset, final Integer size) {
+ if (offset == null || offset < 0) {
+ throw new InvalidAutoCompleteWindowException(
+ "Autocomplete window offset must be zero or greater.");
+ }
+ if (size == null || size < 1) {
+ throw new InvalidAutoCompleteWindowException(
+ "Autocomplete window size must be greater than zero.");
+ }
+ if (size > maxWindowSize) {
+ throw new InvalidAutoCompleteWindowException(
+ "Autocomplete window size exceeds the configured maximum of " + maxWindowSize + ".");
+ }
+ }
+
+ private static GraphQLEnumType orderingType(final Context context) {
+ return context.graphQLTypeRegistry.lookup(ORDERING_TYPE_NAME, GraphQLEnumType.class)
+ .orElseGet(() -> {
+ var type = newEnum()
+ .name(ORDERING_TYPE_NAME)
+ .description("How autocomplete items were ordered before selecting a response window.")
+ .value(AutoCompleteWindowOrdering.APPLICATION.name(), AutoCompleteWindowOrdering.APPLICATION,
+ "The authoritative application autocomplete encounter order for this execution.")
+ .build();
+ context.graphQLTypeRegistry.addTypeIfNotAlreadyPresent(type);
+ return type;
+ });
+ }
+
+ private static GraphQLObjectType resultType(
+ final Context context,
+ final String resultTypeName,
+ final GraphQLOutputType itemType,
+ final GraphQLEnumType orderingType) {
+ return context.graphQLTypeRegistry.lookup(resultTypeName, GraphQLObjectType.class)
+ .orElseGet(() -> {
+ var type = newObject()
+ .name(resultTypeName)
+ .description("A bounded response window over one Causeway autocomplete execution.")
+ .field(newFieldDefinition().name("items").type(list(itemType)))
+ .field(newFieldDefinition().name("offset").type(nonNull(Scalars.GraphQLInt)))
+ .field(newFieldDefinition().name("requestedSize").type(nonNull(Scalars.GraphQLInt)))
+ .field(newFieldDefinition().name("returnedCount").type(nonNull(Scalars.GraphQLInt)))
+ .field(newFieldDefinition().name("totalCount").type(nonNull(Scalars.GraphQLInt)))
+ .field(newFieldDefinition().name("maximumSize").type(nonNull(Scalars.GraphQLInt)))
+ .field(newFieldDefinition().name("hasPrevious").type(nonNull(Scalars.GraphQLBoolean)))
+ .field(newFieldDefinition().name("hasNext").type(nonNull(Scalars.GraphQLBoolean)))
+ .field(newFieldDefinition().name("ordering").type(nonNull(orderingType)))
+ .build();
+ context.graphQLTypeRegistry.addTypeIfNotAlreadyPresent(type);
+ return type;
+ });
+ }
+}
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichProperty.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichProperty.java
index 164eac7e4d0..7adee4d8b58 100644
--- a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichProperty.java
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichProperty.java
@@ -55,6 +55,7 @@ public class RichProperty
* Populated iff there is an autoComplete
*/
private final RichPropertyAutoComplete autoComplete;
+ private final RichPropertyAutoCompleteWindow autoCompleteWindow;
private final RichPropertyValidate validate;
/**
* Populated iff the API variant allows for it.
@@ -74,6 +75,7 @@ public RichProperty(
this.disabled = null;
this.choices = null;
this.autoComplete = null;
+ this.autoCompleteWindow = null;
this.validate = null;
this.set = null;
this.datatype = null;
@@ -94,6 +96,9 @@ public RichProperty(
addChildFieldFor(this.validate = new RichPropertyValidate(this, context));
addChildFieldFor(this.choices = new RichPropertyChoices(this, context));
addChildFieldFor(this.autoComplete = new RichPropertyAutoComplete(this, context));
+ addChildFieldFor(this.autoCompleteWindow = otoa.hasAutoComplete()
+ ? new RichPropertyAutoCompleteWindow(this, context)
+ : null);
addChildFieldFor(this.set = isSetterAllowed() ? new RichPropertySet(this, context) : null);
addChildFieldFor(this.datatype = new RichPropertyDatatype(this, context));
@@ -162,6 +167,9 @@ protected void addDataFetchersForChildren() {
if(autoComplete != null) {
autoComplete.addDataFetcher(this);
}
+ if (autoCompleteWindow != null) {
+ autoCompleteWindow.addDataFetcher(this);
+ }
validate.addDataFetcher(this);
if (set != null) {
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichPropertyAutoCompleteWindow.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichPropertyAutoCompleteWindow.java
new file mode 100644
index 00000000000..de54af29691
--- /dev/null
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/RichPropertyAutoCompleteWindow.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.causeway.viewer.graphql.model.domain.rich.query;
+
+import java.util.List;
+
+import graphql.schema.DataFetchingEnvironment;
+
+import org.apache.causeway.core.metamodel.consent.InteractionInitiatedBy;
+import org.apache.causeway.core.metamodel.object.ManagedObject;
+import org.apache.causeway.core.metamodel.spec.feature.OneToOneAssociation;
+import org.apache.causeway.viewer.graphql.model.context.Context;
+import org.apache.causeway.viewer.graphql.model.domain.SchemaType;
+import org.apache.causeway.viewer.graphql.model.domain.TypeNames;
+import org.apache.causeway.viewer.graphql.model.domain.common.interactors.MemberInteractor;
+import org.apache.causeway.viewer.graphql.model.fetcher.BookmarkedPojo;
+
+final class RichPropertyAutoCompleteWindow extends RichAutoCompleteWindow {
+
+ private final MemberInteractor<OneToOneAssociation> memberInteractor;
+
+ RichPropertyAutoCompleteWindow(
+ final MemberInteractor<OneToOneAssociation> memberInteractor,
+ final Context context) {
+ super(
+ context,
+ TypeNames.propertyAutocompleteWindowTypeNameFor(
+ memberInteractor.getObjectSpecification(),
+ memberInteractor.getObjectMember(),
+ memberInteractor.getSchemaType()),
+ context.typeMapper.outputTypeFor(
+ memberInteractor.getObjectMember().getElementType(), SchemaType.RICH),
+ builder -> { });
+ this.memberInteractor = memberInteractor;
+ }
+
+ @Override
+ protected List<Object> autocompleteItems(final DataFetchingEnvironment environment) {
+ var sourcePojo = BookmarkedPojo.sourceFrom(environment);
+ var objectSpecification = context.specificationLoader.loadSpecification(sourcePojo.getClass());
+ if (objectSpecification == null) {
+ return List.of();
+ }
+
+ var association = memberInteractor.getObjectMember();
+ var managedObject = ManagedObject.adaptSingular(objectSpecification, sourcePojo);
+ var search = environment.<String>getArgument(SEARCH_ARGUMENT);
+ return association.getAutoComplete(managedObject, search, InteractionInitiatedBy.USER).stream()
+ .map(ManagedObject::getPojo)
+ .toList();
+ }
+}
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/exceptions/InvalidAutoCompleteWindowException.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/exceptions/InvalidAutoCompleteWindowException.java
new file mode 100644
index 00000000000..2d3d2f3f190
--- /dev/null
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/exceptions/InvalidAutoCompleteWindowException.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.causeway.viewer.graphql.model.exceptions;
+
+public class InvalidAutoCompleteWindowException extends InteractionException {
+
+ public InvalidAutoCompleteWindowException(final String message) {
+ super(message);
+ }
+}
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java
index 32364dbecf1..f023fdb1887 100644
--- a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java
@@ -57,11 +57,11 @@ public class GraphQLTypeRegistry {
Set<GraphQLType> graphQLTypes = new HashSet<>();
- public Set<GraphQLType> getGraphQLTypes() {
- return Collections.unmodifiableSet(graphQLTypes);
+ public synchronized Set<GraphQLType> getGraphQLTypes() {
+ return Collections.unmodifiableSet(new HashSet<>(graphQLTypes));
}
- void addTypeIfNotAlreadyPresent(
+ synchronized void addTypeIfNotAlreadyPresent(
final GraphQLObjectType typeToAdd,
final String logicalTypeName){
@@ -73,7 +73,7 @@ void addTypeIfNotAlreadyPresent(
graphQLTypes.add(typeToAdd);
}
- public GraphQLEnumType addEnumTypeIfNotAlreadyPresent(
+ public synchronized GraphQLEnumType addEnumTypeIfNotAlreadyPresent(
final Class<?> typeToAdd,
final SchemaType schemaType) {
var objectSpec = contextProvider.get().specificationLoader.loadSpecification(typeToAdd);
@@ -98,7 +98,7 @@ public GraphQLEnumType addEnumTypeIfNotAlreadyPresent(
return enumType;
}
- public void addTypeIfNotAlreadyPresent(final GraphQLType typeToAdd) {
+ public synchronized void addTypeIfNotAlreadyPresent(final GraphQLType typeToAdd) {
if (typeToAdd instanceof GraphQLEnumType) {
addTypeIfNotAlreadyPresent((GraphQLEnumType) typeToAdd);
@@ -131,7 +131,7 @@ public void addTypeIfNotAlreadyPresent(final GraphQLType typeToAdd) {
log.warn("GraphQLType {} not yet implemented", typeToAdd.getClass().getName());
}
- void addTypeIfNotAlreadyPresent(final GraphQLEnumType typeToAdd){
+ synchronized void addTypeIfNotAlreadyPresent(final GraphQLEnumType typeToAdd){
if (isPresent(typeToAdd, GraphQLEnumType.class)){
// For now we just log and skip
log.debug("GraphQLEnumType for {} already present", typeToAdd.getName());
@@ -140,7 +140,7 @@ void addTypeIfNotAlreadyPresent(final GraphQLEnumType typeToAdd){
add(typeToAdd);
}
- void addTypeIfNotAlreadyPresent(final GraphQLObjectType typeToAdd){
+ synchronized void addTypeIfNotAlreadyPresent(final GraphQLObjectType typeToAdd){
if (isPresent(typeToAdd, GraphQLObjectType.class)){
// For now we just log and skip
log.debug("GraphQLObjectType for {} already present", typeToAdd.getName());
@@ -149,7 +149,7 @@ void addTypeIfNotAlreadyPresent(final GraphQLObjectType typeToAdd){
add(typeToAdd);
}
- void addTypeIfNotAlreadyPresent(final GraphQLInputObjectType typeToAdd) {
+ synchronized void addTypeIfNotAlreadyPresent(final GraphQLInputObjectType typeToAdd) {
if (isPresent(typeToAdd, GraphQLInputObjectType.class)){
// For now we just log and skip
log.debug("GraphQLInputObjectType for {} already present", typeToAdd.getName());
@@ -158,7 +158,7 @@ void addTypeIfNotAlreadyPresent(final GraphQLInputObjectType typeToAdd) {
add(typeToAdd);
}
- public GraphQLUnionType addUnionTypeIfNotAlreadyPresent(final GraphQLUnionType typeToAdd) {
+ public synchronized GraphQLUnionType addUnionTypeIfNotAlreadyPresent(final GraphQLUnionType typeToAdd) {
var existing = lookup(typeToAdd.getName(), GraphQLUnionType.class);
if (existing.isPresent()) {
var existingType = existing.get();
@@ -190,7 +190,7 @@ private boolean isPresent(
.anyMatch(ot -> ot.getName().equals(typeToAdd.getName()));
}
- public <T extends GraphQLNamedType> Optional<T> lookup(
+ public synchronized <T extends GraphQLNamedType> Optional<T> lookup(
final String typeName,
final Class<T> cls) {
return graphQLTypes.stream()
diff --git a/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowConfigurationTest.java b/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowConfigurationTest.java
new file mode 100644
index 00000000000..83f9cbf2373
--- /dev/null
+++ b/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/domain/rich/query/AutoCompleteWindowConfigurationTest.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.causeway.viewer.graphql.model.domain.rich.query;
+
+import org.junit.jupiter.api.Test;
+
+import org.apache.causeway.core.config.CausewayConfiguration;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class AutoCompleteWindowConfigurationTest {
+
+ @Test
+ void acceptsAValidDefaultAndMaximum() {
+ assertDoesNotThrow(() -> new CausewayConfiguration.Viewer.Graphql.Autocomplete(20, 100));
+ }
+
+ @Test
+ void rejectsADefaultAboveTheMaximum() {
+ assertThrows(IllegalArgumentException.class,
+ () -> new CausewayConfiguration.Viewer.Graphql.Autocomplete(101, 100));
+ }
+}
diff --git a/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java b/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java
index 25ea4b4e431..08be57dd075 100644
--- a/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java
+++ b/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java
@@ -20,12 +20,14 @@
import java.util.Set;
import java.util.stream.Collectors;
+import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
import graphql.schema.GraphQLTypeReference;
import graphql.schema.GraphQLUnionType;
+import static graphql.schema.GraphQLObjectType.newObject;
import static graphql.schema.GraphQLUnionType.newUnionType;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
@@ -46,6 +48,16 @@ void repeatedUnionRegistrationMergesPossibleTypesByName() {
assertEquals(1, registry.getGraphQLTypes().size());
}
+ @Test
+ void concurrentRegistrationRetainsEveryDistinctType() {
+ var registry = new GraphQLTypeRegistry(null);
+
+ IntStream.range(0, 1_000).parallel().forEach(index ->
+ registry.addTypeIfNotAlreadyPresent(newObject().name("Type" + index).build()));
+
+ assertEquals(1_000, registry.getGraphQLTypes().size());
+ }
+
private static GraphQLUnionType union(final String name, final String... possibleTypes) {
var builder = newUnionType().name(name);
for (var possibleType : possibleTypes) {
diff --git a/viewers/webcomponents/foundation/USAGE.adoc b/viewers/webcomponents/foundation/USAGE.adoc
index e92ceb2e4a3..d6240ac8f5a 100644
--- a/viewers/webcomponents/foundation/USAGE.adoc
+++ b/viewers/webcomponents/foundation/USAGE.adoc
@@ -318,8 +318,12 @@ await import('/causeway-webcomponents/index.mjs');
----
Eligible fixed choices must contain stable object identities and remain within `maximumResults`.
-Eligible autocomplete inputs use the existing public GraphQL search operation, debounce for 250 milliseconds, cancel superseded work, and reject stale route generations.
-The current GraphQL operation is not server-paged; the maximum is an honest accepted-response bound rather than a page size, and an over-bound result produces a refinement error instead of silent truncation.
+Eligible autocomplete inputs prefer the advertised public `autoCompleteWindow` field, debounce filter changes, request the introspected default page size, cancel superseded work, and reject stale route generations.
+The window is an honest bounded server response slice over one authoritative application autocomplete execution.
+It reports total and continuation metadata but does not claim persistence query pushdown or a cross-request snapshot.
+The internal Vaadin data provider maps its filter, page, and page-size callback to semantic context requests and receives authoritative items and total count without exposing Vaadin APIs to applications.
+When only legacy `autoComplete` exists, `maximumResults` remains an accepted complete-response bound and an over-bound result produces a refinement error instead of silent truncation.
+Native autocomplete renders the bounded first window and states when more matches require refinement.
A list-valued input selects Multi-Select Combo Box only when the introspected input and GraphQL interaction already provide authoritative list pending-value semantics.
Unsupported shapes, disabled configuration, over-bound fixed choices, module failure, and rollback retain or recover the existing editor.
diff --git a/viewers/webcomponents/foundation/src/editor-registry.mjs b/viewers/webcomponents/foundation/src/editor-registry.mjs
index 9f360e0e60d..8ac3536e44f 100644
--- a/viewers/webcomponents/foundation/src/editor-registry.mjs
+++ b/viewers/webcomponents/foundation/src/editor-registry.mjs
@@ -90,7 +90,10 @@ const autoCompleteEditor = Object.freeze({
const current = context.value && typeof context.value === 'object'
? normalizeChoice(context.value).encoded
: context.value ?? '';
- return `<input type="text" ${inputAttributes(context)} value="${escapeHtml(current)}" list="${escapeHtml(listId)}"><datalist id="${escapeHtml(listId)}">${options}</datalist>`;
+ const continuation = context.hasMoreSuggestions === true
+ ? '<span class="causeway-autocomplete-continuation" role="status">More matches are available; refine the search.</span>'
+ : '';
+ return `<input type="text" ${inputAttributes(context)} value="${escapeHtml(current)}" list="${escapeHtml(listId)}"><datalist id="${escapeHtml(listId)}">${options}</datalist>${continuation}`;
},
parse: ({value, suggestions = []}) => {
const match = suggestions.map(normalizeChoice).find(choice => choice.encoded === String(value));
diff --git a/viewers/webcomponents/foundation/src/graphql-client.mjs b/viewers/webcomponents/foundation/src/graphql-client.mjs
index 528c91698e6..5dbf98395e0 100644
--- a/viewers/webcomponents/foundation/src/graphql-client.mjs
+++ b/viewers/webcomponents/foundation/src/graphql-client.mjs
@@ -567,9 +567,9 @@ function referencedInteractionTypeNames(typeDescription, generatedTypeName, sche
const consider = (typeRef, fieldName = '') => {
const typeName = namedType(typeRef);
const kind = innermostType(typeRef)?.kind;
- const choiceValue = ['choices', 'default', 'autoComplete'].includes(fieldName)
+ const choiceValue = ['choices', 'default', 'autoComplete', 'autoCompleteWindow'].includes(fieldName)
&& ['OBJECT', 'INTERFACE', 'UNION'].includes(kind);
- const objectValue = ['get', 'rows'].includes(fieldName)
+ const objectValue = ['get', 'rows', 'items'].includes(fieldName)
&& ['OBJECT', 'INTERFACE', 'UNION'].includes(kind);
const objectMetadata = fieldName === '_meta' && kind === 'OBJECT';
if (typeName && (schemaNames.isReachableSupportType(generatedTypeName, typeName)
diff --git a/viewers/webcomponents/foundation/src/interaction-controller-element.mjs b/viewers/webcomponents/foundation/src/interaction-controller-element.mjs
index fc7b0425af4..a082bb2dd08 100644
--- a/viewers/webcomponents/foundation/src/interaction-controller-element.mjs
+++ b/viewers/webcomponents/foundation/src/interaction-controller-element.mjs
@@ -69,7 +69,16 @@ export class CausewayInteractionControllerElement extends HTMLElement {
return;
}
event.stopPropagation();
- void this.loadParameterAutoComplete(parameterId, event.detail.search);
+ const request = event.detail;
+ if (typeof request.respond === 'function') {
+ void this.loadParameterAutoComplete(parameterId, request.search, {
+ offset: request.offset,
+ size: request.size,
+ publish: false
+ }).then(result => request.respond(result));
+ } else {
+ void this.loadParameterAutoComplete(parameterId, request.search);
+ }
});
this.addEventListener('causeway-reference-escape', event => {
if (this.promptState) {
@@ -240,7 +249,7 @@ export class CausewayInteractionControllerElement extends HTMLElement {
return true;
}
- async loadParameterAutoComplete(parameterId, search) {
+ async loadParameterAutoComplete(parameterId, search, {offset = 0, size = null, publish = true} = {}) {
const parameter = this.promptState?.parameters.find(candidate => candidate.id === parameterId);
if (!parameter?.fields.has('autoComplete') || this.promptState.status === InteractionStatus.INVOKING) {
return {status: InteractionStatus.UNSUPPORTED, data: null, errors: []};
@@ -249,13 +258,24 @@ export class CausewayInteractionControllerElement extends HTMLElement {
const controller = new AbortController();
this.autoCompleteController = controller;
const generation = ++this.autoCompleteGeneration;
- const result = await this.promptState.context.autoCompleteActionParameter(
- this.promptState.actionId,
- parameterId,
- search,
- this.promptState.values,
- {signal: controller.signal}
- );
+ const {maximumResults} = causewayReferenceWidgetConfiguration();
+ const requestedSize = size ?? parameter.autoCompleteWindow?.sizeDefault ?? maximumResults;
+ const context = this.promptState.context;
+ const result = typeof context.autoCompleteActionParameterWindow === 'function'
+ ? await context.autoCompleteActionParameterWindow(
+ this.promptState.actionId,
+ parameterId,
+ search,
+ this.promptState.values,
+ {offset, size: requestedSize, signal: controller.signal}
+ )
+ : legacyWindowResult(await context.autoCompleteActionParameter(
+ this.promptState.actionId,
+ parameterId,
+ search,
+ this.promptState.values,
+ {signal: controller.signal}
+ ), offset, requestedSize);
if (generation !== this.autoCompleteGeneration || controller.signal.aborted || !this.promptState) {
return {...result, status: InteractionStatus.OBSOLETE};
}
@@ -267,22 +287,28 @@ export class CausewayInteractionControllerElement extends HTMLElement {
}
return result;
}
- const suggestions = [...(result.data ?? [])];
- const {maximumResults} = causewayReferenceWidgetConfiguration();
- if (suggestions.length > maximumResults) {
+ const window = result.data;
+ const suggestions = [...(window?.items ?? [])];
+ if (window?.windowed !== true && suggestions.length > maximumResults) {
const message = `More than ${maximumResults} references matched. Refine the search.`;
this.promptState = Object.freeze({...this.promptState, status: InteractionStatus.FAILED, error: message});
this.#publishPromptState();
this.render();
return {status: InteractionStatus.FAILED, data: null, errors: [{message, code: 'AUTOCOMPLETE_RESULT_LIMIT'}]};
}
- const parameters = Object.freeze(this.promptState.parameters.map(candidate => candidate.id === parameterId
- ? Object.freeze({...candidate, state: Object.freeze({...candidate.state, suggestions: Object.freeze(suggestions)})})
- : candidate));
- this.promptState = Object.freeze({...this.promptState, status: InteractionStatus.EDITING, parameters, error: null});
- this.#publishPromptState();
- this.render();
- this.#focusFirstControl();
+ if (publish) {
+ const parameters = Object.freeze(this.promptState.parameters.map(candidate => candidate.id === parameterId
+ ? Object.freeze({...candidate, state: Object.freeze({
+ ...candidate.state,
+ suggestions: Object.freeze(suggestions),
+ autoCompleteWindow: window
+ })})
+ : candidate));
+ this.promptState = Object.freeze({...this.promptState, status: InteractionStatus.EDITING, parameters, error: null});
+ this.#publishPromptState();
+ this.render();
+ this.#focusFirstControl();
+ }
return result;
}
@@ -423,6 +449,12 @@ export class CausewayInteractionControllerElement extends HTMLElement {
}
const choices = parameter.state?.choices ?? parameter.enumValues ?? [];
const rendered = renderCausewayEditor(this.#parameterEditorContext(parameter, choices), this._editorRegistry);
+ if (rendered.editor.id === 'autocomplete' && event.type === 'input') {
+ clearTimeout(this.parameterTimer);
+ const search = String(event.target.value ?? '');
+ this.parameterTimer = setTimeout(() => void this.loadParameterAutoComplete(parameterId, search), 250);
+ return;
+ }
try {
const value = parseCausewayEditorValue(rendered.editor, {
value: event.target.value,
@@ -524,6 +556,9 @@ export class CausewayInteractionControllerElement extends HTMLElement {
choices,
suggestions: parameter.state?.suggestions ?? [],
autoComplete: parameter.fields.has('autoComplete'),
+ autoCompleteWindow: Boolean(parameter.autoCompleteWindow),
+ autoCompletePageSize: parameter.autoCompleteWindow?.sizeDefault ?? null,
+ hasMoreSuggestions: parameter.state?.autoCompleteWindow?.hasNext === true,
enumValues: parameter.enumValues,
inputType: parameter.inputType,
semanticType: parameter.state?.datatype ?? null,
@@ -630,6 +665,25 @@ export class CausewayInteractionControllerElement extends HTMLElement {
}
}
+function legacyWindowResult(result, offset, requestedSize) {
+ if (result?.status !== InteractionStatus.SUCCESS || !Array.isArray(result.data)) return result;
+ return {
+ ...result,
+ data: Object.freeze({
+ items: Object.freeze([...result.data]),
+ offset,
+ requestedSize,
+ returnedCount: result.data.length,
+ totalCount: result.data.length,
+ maximumSize: null,
+ hasPrevious: false,
+ hasNext: false,
+ ordering: 'LEGACY',
+ windowed: false
+ })
+ };
+}
+
function focusRestoreTarget(source) {
const panel = source?.closest?.('[data-causeway-menu-panel]');
const panelId = panel?.id;
diff --git a/viewers/webcomponents/foundation/src/interaction-operations.mjs b/viewers/webcomponents/foundation/src/interaction-operations.mjs
index 3d1f63d8e1b..fe60f591d4d 100644
--- a/viewers/webcomponents/foundation/src/interaction-operations.mjs
+++ b/viewers/webcomponents/foundation/src/interaction-operations.mjs
@@ -23,6 +23,58 @@ import {INLINE_FRAGMENTS} from './selection.mjs';
export const MAX_DIRECT_FRAGMENT_TYPES = 8;
+const AUTO_COMPLETE_WINDOW_FIELDS = Object.freeze([
+ 'offset',
+ 'requestedSize',
+ 'returnedCount',
+ 'totalCount',
+ 'maximumSize',
+ 'hasPrevious',
+ 'hasNext',
+ 'ordering'
+]);
+
+export function autoCompleteWindowPlan(field, types) {
+ const typeName = namedType(field?.type);
+ const typeDescription = types.get(typeName) ?? null;
+ const fields = fieldsByName(typeDescription);
+ const itemsField = fields.get('items');
+ if (!field || !typeDescription || !itemsField) {
+ return null;
+ }
+ const args = fieldsByName({fields: field.args ?? []});
+ const selection = Object.fromEntries(AUTO_COMPLETE_WINDOW_FIELDS
+ .filter(name => fields.has(name))
+ .map(name => [name, true]));
+ selection.items = resultSelectionForType(itemsField.type, types) ?? true;
+ return Object.freeze({
+ typeName,
+ typeDescription,
+ itemsField,
+ selection: Object.freeze(selection),
+ offsetDefault: integerDefault(args.get('offset')?.defaultValue, 0),
+ sizeDefault: integerDefault(args.get('size')?.defaultValue, null)
+ });
+}
+
+export function normalizeAutoCompleteWindow(value, {legacy = false, offset = 0, requestedSize = null} = {}) {
+ const items = Array.isArray(legacy ? value : value?.items) ? [...(legacy ? value : value.items)] : [];
+ const totalCount = legacy ? items.length : nonNegativeInteger(value?.totalCount, items.length);
+ const effectiveOffset = legacy ? offset : nonNegativeInteger(value?.offset, offset);
+ return Object.freeze({
+ items: Object.freeze(items),
+ offset: effectiveOffset,
+ requestedSize: legacy ? requestedSize : positiveInteger(value?.requestedSize, requestedSize ?? items.length),
+ returnedCount: legacy ? items.length : nonNegativeInteger(value?.returnedCount, items.length),
+ totalCount,
+ maximumSize: legacy ? null : positiveInteger(value?.maximumSize, null),
+ hasPrevious: legacy ? effectiveOffset > 0 : value?.hasPrevious === true,
+ hasNext: legacy ? false : value?.hasNext === true,
+ ordering: legacy ? 'LEGACY' : String(value?.ordering ?? 'APPLICATION'),
+ windowed: !legacy
+ });
+}
+
export function buildDescribeOperationRootsOperation() {
return Object.freeze({
document: 'query CausewayDescribeOperationRoots { __schema { queryType { name } mutationType { name } } }',
@@ -240,6 +292,22 @@ export function resultSelectionForType(typeRef, types) {
: {__typename: true};
}
+function integerDefault(value, fallback) {
+ if (value == null) return fallback;
+ const parsed = Number(value);
+ return Number.isSafeInteger(parsed) ? parsed : fallback;
+}
+
+function nonNegativeInteger(value, fallback) {
+ const parsed = Number(value);
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : fallback;
+}
+
+function positiveInteger(value, fallback) {
+ const parsed = Number(value);
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
+}
+
function renderExecutableSelection({
selection,
typeDescription,
diff --git a/viewers/webcomponents/foundation/src/object-context-controller.mjs b/viewers/webcomponents/foundation/src/object-context-controller.mjs
index de520fec19d..2c53f422544 100644
--- a/viewers/webcomponents/foundation/src/object-context-controller.mjs
+++ b/viewers/webcomponents/foundation/src/object-context-controller.mjs
@@ -29,9 +29,11 @@ import {createSemanticEvent, OBJECT_CONTEXT_STATE_EVENT} from './context-events.
import {fieldsByName, namedType} from './introspection.mjs';
import {
argumentsFromValues,
+ autoCompleteWindowPlan,
commandSelection,
MAX_DIRECT_FRAGMENT_TYPES,
metadataSelectionForType,
+ normalizeAutoCompleteWindow,
resultSelectionForType
} from './interaction-operations.mjs';
import {
@@ -159,12 +161,16 @@ export class ObjectContextController extends EventTarget {
const mutationFieldName = mutationFieldNameFor(description, member);
const mutationField = mutationType ? fieldsByName(mutationType).get(mutationFieldName) ?? null : null;
const enumValues = descriptor.value?.typeDescription?.enumValues?.map(value => value.name) ?? [];
+ const autoCompleteWindow = autoCompleteWindowPlan(
+ descriptor.fields.get('autoCompleteWindow'), description.types);
return Object.freeze({
descriptor,
editable: descriptor.fields.has('set') || Boolean(mutationField),
validate: descriptor.fields.has('validate'),
choices: descriptor.fields.has('choices'),
autoComplete: descriptor.fields.has('autoComplete'),
+ autoCompleteWindow: Boolean(autoCompleteWindow),
+ autoCompleteWindowSize: autoCompleteWindow?.sizeDefault ?? null,
mutationFieldName: mutationField ? mutationFieldName : null,
inputType: propertyInputType(descriptor, mutationField, member),
enumValues: Object.freeze(enumValues)
@@ -230,6 +236,38 @@ export class ObjectContextController extends EventTarget {
});
}
+ async autoCompletePropertyWindow(member, search, {offset = 0, size = null, signal} = {}) {
+ const {description, descriptor} = await this.#memberDescriptor(member, 'property');
+ const field = descriptor.fields.get('autoCompleteWindow');
+ if (!field) {
+ const legacy = await this.autoCompleteProperty(member, search, {signal});
+ return legacy.status === InteractionStatus.SUCCESS
+ ? interactionResult(legacy.status, normalizeAutoCompleteWindow(legacy.data, {
+ legacy: true, offset, requestedSize: size
+ }), legacy.errors, legacy.operation)
+ : legacy;
+ }
+ return this.#runTransient(`property:${member}:autocomplete`, signal, async commandSignal => {
+ const plan = autoCompleteWindowPlan(field, description.types);
+ if (!plan) {
+ return interactionResult(InteractionStatus.UNSUPPORTED, null, [commandError(
+ `Property '${member}' exposes an incomplete autocomplete window.`)]);
+ }
+ const args = windowArguments(field, search, offset, size);
+ const result = await this.client.executeObjectInteraction({
+ description,
+ identity: this.identity,
+ selection: {[member]: {autoCompleteWindow: commandSelection(args, plan.selection)}},
+ operationName: 'CausewayPropertyAutoCompleteWindow',
+ signal: commandSignal
+ });
+ return commandResponse(result, normalizeAutoCompleteWindow(
+ result.data?.[member]?.autoCompleteWindow ?? null,
+ {offset, requestedSize: size ?? plan.sizeDefault}
+ ));
+ });
+ }
+
async validateProperty(member, value, {signal} = {}) {
return this.#runTransient(`property:${member}:validate`, signal, async commandSignal => {
const {description, descriptor} = await this.#memberDescriptor(member, 'property');
@@ -302,11 +340,13 @@ export class ObjectContextController extends EventTarget {
const actionArgument = validateField?.args.find(argument => argument.name === field.name) ?? null;
const inputType = actionArgument?.type ?? parameterInputType(wrapper);
const enumType = inputType ? description.types.get(namedType(inputType)) ?? null : null;
+ const fields = fieldsByName(wrapper);
return Object.freeze({
id: field.name,
description: field.description ?? null,
generatedTypeName: wrapper?.name ?? namedType(field.type),
- fields: fieldsByName(wrapper),
+ fields,
+ autoCompleteWindow: autoCompleteWindowPlan(fields.get('autoCompleteWindow'), description.types),
inputType,
enumValues: Object.freeze(enumType?.enumValues?.map(value => value.name) ?? [])
});
@@ -434,6 +474,48 @@ export class ObjectContextController extends EventTarget {
});
}
+ async autoCompleteActionParameterWindow(
+ member,
+ parameterId,
+ search,
+ values = {},
+ {offset = 0, size = null, signal} = {}
+ ) {
+ const {description} = await this.#memberDescriptor(member, 'action');
+ const capabilities = await this.describeActionInteraction(member);
+ const parameter = capabilities.parameters.find(candidate => candidate.id === parameterId);
+ const field = parameter?.fields.get('autoCompleteWindow');
+ if (!field) {
+ const legacy = await this.autoCompleteActionParameter(member, parameterId, search, values, {signal});
+ return legacy.status === InteractionStatus.SUCCESS
+ ? interactionResult(legacy.status, normalizeAutoCompleteWindow(legacy.data, {
+ legacy: true, offset, requestedSize: size
+ }), legacy.errors, legacy.operation)
+ : legacy;
+ }
+ return this.#runTransient(`action:${member}:${parameterId}:autocomplete`, signal, async commandSignal => {
+ const plan = autoCompleteWindowPlan(field, description.types);
+ if (!plan) {
+ return interactionResult(InteractionStatus.UNSUPPORTED, null, [commandError(
+ `Action parameter '${member}.${parameterId}' exposes an incomplete autocomplete window.`)]);
+ }
+ const args = {...argumentsFromValues(field, values), ...windowArguments(field, search, offset, size)};
+ const result = await this.client.executeObjectInteraction({
+ description,
+ identity: this.identity,
+ selection: {
+ [member]: {params: {[parameterId]: {autoCompleteWindow: commandSelection(args, plan.selection)}}}
+ },
+ operationName: 'CausewayActionParameterAutoCompleteWindow',
+ signal: commandSignal
+ });
+ return commandResponse(result, normalizeAutoCompleteWindow(
+ result.data?.[member]?.params?.[parameterId]?.autoCompleteWindow ?? null,
+ {offset, requestedSize: size ?? plan.sizeDefault}
+ ));
+ });
+ }
+
async validateAction(member, values = {}, {signal} = {}) {
return this.#runTransient(`action:${member}:validate`, signal, async commandSignal => {
const {description, descriptor} = await this.#memberDescriptor(member, 'action');
@@ -1009,6 +1091,12 @@ async function ensureResultTypes(client, description, typeRef, signal) {
}
}
+function windowArguments(field, search, offset, size) {
+ const values = {search, offset};
+ if (size != null) values.size = size;
+ return argumentsFromValues(field, values);
+}
+
function mutationFieldNameFor(description, member) {
return `${description.generatedFieldName}__${member}`;
}
diff --git a/viewers/webcomponents/foundation/src/property-element.mjs b/viewers/webcomponents/foundation/src/property-element.mjs
index 9d11b47f9a5..0b86fce3b42 100644
--- a/viewers/webcomponents/foundation/src/property-element.mjs
+++ b/viewers/webcomponents/foundation/src/property-element.mjs
@@ -72,7 +72,16 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
return;
}
event.stopPropagation();
- void this.loadAutoComplete(event.detail.search);
+ const request = event.detail;
+ if (typeof request.respond === 'function') {
+ void this.loadAutoComplete(request.search, {
+ offset: request.offset,
+ size: request.size,
+ publish: false
+ }).then(result => request.respond(result));
+ } else {
+ void this.loadAutoComplete(request.search);
+ }
});
this.addEventListener('causeway-reference-escape', event => {
if (this.interactionState) {
@@ -269,7 +278,7 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
return true;
}
- async loadAutoComplete(search) {
+ async loadAutoComplete(search, {offset = 0, size = null, publish = true} = {}) {
if (!this.interactionState?.capabilities?.autoComplete) {
return {status: InteractionStatus.UNSUPPORTED, data: null, errors: []};
}
@@ -277,7 +286,18 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
const controller = new AbortController();
this.autoCompleteController = controller;
const generation = ++this.autoCompleteGeneration;
- const result = await this._resolvedContext.autoCompleteProperty(this.member, search, {signal: controller.signal});
+ const {maximumResults} = causewayReferenceWidgetConfiguration();
+ const requestedSize = size
+ ?? this.interactionState.capabilities?.autoCompleteWindowSize
+ ?? maximumResults;
+ const result = typeof this._resolvedContext.autoCompletePropertyWindow === 'function'
+ ? await this._resolvedContext.autoCompletePropertyWindow(this.member, search, {
+ offset,
+ size: requestedSize,
+ signal: controller.signal
+ })
+ : legacyWindowResult(await this._resolvedContext.autoCompleteProperty(
+ this.member, search, {signal: controller.signal}), offset, requestedSize);
if (generation !== this.autoCompleteGeneration || controller.signal.aborted || !this.interactionState) {
return {...result, status: InteractionStatus.OBSOLETE};
}
@@ -291,20 +311,23 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
}
return result;
}
- const suggestions = [...(result.data ?? [])];
- const {maximumResults} = causewayReferenceWidgetConfiguration();
- if (suggestions.length > maximumResults) {
+ const window = result.data;
+ const suggestions = [...(window?.items ?? [])];
+ if (window?.windowed !== true && suggestions.length > maximumResults) {
const message = `More than ${maximumResults} references matched. Refine the search.`;
this.#setInteraction({...this.interactionState, status: InteractionStatus.FAILED, suggestions: Object.freeze([]), error: message});
return {status: InteractionStatus.FAILED, data: null, errors: [{message, code: 'AUTOCOMPLETE_RESULT_LIMIT'}]};
}
- this.interactionState = Object.freeze({
- ...this.interactionState,
- status: InteractionStatus.EDITING,
- suggestions: Object.freeze(suggestions),
- error: null
- });
- this.renderComponentState(this.componentState);
+ if (publish) {
+ this.interactionState = Object.freeze({
+ ...this.interactionState,
+ status: InteractionStatus.EDITING,
+ suggestions: Object.freeze(suggestions),
+ autoCompleteWindow: window,
+ error: null
+ });
+ this.renderComponentState(this.componentState);
+ }
return result;
}
@@ -429,6 +452,12 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
return;
}
const editor = this.interactionState.editor;
+ if (editor.id === 'autocomplete' && debounce) {
+ clearTimeout(this.validationTimer);
+ const search = String(event.target.value ?? '');
+ this.validationTimer = setTimeout(() => void this.loadAutoComplete(search), 250);
+ return;
+ }
try {
const value = parseCausewayEditorValue(editor, {
value: event.target.value,
@@ -502,6 +531,9 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
choices: interaction.choices ?? [],
suggestions: interaction.suggestions ?? [],
autoComplete: interaction.capabilities?.autoComplete === true,
+ autoCompleteWindow: interaction.capabilities?.autoCompleteWindow === true,
+ autoCompletePageSize: interaction.capabilities?.autoCompleteWindowSize ?? null,
+ hasMoreSuggestions: interaction.autoCompleteWindow?.hasNext === true,
enumValues: interaction.capabilities?.enumValues ?? [],
inputType: interaction.capabilities?.inputType,
semanticType: this.componentState?.data?.datatype ?? interaction.capabilities?.semanticType ?? null,
@@ -585,6 +617,25 @@ export class CausewayPropertyElement extends CausewayContextConsumerElement {
}
}
+function legacyWindowResult(result, offset, requestedSize) {
+ if (result?.status !== InteractionStatus.SUCCESS || !Array.isArray(result.data)) return result;
+ return {
+ ...result,
+ data: Object.freeze({
+ items: Object.freeze([...result.data]),
+ offset,
+ requestedSize,
+ returnedCount: result.data.length,
+ totalCount: result.data.length,
+ maximumSize: null,
+ hasPrevious: false,
+ hasNext: false,
+ ordering: 'LEGACY',
+ windowed: false
+ })
+ };
+}
+
function publicInteractionValue(editor, value) {
return editor?.codec?.sensitive === true ? null : value;
}
diff --git a/viewers/webcomponents/foundation/src/reference-widget.mjs b/viewers/webcomponents/foundation/src/reference-widget.mjs
index 3f403bdb28b..433aa8f38e7 100644
--- a/viewers/webcomponents/foundation/src/reference-widget.mjs
+++ b/viewers/webcomponents/foundation/src/reference-widget.mjs
@@ -70,6 +70,11 @@ export function renderCausewayReferenceWidget(context) {
if (context.disabled) attributes.push('disabled');
if (context.required) attributes.push('required');
if (context.autoComplete === true) attributes.push('data-autocomplete="true"');
+ if (context.autoCompleteWindow === true) {
+ attributes.push('data-autocomplete-window="true"');
+ attributes.push(`data-autocomplete-page-size="${positiveInteger(context.autoCompletePageSize, configuration.maximumResults)}"`);
+ }
+ if (context.hasMoreSuggestions === true) attributes.push('data-has-more-suggestions="true"');
if (multiple) attributes.push('multiple');
return `<causeway-reference-editor ${attributes.join(' ')}><span role="status">Loading reference editor…</span></causeway-reference-editor>`;
}
@@ -82,6 +87,8 @@ export class CausewayReferenceEditorElement extends HTMLElement {
this._searchTimer = null;
this._syncing = false;
this._value = null;
+ this._filterGeneration = 0;
+ this._activeFilter = null;
this.addEventListener('keydown', event => {
if (event.key === 'Escape' && this._control?.opened !== true) {
this.dispatchEvent(new CustomEvent('causeway-reference-escape', {bubbles: true, composed: true}));
@@ -130,7 +137,14 @@ export class CausewayReferenceEditorElement extends HTMLElement {
control.label = this.dataset.label || this.getAttribute('data-causeway-editor') || 'Reference';
control.itemLabelPath = 'title';
control.itemValuePath = 'id';
- control.items = this.#items();
+ control.itemIdPath = 'id';
+ if (this.dataset.autocompleteWindow === 'true') {
+ control.pageSize = positiveInteger(
+ Number(this.dataset.autocompletePageSize), configuration.maximumResults);
+ control.dataProvider = (params, callback) => this.#providePage(params, callback, generation);
+ } else {
+ control.items = this.#items();
+ }
if (this.hasAttribute('multiple')) control.autoExpandVertically = true;
control.clearButtonVisible = !this.hasAttribute('required');
control.required = this.hasAttribute('required');
@@ -138,7 +152,9 @@ export class CausewayReferenceEditorElement extends HTMLElement {
const describedBy = this.dataset.describedby;
if (describedBy) control.setAttribute('aria-describedby', describedBy);
if (this.dataset.invalid === 'true') control.setAttribute('invalid', '');
- control.addEventListener('filter-changed', event => this.#filterChanged(event));
+ if (this.dataset.autocompleteWindow !== 'true') {
+ control.addEventListener('filter-changed', event => this.#filterChanged(event));
+ }
const selectionEvent = this.hasAttribute('multiple') ? 'selected-items-changed' : 'selected-item-changed';
control.addEventListener(selectionEvent, event => this.#selectionChanged(event));
this.replaceChildren(control);
@@ -206,6 +222,48 @@ export class CausewayReferenceEditorElement extends HTMLElement {
}, 250);
}
+ #providePage(params, callback, connectionGeneration) {
+ const filter = String(params?.filter ?? '').trim();
+ if (filter.length < configuration.minimumSearchLength) {
+ callback([], 0);
+ return;
+ }
+ if (filter !== this._activeFilter) {
+ this._activeFilter = filter;
+ this._filterGeneration += 1;
+ }
+ const filterGeneration = this._filterGeneration;
+ const pageSize = positiveInteger(params?.pageSize, configuration.maximumResults);
+ const page = nonNegativeInteger(params?.page, 0);
+ let responded = false;
+ const respond = result => {
+ if (responded || !this.isConnected || connectionGeneration !== this._generation
+ || filterGeneration !== this._filterGeneration || filter !== this._activeFilter) {
+ return;
+ }
+ responded = true;
+ const window = result?.status === 'success' ? result.data : null;
+ if (!window) {
+ this.dataset.widgetError = result?.errors?.[0]?.message ?? 'Reference page request failed.';
+ } else {
+ delete this.dataset.widgetError;
+ }
+ const items = (window?.items ?? []).map(normalizeReference).filter(Boolean);
+ callback(items, Number(window?.totalCount ?? 0));
+ };
+ this.dispatchEvent(new CustomEvent('causeway-reference-search', {
+ bubbles: true,
+ composed: true,
+ detail: Object.freeze({
+ name: this.getAttribute('data-causeway-editor'),
+ search: filter,
+ offset: page * pageSize,
+ size: pageSize,
+ respond
+ })
+ }));
+ }
+
#selectionChanged(event) {
if (this._syncing) return;
const selected = event.detail?.value;
diff --git a/viewers/webcomponents/foundation/src/service-action-context.mjs b/viewers/webcomponents/foundation/src/service-action-context.mjs
index f6c3fa929f0..24cb32a613f 100644
--- a/viewers/webcomponents/foundation/src/service-action-context.mjs
+++ b/viewers/webcomponents/foundation/src/service-action-context.mjs
@@ -26,7 +26,13 @@ import {
secureActionInvocationResult
} from './action-dispatch.mjs';
import {fieldsByName, namedType} from './introspection.mjs';
-import {argumentsFromValues, commandSelection, resultSelectionForType} from './interaction-operations.mjs';
+import {
+ argumentsFromValues,
+ autoCompleteWindowPlan,
+ commandSelection,
+ normalizeAutoCompleteWindow,
+ resultSelectionForType
+} from './interaction-operations.mjs';
import {InteractionResultKind, InteractionStatus} from './types.mjs';
export class ServiceActionContextController {
@@ -206,6 +212,50 @@ export class ServiceActionContextController {
});
}
+ async autoCompleteActionParameterWindow(
+ actionId,
+ parameterId,
+ search,
+ values = {},
+ {offset = 0, size = null, signal} = {}
+ ) {
+ const description = await this.describeService();
+ const capabilities = await this.describeActionInteraction(actionId);
+ const parameter = capabilities.parameters.find(candidate => candidate.id === parameterId);
+ const field = parameter?.fields.get('autoCompleteWindow');
+ if (!field) {
+ const legacy = await this.autoCompleteActionParameter(actionId, parameterId, search, values, {signal});
+ return legacy.status === InteractionStatus.SUCCESS
+ ? interactionResult(legacy.status, normalizeAutoCompleteWindow(legacy.data, {
+ legacy: true, offset, requestedSize: size
+ }), legacy.errors, legacy.operation)
+ : legacy;
+ }
+ return this.#runTransient(`action:${actionId}:${parameterId}:autocomplete`, signal, async commandSignal => {
+ const plan = autoCompleteWindowPlan(field, description.types);
+ if (!plan) {
+ return interactionResult(InteractionStatus.UNSUPPORTED, null, [commandError(
+ `Service-action parameter '${actionId}.${parameterId}' exposes an incomplete autocomplete window.`)]);
+ }
+ const args = {
+ ...argumentsFromValues(field, values),
+ ...windowArguments(field, search, offset, size)
+ };
+ const result = await this.client.executeServiceInteraction({
+ description,
+ selection: {
+ [actionId]: {params: {[parameterId]: {autoCompleteWindow: commandSelection(args, plan.selection)}}}
+ },
+ operationName: 'CausewayServiceActionParameterAutoCompleteWindow',
+ signal: commandSignal
+ });
+ return commandResponse(result, normalizeAutoCompleteWindow(
+ result.data?.[actionId]?.params?.[parameterId]?.autoCompleteWindow ?? null,
+ {offset, requestedSize: size ?? plan.sizeDefault}
+ ));
+ });
+ }
+
async validateAction(actionId, values = {}, {signal} = {}) {
return this.#runTransient(`action:${actionId}:validate`, signal, async commandSignal => {
const description = await this.describeService();
@@ -306,11 +356,13 @@ export class ServiceActionContextController {
const actionArgument = validateField?.args.find(argument => argument.name === field.name) ?? null;
const inputType = actionArgument?.type ?? parameterInputType(wrapper);
const enumType = inputType ? description.types.get(namedType(inputType)) ?? null : null;
+ const fields = fieldsByName(wrapper);
return Object.freeze({
id: field.name,
description: field.description ?? null,
generatedTypeName: wrapper?.name ?? namedType(field.type),
- fields: fieldsByName(wrapper),
+ fields,
+ autoCompleteWindow: autoCompleteWindowPlan(fields.get('autoCompleteWindow'), description.types),
inputType,
enumValues: Object.freeze(enumType?.enumValues?.map(value => value.name) ?? [])
});
@@ -399,6 +451,12 @@ async function ensureResultTypes(client, description, typeRef, signal) {
}
}
+function windowArguments(field, search, offset, size) {
+ const values = {search, offset};
+ if (size != null) values.size = size;
+ return argumentsFromValues(field, values);
+}
+
function parameterInputType(wrapper) {
if (!wrapper) {
return null;
diff --git a/viewers/webcomponents/foundation/test/application-menu-client.test.mjs b/viewers/webcomponents/foundation/test/application-menu-client.test.mjs
index 83d5dc896c5..bfe5c73c49f 100644
--- a/viewers/webcomponents/foundation/test/application-menu-client.test.mjs
+++ b/viewers/webcomponents/foundation/test/application-menu-client.test.mjs
@@ -127,6 +127,23 @@ test('service action adapter reuses parameter preparation, validation, safe invo
assert.deepEqual(context.interactionTarget, {kind: 'service', logicalTypeName: SAMPLE_SERVICE_LOGICAL_TYPE});
});
+test('service action context executes advertised autocomplete windows', async () => {
+ const executor = createMenuGraphQLExecutor();
+ const client = new CausewayGraphQLClient({executor});
+ const context = new ServiceActionContextController({client, logicalTypeName: SAMPLE_SERVICE_LOGICAL_TYPE});
+
+ const result = await context.autoCompleteActionParameterWindow(
+ 'greet', 'name', 'Gr', {}, {offset: 2, size: 2});
+
+ assert.equal(result.status, InteractionStatus.SUCCESS);
+ assert.deepEqual(result.data.items, ['Grace']);
+ assert.equal(result.data.totalCount, 3);
+ const call = executor.serviceCalls.find(candidate =>
+ candidate.operationName === 'CausewayServiceActionParameterAutoCompleteWindow');
+ assert.deepEqual(Object.values(call.variables), ['Gr', 2, 2]);
+ assert.match(call.document, /autoCompleteWindow/);
+});
+
test('superseded service parameter preparation cannot replace the latest response', async () => {
const base = createMenuGraphQLExecutor();
let releaseFirst;
diff --git a/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs b/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs
index 3c0b63f4a59..de94c71062e 100644
--- a/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs
+++ b/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs
@@ -22,6 +22,8 @@ import {CAUSEWAY_MENU_BARS_NAMESPACE} from '../../src/menu-layout.mjs';
export const SAMPLE_SERVICE_LOGICAL_TYPE = 'causeway.webcomponents.sample.SampleMenu';
export const SAMPLE_SERVICE_FIELD = 'causeway_webcomponents_sample_SampleMenu';
export const SAMPLE_SERVICE_TYPE = 'rich__causeway_webcomponents_sample_SampleMenu';
+const GREET_PARAMETER_TYPE = `${SAMPLE_SERVICE_TYPE}__greet__name__gqlv_action_parameter`;
+const GREET_AUTOCOMPLETE_WINDOW_TYPE = `${GREET_PARAMETER_TYPE}_autocomplete_window`;
export function createMenuGraphQLTypes({menuBarsAvailable = true} = {}) {
const applicationFields = [
@@ -92,14 +94,27 @@ export function createMenuGraphQLTypes({menuBarsAvailable = true} = {}) {
[`${SAMPLE_SERVICE_TYPE}__greet__gqlv_action_params`, objectType(`${SAMPLE_SERVICE_TYPE}__greet__gqlv_action_params`, [
field('name', named(`${SAMPLE_SERVICE_TYPE}__greet__name__gqlv_action_parameter`))
])],
- [`${SAMPLE_SERVICE_TYPE}__greet__name__gqlv_action_parameter`, objectType(`${SAMPLE_SERVICE_TYPE}__greet__name__gqlv_action_parameter`, [
+ [GREET_PARAMETER_TYPE, objectType(GREET_PARAMETER_TYPE, [
field('hidden', scalar('Boolean'), [argument('name', scalar('String'))]),
field('disabled', scalar('String'), [argument('name', scalar('String'))]),
field('default', scalar('String'), [argument('name', scalar('String'))]),
field('choices', list(scalar('String')), [argument('name', scalar('String'))]),
+ field('autoComplete', list(scalar('String')), [argument('search', scalar('String'))]),
+ field('autoCompleteWindow', named(GREET_AUTOCOMPLETE_WINDOW_TYPE), [
+ argument('search', scalar('String')),
+ {...argument('offset', scalar('Int')), defaultValue: '0'},
+ {...argument('size', scalar('Int')), defaultValue: '2'}
+ ]),
field('validity', scalar('String'), [argument('name', scalar('String'))]),
field('datatype', scalar('String'))
])],
+ [GREET_AUTOCOMPLETE_WINDOW_TYPE, objectType(GREET_AUTOCOMPLETE_WINDOW_TYPE, [
+ field('items', list(scalar('String'))), field('offset', scalar('Int')),
+ field('requestedSize', scalar('Int')), field('returnedCount', scalar('Int')),
+ field('totalCount', scalar('Int')), field('maximumSize', scalar('Int')),
+ field('hasPrevious', scalar('Boolean')), field('hasNext', scalar('Boolean')),
+ field('ordering', scalar('String'))
+ ])],
[`${SAMPLE_SERVICE_TYPE}__greet__gqlv_action_invoke`, invokeType(
`${SAMPLE_SERVICE_TYPE}__greet__gqlv_action_invoke`, scalar('String')
)],
@@ -189,6 +204,16 @@ export function createMenuGraphQLExecutor({
datatype: 'String'
}}}}}}};
}
+ if (request.operationName === 'CausewayServiceActionParameterAutoCompleteWindow') {
+ serviceCalls.push(request);
+ return {data: {rich: {[SAMPLE_SERVICE_FIELD]: {greet: {params: {name: {
+ autoCompleteWindow: {
+ items: ['Grace'], offset: 2, requestedSize: 2, returnedCount: 1,
+ totalCount: 3, maximumSize: 2, hasPrevious: true, hasNext: false,
+ ordering: 'APPLICATION'
+ }
+ }}}}}}};
+ }
if (request.operationName === 'CausewayValidateServiceAction') {
serviceCalls.push(request);
const value = Object.values(request.variables)[0];
diff --git a/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs b/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs
index da0232819d2..dd108d56b98 100644
--- a/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs
+++ b/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs
@@ -37,6 +37,9 @@ const EMPTY_COLLECTION_TYPE = `${OBJECT_TYPE}__formerStaff__gqlv_collection`;
const ACTION_TYPE = `${OBJECT_TYPE}__changeName__gqlv_action`;
const ACTION_PARAMS_TYPE = `${OBJECT_TYPE}__changeName__gqlv_action_params`;
const ACTION_PARAM_TYPE = `${OBJECT_TYPE}__changeName__newName__gqlv_action_parameter`;
+const AUTOCOMPLETE_WINDOW_ORDERING_TYPE = 'rich__gqlv_autocomplete_window_ordering';
+const CHAIR_AUTOCOMPLETE_WINDOW_TYPE = `${CHAIR_TYPE}_autocomplete_window`;
+const ACTION_PARAM_AUTOCOMPLETE_WINDOW_TYPE = `${ACTION_PARAM_TYPE}_autocomplete_window`;
const STAFF_OBJECT_TYPE = 'rich__university_staff_StaffMember';
const STAFF_META_TYPE = `${STAFF_OBJECT_TYPE}__gqlv_meta`;
const STAFF_NAME_TYPE = `${STAFF_OBJECT_TYPE}__name__gqlv_property`;
@@ -136,6 +139,50 @@ export function createRichSchemaTypes() {
]);
}
+export function createAutoCompleteWindowRichSchemaTypes() {
+ const types = createRichSchemaTypes();
+ const windowFields = () => [
+ field('items', null, list(named(STAFF_OBJECT_TYPE))),
+ field('offset', null, nonNull(scalar('Int'))),
+ field('requestedSize', null, nonNull(scalar('Int'))),
+ field('returnedCount', null, nonNull(scalar('Int'))),
+ field('totalCount', null, nonNull(scalar('Int'))),
+ field('maximumSize', null, nonNull(scalar('Int'))),
+ field('hasPrevious', null, nonNull(scalar('Boolean'))),
+ field('hasNext', null, nonNull(scalar('Boolean'))),
+ field('ordering', null, nonNull(enumeration(AUTOCOMPLETE_WINDOW_ORDERING_TYPE)))
+ ];
+ const windowArguments = [
+ argument('search', nonNull(scalar('String'))),
+ argument('offset', nonNull(scalar('Int')), {defaultValue: '0'}),
+ argument('size', nonNull(scalar('Int')), {defaultValue: '5'})
+ ];
+ const chairType = types.get(CHAIR_TYPE);
+ types.set(CHAIR_TYPE, objectType(CHAIR_TYPE, null, [
+ ...chairType.fields,
+ field('autoComplete', null, list(named(STAFF_OBJECT_TYPE)), [argument('search', nonNull(scalar('String')))]),
+ field('autoCompleteWindow', null, named(CHAIR_AUTOCOMPLETE_WINDOW_TYPE), windowArguments)
+ ]));
+ const parameterType = types.get(ACTION_PARAM_TYPE);
+ types.set(ACTION_PARAM_TYPE, objectType(ACTION_PARAM_TYPE, null, [
+ ...parameterType.fields,
+ field('autoComplete', null, list(named(STAFF_OBJECT_TYPE)), [argument('search', nonNull(scalar('String')))]),
+ field('autoCompleteWindow', null, named(ACTION_PARAM_AUTOCOMPLETE_WINDOW_TYPE), [
+ argument('preceding', scalar('String')),
+ ...windowArguments
+ ])
+ ]));
+ types.set(CHAIR_AUTOCOMPLETE_WINDOW_TYPE, objectType(
+ CHAIR_AUTOCOMPLETE_WINDOW_TYPE, null, windowFields()));
+ types.set(ACTION_PARAM_AUTOCOMPLETE_WINDOW_TYPE, objectType(
+ ACTION_PARAM_AUTOCOMPLETE_WINDOW_TYPE, null, windowFields()));
+ types.set(AUTOCOMPLETE_WINDOW_ORDERING_TYPE, {
+ kind: 'ENUM', name: AUTOCOMPLETE_WINDOW_ORDERING_TYPE, description: null,
+ fields: [], enumValues: [{name: 'APPLICATION', description: null}], possibleTypes: []
+ });
+ return types;
+}
+
export function createVersionlessRichSchemaTypes({windowed = false} = {}) {
const types = windowed ? createWindowedRichSchemaTypes() : createRichSchemaTypes();
const metadataType = types.get(STAFF_META_TYPE);
diff --git a/viewers/webcomponents/foundation/test/graphql-client.test.mjs b/viewers/webcomponents/foundation/test/graphql-client.test.mjs
index 76ef647ad84..d6e87e17a92 100644
--- a/viewers/webcomponents/foundation/test/graphql-client.test.mjs
+++ b/viewers/webcomponents/foundation/test/graphql-client.test.mjs
@@ -23,6 +23,7 @@ import {CausewayGraphQLClient, CausewaySchemaError} from '../src/graphql-client.
import {RichSchemaNames} from '../src/schema-names.mjs';
import {
collectionWindowResponse,
+ createAutoCompleteWindowRichSchemaTypes,
createRichSchemaFixtureExecutor,
createRichSchemaTypes,
createWindowedRichSchemaTypes,
@@ -76,6 +77,25 @@ test('targeted introspection discovers object-valued action choices and their me
assert.equal(executor.introspectionCalls.every(call => Object.keys(call.variables).length === 1), true);
});
+test('autocomplete window discovery follows result item and metadata types', async () => {
+ const types = createAutoCompleteWindowRichSchemaTypes();
+ const executor = createRichSchemaFixtureExecutor({types});
+ const client = new CausewayGraphQLClient({executor});
+
+ const description = await client.describeObject(DEPARTMENT_LOGICAL_TYPE);
+
+ const propertyField = description.members.get('chair').fields.get('autoCompleteWindow');
+ const resultTypeName = propertyField.type.name;
+ assert.equal(description.types.has(resultTypeName), true);
+ const resultType = description.types.get(resultTypeName);
+ assert.equal(resultType.fields.some(field => field.name === 'items'), true);
+ assert.equal(description.types.has('rich__university_staff_StaffMember'), true);
+ assert.equal(description.types.has('rich__university_staff_StaffMember__gqlv_meta'), true);
+ const parameterType = description.types.get(
+ 'rich__university_dept_Department__changeName__newName__gqlv_action_parameter');
+ assert.equal(parameterType.fields.some(field => field.name === 'autoCompleteWindow'), true);
+});
+
test('targeted introspection discovers and executes bounded collection windows', async () => {
const rows = [{
_meta: {id: 'staff-1', logicalTypeName: 'university.staff.StaffMember', title: 'Dr Ada', version: '1'}
diff --git a/viewers/webcomponents/foundation/test/interaction-command.test.mjs b/viewers/webcomponents/foundation/test/interaction-command.test.mjs
index 8538cff5d5d..ee57671225a 100644
--- a/viewers/webcomponents/foundation/test/interaction-command.test.mjs
+++ b/viewers/webcomponents/foundation/test/interaction-command.test.mjs
@@ -155,6 +155,65 @@ test('object context executes property validation and update through semantic co
context.disconnect();
});
+test('object context prefers property autocomplete windows and normalizes metadata', async () => {
+ const description = fixtureDescription();
+ const choiceTypeName = 'rich__example_Choice';
+ const metadataTypeName = `${choiceTypeName}__gqlv_meta`;
+ const windowTypeName = `${description.generatedTypeName}__name__gqlv_property_autocomplete_window`;
+ const originalProperty = description.members.get('name');
+ const windowField = field('autoCompleteWindow', named(windowTypeName), [
+ {...argument('search', scalar('String')), defaultValue: null},
+ {...argument('offset', scalar('Int')), defaultValue: '0'},
+ {...argument('size', scalar('Int')), defaultValue: '5'}
+ ]);
+ const windowedDescription = {
+ ...description,
+ members: new Map(description.members).set('name', {
+ ...originalProperty,
+ fields: new Map(originalProperty.fields)
+ .set('autoComplete', field('autoComplete', list(named(choiceTypeName)), [argument('search', scalar('String'))]))
+ .set('autoCompleteWindow', windowField)
+ }),
+ types: new Map([
+ ...description.types,
+ [windowTypeName, graphType(windowTypeName, [
+ field('items', list(named(choiceTypeName))), field('offset', scalar('Int')),
+ field('requestedSize', scalar('Int')), field('returnedCount', scalar('Int')),
+ field('totalCount', scalar('Int')), field('maximumSize', scalar('Int')),
+ field('hasPrevious', scalar('Boolean')), field('hasNext', scalar('Boolean')),
+ field('ordering', scalar('String'))
+ ])],
+ [choiceTypeName, graphType(choiceTypeName, [field('_meta', named(metadataTypeName))])],
+ [metadataTypeName, graphType(metadataTypeName, [
+ field('id', scalar('ID')), field('logicalTypeName', scalar('String')), field('title', scalar('String'))
+ ])]
+ ])
+ };
+ const choice = {_meta: {id: 'choice-6', logicalTypeName: 'example.Choice', title: 'Choice 6'}};
+ let request;
+ const client = {
+ describeObject: async () => windowedDescription,
+ executeObjectInteraction: async candidate => {
+ request = candidate;
+ return {data: {name: {autoCompleteWindow: {
+ items: [choice], offset: 5, requestedSize: 5, returnedCount: 1, totalCount: 6,
+ maximumSize: 5, hasPrevious: true, hasNext: false, ordering: 'APPLICATION'
+ }}}, errors: [], operation: {operationName: candidate.operationName}};
+ }
+ };
+ const context = new ObjectContextController({client, logicalTypeName: 'example.Object', objectId: '42'});
+
+ const result = await context.autoCompletePropertyWindow('name', 'Choice', {offset: 5, size: 5});
+
+ assert.equal(result.status, 'success');
+ assert.equal(result.data.windowed, true);
+ assert.deepEqual(result.data.items, [choice]);
+ assert.equal(result.data.totalCount, 6);
+ assert.match(JSON.stringify(request.selection), /autoCompleteWindow/);
+ assert.deepEqual(request.selection.name.autoCompleteWindow.__args, {search: 'Choice', offset: 5, size: 5});
+ context.disconnect();
+});
+
test('query-only and non-compliant variants report or execute discovered capabilities', async () => {
const description = fixtureDescription();
const queryOnlyClient = {
@@ -222,6 +281,56 @@ test('versionless preparation and autocomplete select only advertised identity m
context.disconnect();
});
+test('action parameter autocomplete windows preserve declared dependent arguments', async () => {
+ const description = versionlessPreparationDescription();
+ const parameterTypeName = `${description.generatedTypeName}__choose__choice__gqlv_action_parameter`;
+ const windowTypeName = `${parameterTypeName}_autocomplete_window`;
+ const parameterType = description.types.get(parameterTypeName);
+ const windowField = field('autoCompleteWindow', named(windowTypeName), [
+ argument('preceding', scalar('String')), argument('search', scalar('String')),
+ {...argument('offset', scalar('Int')), defaultValue: '0'},
+ {...argument('size', scalar('Int')), defaultValue: '5'}
+ ]);
+ description.types.set(parameterTypeName, graphType(parameterTypeName, [
+ ...parameterType.fields, windowField
+ ]));
+ const action = description.members.get('choose');
+ const paramsTypeName = `${description.generatedTypeName}__choose__gqlv_action_params`;
+ description.types.set(paramsTypeName, graphType(paramsTypeName, [field('choice', named(parameterTypeName))]));
+ description.types.set(windowTypeName, graphType(windowTypeName, [
+ field('items', list(named('rich__example_VersionlessChoice'))),
+ field('offset', scalar('Int')), field('requestedSize', scalar('Int')),
+ field('returnedCount', scalar('Int')), field('totalCount', scalar('Int')),
+ field('maximumSize', scalar('Int')), field('hasPrevious', scalar('Boolean')),
+ field('hasNext', scalar('Boolean')), field('ordering', scalar('String'))
+ ]));
+ description.members.set('choose', {...action});
+ const choice = {_meta: {id: 'choice-6', logicalTypeName: 'example.VersionlessChoice', title: 'Choice six'}};
+ let request;
+ const client = {
+ describeObject: async () => description,
+ describeMutation: async () => null,
+ executeObjectInteraction: async candidate => {
+ request = candidate;
+ return {data: {choose: {params: {choice: {autoCompleteWindow: {
+ items: [choice], offset: 5, requestedSize: 5, returnedCount: 1, totalCount: 6,
+ maximumSize: 5, hasPrevious: true, hasNext: false, ordering: 'APPLICATION'
+ }}}}}, errors: [], operation: {}};
+ }
+ };
+ const context = new ObjectContextController({client, logicalTypeName: 'example.Object', objectId: '42'});
+
+ const result = await context.autoCompleteActionParameterWindow(
+ 'choose', 'choice', 'Cho', {preceding: 'current', ignored: 'omit'}, {offset: 5, size: 5});
+
+ assert.equal(result.status, 'success');
+ assert.equal(result.data.items[0]._meta.id, 'choice-6');
+ assert.deepEqual(request.selection.choose.params.choice.autoCompleteWindow.__args, {
+ preceding: 'current', search: 'Cho', offset: 5, size: 5
+ });
+ context.disconnect();
+});
+
test('broad abstract mutation outcomes execute once and remain typename-only', async () => {
const description = fixtureDescription();
const unionTypeName = 'rich__example_BroadResultUnion';
diff --git a/viewers/webcomponents/foundation/test/interaction.test.mjs b/viewers/webcomponents/foundation/test/interaction.test.mjs
index 6a9532eef41..7599c35d042 100644
--- a/viewers/webcomponents/foundation/test/interaction.test.mjs
+++ b/viewers/webcomponents/foundation/test/interaction.test.mjs
@@ -26,12 +26,15 @@ const {
CausewayEditorRegistry,
CausewayInteractionControllerElement,
CausewayPropertyElement,
+ CausewayReferenceEditorElement,
InteractionStatus,
+ autoCompleteWindowPlan,
buildMutationInteractionOperation,
buildObjectInteractionOperation,
commandSelection,
configureCausewayReferenceWidgets,
defaultEditorRegistry,
+ normalizeAutoCompleteWindow,
parseCausewayEditorValue,
renderCausewayEditor
} = await import('../src/index.mjs');
@@ -126,6 +129,37 @@ test('interaction operations render and validate inline fragments', () => {
}), /not advertised/);
});
+test('autocomplete windows derive advertised selections and normalize paging metadata', () => {
+ const itemType = type('Choice', [field('_meta', named('ChoiceMeta'))]);
+ const metadataType = type('ChoiceMeta', [field('id', scalar('ID')), field('logicalTypeName', scalar('String'))]);
+ const windowType = type('ChoiceWindow', [
+ field('items', list(named('Choice'))), field('offset', scalar('Int')),
+ field('requestedSize', scalar('Int')), field('returnedCount', scalar('Int')),
+ field('totalCount', scalar('Int')), field('maximumSize', scalar('Int')),
+ field('hasPrevious', scalar('Boolean')), field('hasNext', scalar('Boolean')),
+ field('ordering', scalar('String'))
+ ]);
+ const windowField = field('autoCompleteWindow', named('ChoiceWindow'), [
+ {...argument('offset', scalar('Int')), defaultValue: '0'},
+ {...argument('size', scalar('Int')), defaultValue: '5'}
+ ]);
+ const plan = autoCompleteWindowPlan(windowField, new Map([
+ ['ChoiceWindow', windowType], ['Choice', itemType], ['ChoiceMeta', metadataType]
+ ]));
+
+ assert.equal(plan.offsetDefault, 0);
+ assert.equal(plan.sizeDefault, 5);
+ assert.deepEqual(plan.selection.items, {_meta: {id: true, logicalTypeName: true}});
+ const normalized = normalizeAutoCompleteWindow({
+ items: [{_meta: {id: '6', logicalTypeName: 'example.Choice'}}], offset: 5,
+ requestedSize: 5, returnedCount: 1, totalCount: 6, maximumSize: 5,
+ hasPrevious: true, hasNext: false, ordering: 'APPLICATION'
+ });
+ assert.equal(normalized.windowed, true);
+ assert.equal(normalized.totalCount, 6);
+ assert.equal(normalized.items.length, 1);
+});
+
test('editor registry selects standard inputs and supports application overrides', () => {
const text = renderCausewayEditor({
name: 'name', value: 'Classics', choices: [], enumValues: [], inputType: scalar('String'),
@@ -366,6 +400,100 @@ test('editable properties support prepare, validation, cancel and authoritative
assert.equal(calls.includes('update:Cancelled'), false);
});
+test('windowed Vaadin reference adapter requests authoritative later pages', async () => {
+ const moduleSource = `
+ if (!globalThis.customElements.get('vaadin-combo-box')) globalThis.customElements.define('vaadin-combo-box', class extends HTMLElement {});
+ if (!globalThis.customElements.get('vaadin-multi-select-combo-box')) globalThis.customElements.define('vaadin-multi-select-combo-box', class extends HTMLElement {});
+ `;
+ globalThis.customElements.whenDefined ??= async () => {};
+ configureCausewayReferenceWidgets({
+ enabled: true,
+ minimumSearchLength: 1,
+ maximumResults: 50,
+ moduleUrl: `data:text/javascript,${encodeURIComponent(moduleSource)}`
+ });
+ const editor = new CausewayReferenceEditorElement();
+ editor.dataset ??= {};
+ editor.childNodes ??= [];
+ editor.replaceChildren = (...children) => {
+ editor.childNodes = children;
+ for (const child of children) child.parentNode = editor;
+ };
+ editor.id = 'owner-editor';
+ editor.setAttribute('data-causeway-editor', 'owner');
+ editor.setAttribute('data-label', 'Owner');
+ editor.setAttribute('data-items', '[]');
+ editor.setAttribute('data-value', 'null');
+ editor.setAttribute('data-autocomplete', 'true');
+ editor.setAttribute('data-autocomplete-window', 'true');
+ editor.setAttribute('data-autocomplete-page-size', '2');
+ Object.assign(editor.dataset, {
+ autocomplete: 'true',
+ autocompleteWindow: 'true',
+ autocompletePageSize: '2',
+ items: '[]',
+ value: 'null',
+ label: 'Owner'
+ });
+ let requested;
+ const pendingRequests = new Map();
+ editor.addEventListener('causeway-reference-search', event => {
+ requested = event.detail;
+ pendingRequests.set(event.detail.search, event.detail);
+ if (event.detail.search === 'Ow') {
+ event.detail.respond({
+ status: 'success',
+ data: {
+ items: [{_meta: {id: 'owner-3', logicalTypeName: 'example.Owner', title: 'Owner 3'}}],
+ offset: 2,
+ requestedSize: 2,
+ returnedCount: 1,
+ totalCount: 3,
+ maximumSize: 2,
+ hasPrevious: true,
+ hasNext: false,
+ ordering: 'APPLICATION',
+ windowed: true
+ }
+ });
+ }
+ });
+ document.body.appendChild(editor);
+ for (let index = 0; index < 20 && editor.dataset.widgetState !== 'ready'; index += 1) {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ }
+ assert.equal(editor.dataset.widgetState, 'ready', editor.dataset.widgetError);
+ const control = editor.childNodes[0];
+ assert.equal(control.pageSize, 2);
+ let callbackResult;
+
+ control.dataProvider({filter: 'Ow', page: 1, pageSize: 2}, (items, total) => {
+ callbackResult = {items, total};
+ });
+ await new Promise(resolve => setTimeout(resolve, 0));
+
+ assert.equal(requested.offset, 2);
+ assert.equal(requested.size, 2);
+ assert.deepEqual(callbackResult, {
+ items: [{id: 'owner-3', logicalTypeName: 'example.Owner', title: 'Owner 3'}],
+ total: 3
+ });
+
+ let staleCallback;
+ let currentCallback;
+ control.dataProvider({filter: 'Old', page: 0, pageSize: 2}, (items, total) => staleCallback = {items, total});
+ control.dataProvider({filter: 'New', page: 0, pageSize: 2}, (items, total) => currentCallback = {items, total});
+ pendingRequests.get('Old').respond({status: 'success', data: {
+ items: [{_meta: {id: 'old', title: 'Old'}}], totalCount: 1, windowed: true
+ }});
+ pendingRequests.get('New').respond({status: 'success', data: {
+ items: [{_meta: {id: 'new', title: 'New'}}], totalCount: 1, windowed: true
+ }});
+ assert.equal(staleCallback, undefined);
+ assert.deepEqual(currentCallback, {items: [{id: 'new', title: 'New'}], total: 1});
+ document.body.removeChild(editor);
+});
+
test('reference autocomplete cancels stale work and rejects over-bound results', async () => {
configureCausewayReferenceWidgets({enabled: true, minimumSearchLength: 2, maximumResults: 2});
let stateListener;
diff --git a/viewers/webcomponents/htmx/README.adoc b/viewers/webcomponents/htmx/README.adoc
index 28b51698046..a626efafc01 100644
--- a/viewers/webcomponents/htmx/README.adoc
+++ b/viewers/webcomponents/htmx/README.adoc
@@ -26,7 +26,8 @@ The shell uses external same-origin scripts and styles and requires no inline sc
`causeway.viewer.webcomponents.htmx.wicket-comparison-path` optionally adds a footer link and is intended only for comparison samples.
`causeway.viewer.webcomponents.htmx.vaadin-reference-widgets` defaults to `false` and explicitly enables the internal free-core reference-widget pilot.
`causeway.viewer.webcomponents.htmx.reference-minimum-search-length` defaults to `2`.
-`causeway.viewer.webcomponents.htmx.reference-maximum-results` defaults to `50` and bounds one complete search-only GraphQL autocomplete response; it is not a server page size.
+`causeway.viewer.webcomponents.htmx.reference-maximum-results` defaults to `50` and is the requested page-size fallback for advertised GraphQL autocomplete windows as well as the accepted complete-response bound for legacy non-windowed autocomplete.
+An advertised field's smaller introspected default window size takes precedence.
The complete shell applies a restrictive same-origin content-security policy and returns `private, no-store`.
The default policy and asset requests remain unchanged while the pilot is disabled.
diff --git a/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java b/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java
index f2f08454684..f90b2f178ff 100644
--- a/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java
+++ b/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java
@@ -361,8 +361,14 @@ void disposableOwnerExercisesCreateAndEveryObjectAction() {
throw new AssertionError(String.valueOf(
page.locator(PROMPT).evaluate("element => element.outerHTML")), cause);
}
- page.waitForFunction("selector => document.querySelector(selector)?.dataset.widgetState === 'ready'", parameter("pet"));
- assertThat(petReference.evaluate("element => element.value?.id")).isNotNull();
+ if (Boolean.TRUE.equals(petReference.evaluate("element => element.localName === 'select'"))) {
+ petReference.evaluate("element => { element.selectedIndex = 0; "
+ + "element.dispatchEvent(new Event('change', {bubbles: true, composed: true})); }");
+ assertThat(petReference.inputValue()).isNotBlank();
+ } else {
+ page.waitForFunction("selector => document.querySelector(selector)?.dataset.widgetState === 'ready'", parameter("pet"));
+ assertThat(petReference.evaluate("element => element.value?.id")).isNotNull();
+ }
assertThat(page.locator(parameter("visitAt")).count())
.as(page.locator(PROMPT).evaluate("element => element.outerHTML").toString())
.isEqualTo(1);
(causeway) 04/15: plans versionless web component identity correction
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit 1df0857c476f27049b9ea5054dc2506bd3b04eed
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 11:00:33 2026 +0100
plans versionless web component identity correction
---
.../.openspec.yaml | 2 +
.../design.md | 79 ++++++++++++++++++++++
.../proposal.md | 29 ++++++++
.../specs/domain-web-components/spec.md | 35 ++++++++++
.../spec.md | 25 +++++++
.../tasks.md | 62 +++++++++++++++++
6 files changed, 232 insertions(+)
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/.openspec.yaml b/openspec/changes/fix-webcomponent-versionless-identity-preparation/.openspec.yaml
new file mode 100644
index 00000000000..4102db8a47b
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-08-24
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/design.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/design.md
new file mode 100644
index 00000000000..77380529242
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/design.md
@@ -0,0 +1,79 @@
+## Context
+
+The foundation already derives object-header metadata fields from the advertised rich metadata wrapper, and the action-dispatch correction made action result and parameter-state selections type-aware.
+Two older projection paths remain unconditional: object-valued property reads and collection-row reads always request `_meta { id logicalTypeName title version }`.
+The pinned Reference Application proves that view models including `DependentArgsDemoItem`, `ActionSemanticsVm`, and `CollectionLayoutPagedChildVm` legitimately omit `version` while retaining `id`, `logicalTypeName`, and `title`.
+Those reads currently fail GraphQL validation before existing identity, editor, cancellation, and row-hydration policies can run.
+
+Identity and optimistic concurrency are distinct concerns.
+A versionless object can still have a stable logical type and identifier suitable for values, choices, hydration, and navigation, while a mutation that requires an advertised concurrency token must not invent one.
+The GraphQL schema remains authoritative, strict CSP and route-lazy delivery remain unchanged, and this change must not absorb union or opaque-route corrections.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- Request only metadata fields advertised by the effective concrete object metadata type.
+- Preserve `version` for versioned entities and omit it for versionless view models.
+- Reuse one metadata-selection policy across property references, direct action/preparation values, and collection rows.
+- Require `id` and `logicalTypeName` before claiming navigable or hydratable semantic identity.
+- Prove preparation, choices, autocomplete, object values, and collection rows against versionless Reference Application targets.
+- Preserve cancellation, stale-response, refresh, error, redaction, and native/Vaadin boundaries.
+
+**Non-Goals:**
+
+- Adding a nullable version or concurrency field to rich GraphQL.
+- Defining optimistic-concurrency behavior for a mutation that explicitly requires an unavailable token.
+- Selecting metadata from interfaces or unions through fragments.
+- Changing opaque bookmark route encoding, decoding, or length limits.
+- Changing action placement, reference paging, Vaadin adapters, dependencies, or public browser contracts.
+
+## Decisions
+
+### Centralize concrete metadata selection
+
+A shared selection helper will inspect the effective object type, locate its `_meta` field, inspect the referenced metadata type, and select the advertised subset of `id`, `logicalTypeName`, `title`, and `version`.
+Callers will use this helper instead of constructing metadata selections independently.
+
+This extends the introspection-driven result-selection approach introduced by action dispatch and avoids maintaining a second list of versionless types.
+The rejected alternative is to remove `version` globally, because that would discard an advertised concurrency value from ordinary entities and weaken existing refresh behavior.
+
+### Keep semantic identity minimums explicit
+
+A value is navigable or suitable for hydrated row context only when the effective metadata advertises both `id` and `logicalTypeName` and the response supplies both values.
+`title` remains optional with the established identifier fallback, and `version` remains optional.
+If the minimum fields are absent, the projection returns bounded non-navigable data or an existing local unsupported/error state rather than manufacturing identity.
+
+The rejected alternative is to infer logical type from the enclosing member or generated GraphQL name, because polymorphism and aliases make that speculative.
+
+### Merge row identity with authored columns
+
+Collection row selection will start with the concrete row type's advertised metadata selection and then merge declared semantic column selections.
+Versionless rows therefore retain identity and row hydration, while rows without concrete metadata remain bounded and await the separate union-projection change.
+Windowing, offsets, ordering, partial errors, and lazy activation remain unchanged.
+
+### Treat preparation as a regression boundary
+
+Action and property preparation paths already route nested result selection through described types after the action-dispatch change.
+This change will add focused fixtures and Reference Application assertions to prove that versionless defaults, choices, autocomplete results, and valid pending values remain usable without reintroducing unconditional metadata.
+Production changes will be limited to any remaining unconditional paths revealed by those tests.
+
+### Preserve schema and host boundaries
+
+No public GraphQL operation or metadata field changes.
+No route, event, custom-element, HTMX, Vaadin, CSP, or asset policy changes.
+Capability inventory classifications change only when executable evidence changes, and unrelated union and opaque-route gaps remain visible.
+
+## Risks / Trade-offs
+
+- [A helper receives an incomplete type graph] → Return a bounded `__typename` or unsupported projection and add focused missing-description tests rather than speculating about metadata.
+- [Versionless identity is mistaken for mutation concurrency] → Keep identity extraction separate from target-input construction and never manufacture `version`.
+- [Collection column merging creates invalid nested selections] → Derive the base row selection from the concrete element type and retain existing member-wrapper column grammar.
+- [Fixing concrete rows masks union failures] → Keep union targets classified and asserted as known gaps until fragment projection is implemented separately.
+- [A stale Reference Application target changes upstream] → Pin tests to the copied corpus and validate the semantic target catalogue against introspection.
+
+## Migration Plan
+
+The change is a client-side projection correction with no persisted-data or schema migration.
+Deploy through the existing same-origin foundation artifact and verify both versioned and versionless paths.
+Rollback is a source revert with no application configuration or route migration.
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/proposal.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/proposal.md
new file mode 100644
index 00000000000..8f83a70a2bd
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/proposal.md
@@ -0,0 +1,29 @@
+## Why
+
+The pinned Reference Application exposes view models and collection rows whose rich metadata advertises stable identity and title but no `version` field.
+The generic web-component viewer still hard-codes `_meta.version` in property-reference and collection-row projections, causing otherwise valid preparation, choice, autocomplete, editing, and collection operations to fail visibly.
+
+## What Changes
+
+- Derive identity metadata selections from each effective advertised metadata type rather than assuming `id`, `logicalTypeName`, `title`, and `version` are all present.
+- Preserve version when advertised while allowing versionless identities to participate in property values, action-parameter preparation, choices, autocomplete, collection rows, and authoritative refresh.
+- Define bounded behavior when metadata lacks fields required for semantic identity instead of inventing a version or bookmark.
+- Add focused foundation fixtures and pinned Reference Application browser and integration coverage for versioned and versionless values and rows.
+- Reclassify only capability-inventory entries whose executable evidence changes.
+- Keep union-fragment projection, opaque route encoding, action placement, GraphQL schema changes, paging, and Vaadin policy outside this change.
+
+## Capabilities
+
+### New Capabilities
+
+None.
+
+### Modified Capabilities
+
+- `domain-web-components`: Require metadata-aware property, preparation, choice, autocomplete, collection-row, and refresh projections that request only advertised identity fields.
+- `reference-application-viewer-regression-suite`: Require executable versionless view-model and row journeys and preserve unrelated union and opaque-route gaps.
+
+## Impact
+
+The change affects internal selection construction in the framework-neutral web-component foundation, its targeted-introspection descriptions and fixtures, and the pinned Reference Application regression corpus.
+Public Causeway elements, semantic events, GraphQL operations and generated names, canonical routes, HTMX lifecycle, Vaadin qualification policy, dependencies, and production asset inputs remain unchanged.
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/specs/domain-web-components/spec.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/specs/domain-web-components/spec.md
new file mode 100644
index 00000000000..9b1d3db28df
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/specs/domain-web-components/spec.md
@@ -0,0 +1,35 @@
+## ADDED Requirements
+
+### Requirement: Advertised semantic identity projection
+The component library SHALL derive metadata selection for concrete object values and rows from the effective metadata type advertised by targeted introspection.
+It MUST preserve advertised identity and presentation fields, MUST treat `version` as optional, and MUST NOT request, synthesize, or infer absent metadata fields.
+
+#### Scenario: Versioned object value is read
+- **WHEN** a concrete property, choice, autocomplete result, preparation value, action result, or collection row advertises `id`, `logicalTypeName`, `title`, and `version`
+- **THEN** the operation selects those advertised fields
+- **AND** the semantic value preserves the returned version
+
+#### Scenario: Versionless object value is read
+- **WHEN** a concrete property, choice, autocomplete result, preparation value, action result, or collection row advertises `id`, `logicalTypeName`, and `title` but not `version`
+- **THEN** the operation omits `version`
+- **AND** the value remains available for supported rendering, pending-value conversion, validation, hydration, refresh, and navigation
+
+#### Scenario: Metadata lacks semantic identity minimums
+- **WHEN** an effective metadata type does not advertise both `id` and `logicalTypeName`
+- **THEN** the component does not claim a navigable bookmark or hydratable object identity
+- **AND** it exposes only a valid bounded projection or the existing local unsupported state
+
+#### Scenario: Versionless value participates in preparation
+- **WHEN** a property or action parameter preparation field returns a concrete versionless object through default, choices, autocomplete, validity, or datatype semantics
+- **THEN** the context selects only metadata fields advertised for that object
+- **AND** cancellation and stale-response protection remain unchanged
+
+#### Scenario: Versionless collection rows are loaded
+- **WHEN** a concrete collection element type advertises semantic identity without `version`
+- **THEN** row selection merges the advertised identity fields with requested semantic columns
+- **AND** the rows remain hydratable without manufacturing a concurrency token
+
+#### Scenario: Abstract row type requires fragments
+- **WHEN** an interface or union row cannot expose semantic metadata without concrete fragments
+- **THEN** the component retains a bounded non-navigable or partial-error result
+- **AND** does not treat versionless concrete-object support as general union-projection support
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/specs/reference-application-viewer-regression-suite/spec.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/specs/reference-application-viewer-regression-suite/spec.md
new file mode 100644
index 00000000000..c3a7eee3953
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/specs/reference-application-viewer-regression-suite/spec.md
@@ -0,0 +1,25 @@
+## ADDED Requirements
+
+### Requirement: Versionless identity regression coverage
+The pinned Reference Application suite SHALL exercise representative concrete view models and collection rows whose rich metadata omits `version` while preserving stable semantic identity.
+It MUST distinguish corrected versionless projection behavior from retained polymorphic-union and opaque-route gaps.
+
+#### Scenario: Versionless preparation target is exercised
+- **WHEN** the browser prepares representative action or property interaction semantics that return concrete versionless values
+- **THEN** defaults, choices, autocomplete, validation, and successful submission remain usable without a missing-version GraphQL error
+- **AND** invalid, cancelled, and stale interactions retain their established behavior
+
+#### Scenario: Versionless property or action result is rendered
+- **WHEN** a representative concrete view model is returned as a property value or typed action outcome
+- **THEN** its advertised identity and title remain renderable and navigable through existing semantic contracts
+- **AND** no `_meta.version` selection is submitted for its versionless metadata type
+
+#### Scenario: Versionless collection row is rendered
+- **WHEN** a representative concrete view-model collection is activated
+- **THEN** its row window reaches the supported ready or documented partial state with stable identities and requested columns
+- **AND** a missing version field is not the cause of any row error
+
+#### Scenario: Unrelated retained gaps remain classified
+- **WHEN** the same qualification run reaches a polymorphic union target or a long opaque composite bookmark
+- **THEN** the suite retains the corresponding bounded known-gap assertion until its focused change is implemented
+- **AND** does not count it as evidence that concrete versionless identity failed
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/tasks.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/tasks.md
new file mode 100644
index 00000000000..80ff5b2f3db
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/tasks.md
@@ -0,0 +1,62 @@
+## 1. Confirm executable versionless shapes
+
+- [ ] 1.1 Capture targeted introspection for representative versioned entity and versionless view-model metadata types.
+- [ ] 1.2 Identify concrete Reference Application property, preparation, choice or autocomplete, action-result, and collection-row targets that omit `version`.
+- [ ] 1.3 Record retained interface or union and opaque-route targets that remain outside this correction.
+
+## 2. Centralize metadata selection
+
+- [ ] 2.1 Add a shared helper that derives the advertised metadata subset for a concrete object type.
+- [ ] 2.2 Preserve `id`, `logicalTypeName`, `title`, and `version` only when each field is advertised.
+- [ ] 2.3 Return a bounded projection when an object type or metadata description is unavailable.
+- [ ] 2.4 Keep semantic identity minimum validation separate from optional version handling.
+- [ ] 2.5 Reuse the helper from direct interaction result selection without changing scalar, enum, resource, or union behavior.
+
+## 3. Correct property and preparation projections
+
+- [ ] 3.1 Replace unconditional object-valued property metadata selection with the shared advertised selection.
+- [ ] 3.2 Verify versioned property references continue to retain returned versions.
+- [ ] 3.3 Verify versionless property references remain renderable and convertible to pending identity values.
+- [ ] 3.4 Verify action and property defaults, choices, autocomplete, validity, and datatype preparation omit absent metadata fields.
+- [ ] 3.5 Preserve preparation cancellation, stale-response, validation, and protected-value behavior.
+
+## 4. Correct collection-row projections
+
+- [ ] 4.1 Derive the base row selection from the concrete collection element type.
+- [ ] 4.2 Merge advertised row metadata with declared semantic columns without duplicate or speculative fields.
+- [ ] 4.3 Preserve versioned row hydration, windows, ordering, offsets, lazy activation, and partial errors.
+- [ ] 4.4 Support versionless concrete row hydration when `id` and `logicalTypeName` are advertised and returned.
+- [ ] 4.5 Retain bounded non-navigable or partial behavior for abstract rows that require the later union-projection change.
+
+## 5. Add focused foundation coverage
+
+- [ ] 5.1 Add versioned and versionless metadata-selection fixtures and unit tests.
+- [ ] 5.2 Add object-valued property tests proving absent `version` is not selected.
+- [ ] 5.3 Add preparation, choices, and autocomplete tests for concrete versionless values.
+- [ ] 5.4 Add versioned and versionless collection-row selection and hydration tests.
+- [ ] 5.5 Add missing metadata-description and missing identity-minimum tests.
+- [ ] 5.6 Add regression assertions that unions remain bounded and no version or bookmark is invented.
+
+## 6. Qualify against the pinned Reference Application
+
+- [ ] 6.1 Add or refine deterministic target-catalogue entries for versionless preparation and row journeys.
+- [ ] 6.2 Convert missing-version browser assertions to successful typed interactions only where executable evidence supports the correction.
+- [ ] 6.3 Preserve invalid, cancelled, stale, responsive, accessibility, CSP, console, external-request, and route-disposal assertions.
+- [ ] 6.4 Preserve explicit union-projection and opaque-route known gaps.
+- [ ] 6.5 Update capability inventory classifications only where executable evidence changes.
+- [ ] 6.6 Verify clean and incremental inventory generation remain byte-identical.
+
+## 7. Document compatibility and isolation
+
+- [ ] 7.1 Document the identity-versus-version contract and concrete metadata selection algorithm.
+- [ ] 7.2 Record representative introspection and operation evidence with reproducible commands.
+- [ ] 7.3 Verify no public GraphQL, Causeway element, event, route, HTMX, Vaadin, dependency, CSP, or asset-policy contract changes.
+
+## 8. Run final qualification gates
+
+- [ ] 8.1 Run the complete foundation Node suite and web-component foundation and HTMX Maven tests.
+- [ ] 8.2 Run relevant GraphQL model and integration tests.
+- [ ] 8.3 Run the full Petclinic integration and Playwright suites.
+- [ ] 8.4 Run the Reference Application clean package, integration, capability inventory, and Playwright suites.
+- [ ] 8.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
+- [ ] 8.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
(causeway) 10/15: plans opaque bookmark route correction
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit 3b64c1793abd7a5931611c98d84e36549cf0f785
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 13:59:33 2026 +0100
plans opaque bookmark route correction
---
.../.openspec.yaml | 2 +
.../design.md | 79 ++++++++++++++++++++++
.../proposal.md | 29 ++++++++
.../generic-htmx-web-component-viewer/spec.md | 30 ++++++++
.../spec.md | 25 +++++++
.../tasks.md | 66 ++++++++++++++++++
.../planned-changes/web-component-viewer/README.md | 2 +-
.../web-component-viewer/vaadin-default-roadmap.md | 4 +-
8 files changed, 234 insertions(+), 3 deletions(-)
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/.openspec.yaml b/openspec/changes/fix-webcomponent-opaque-route-correctness/.openspec.yaml
new file mode 100644
index 00000000000..4102db8a47b
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-08-24
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/design.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/design.md
new file mode 100644
index 00000000000..20de53ab37d
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/design.md
@@ -0,0 +1,79 @@
+## Context
+
+The canonical route grammar stores the public logical type and authoritative object identifier as independent UTF-8 percent-encoded path segments.
+Both Java and browser codecs currently reject decoded text longer than 1,024 UTF-16 characters before checking the existing 4,096-character encoded-segment envelope.
+That decoded-character limit is not aligned with HTTP representation cost, differs subtly between Java and JavaScript Unicode models, and rejects the valid memento bookmark returned for `demo.CompositeValuesPage`.
+The server consequently returns the safe `invalid-route` fragment before GraphQL can reconstruct the view model.
+
+The correction crosses browser route generation, server parsing, direct loads, HTMX history, and Reference Application qualification.
+It must retain strict canonicalization and denial-of-service bounds without interpreting an opaque Causeway bookmark.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- Round-trip valid authoritative opaque identifiers whenever each canonical encoded segment is at most 4,096 ASCII characters.
+- Use equivalent browser and server validation for Unicode, separators, controls, dot segments, canonical percent encoding, and encoded length.
+- Preserve exact identity through direct loads, semantic navigation, action results, HTMX replacement, history restoration, back, and forward.
+- Convert the pinned composite-values route into a ready supported regression.
+- Retain bounded non-disclosing invalid-route behavior for malformed and overlong input.
+
+**Non-Goals:**
+
+- Do not interpret, decompress, normalize, truncate, hash, alias, persist, or otherwise transform opaque bookmarks.
+- Do not add query-string, fragment, POST, cookie, session, or server-side route-token alternatives.
+- Do not change the route grammar, public semantic navigation event, GraphQL identity, metamodel bookmark format, or application configuration.
+- Do not alter unrelated union mismatches, value rendering, Vaadin policy, assets, dependencies, CSP, or native fallback.
+
+## Decisions
+
+### Bound canonical encoded representation rather than decoded UTF-16 length
+
+Each independently encoded segment remains limited to 4,096 ASCII characters, and the complete server path retains its existing bound derived from two segments plus fixed route syntax.
+Before encoding caller-provided text, each codec first rejects values whose UTF-8 byte representation already exceeds the encoded bound, then rejects a final percent-encoded representation over 4,096 characters.
+Server parsing rejects incoming encoded segments over the same bound before allocation and requires decode-then-reencode equality.
+
+This policy measures the actual route representation, accepts long ASCII-oriented mementos, and keeps allocation bounded.
+Increasing the decoded character limit alone was rejected because Java UTF-16 length, JavaScript string length, UTF-8 bytes, and percent-encoded size are different units.
+Removing all limits was rejected because opaque identity does not justify unbounded request or browser-history state.
+
+### Retain strict segment canonicalization
+
+The codecs continue to reject empty values, `.` and `..`, literal or encoded slash and backslash, ISO controls, malformed UTF-8, malformed percent escapes, lowercase or unnecessary percent escapes, non-ASCII literals, and unpaired UTF-16 surrogates supplied to route generation.
+The browser codec explicitly validates Unicode before `encodeURIComponent` and reports the same bounded route error instead of leaking a native `URIError`.
+No Unicode normalization is applied because it would alter identity.
+
+Allowing alternate spellings and normalizing them was rejected because one semantic identity must have one history and cache key.
+Allowing encoded separators was rejected because containers and proxies may decode paths at different stages.
+
+### Keep identity transport end to end
+
+All producers continue to call `canonicalObjectPath`, and the server continues to parse into `HtmxObjectRoute` before rendering one object context.
+The correction therefore applies uniformly to object links, collection links, home objects, action results, direct URLs, and history navigation without special-casing composite values.
+Tests compare the reconstructed context's exact `object-id` with the GraphQL-returned identifier and exercise route replacement and history restoration.
+
+A server-side short-token registry was rejected because it would make bookmarks session-dependent, introduce state and authorization complexity, and break direct loads.
+A query parameter was rejected because it changes the established public grammar and does not remove practical request-size limits.
+
+### Preserve bounded failure and response behavior
+
+Malformed or excessive routes still produce the existing non-disclosing `invalid-route` state and canonical root history instruction.
+No rejected route content enters HTML, headers, errors, events, logs, or diagnostics.
+Valid long identifiers are emitted only as safely escaped HTML attributes by the existing renderer and as encoded URLs by the route policy.
+
+## Risks / Trade-offs
+
+- [Longer accepted URLs may encounter external proxy limits below the viewer bound] → Keep the documented 4,096-character per-segment ceiling, qualify the embedded server, and document that deployments must permit supported canonical routes.
+- [Browser and Java codecs could drift] → Maintain a shared vector matrix covering ASCII, multibyte Unicode, reserved punctuation, malformed Unicode, the maximum boundary, and one-character overflow.
+- [Long attribute values could increase page size] → Permit at most the same bounded identity already present in the GraphQL response and render one route context only.
+- [A container could decode separators before the application] → Continue rejecting both literal and encoded separators and test the raw request URI contract.
+
+## Migration Plan
+
+No data or configuration migration is required.
+Deploy the corrected codecs together so browser-generated routes and server parsing use the same bound.
+Rollback restores the former conservative rejection and causes long memento bookmarks to return `invalid-route`; it does not corrupt persisted data or identity.
+
+## Open Questions
+
+None.
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/proposal.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/proposal.md
new file mode 100644
index 00000000000..663a459cdaa
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/proposal.md
@@ -0,0 +1,29 @@
+## Why
+
+The HTMX route codec rejects valid Causeway view-model bookmarks longer than 1,024 decoded characters even when their canonical UTF-8 percent-encoded path remains within the existing bounded route envelope.
+The pinned Reference Application exposes this defect through `demo.CompositeValuesPage`, whose authoritative opaque identifier currently ends in `invalid-route` instead of reconstructing the object context.
+
+## What Changes
+
+- Define one byte-oriented canonical segment policy shared by browser route construction and server route parsing.
+- Accept authoritative opaque identifiers up to the documented encoded-route bound without decoding, shortening, interpreting, hashing, aliasing, or fabricating bookmark content.
+- Preserve rejection of malformed escapes, non-canonical encodings, separators, control characters, dot segments, invalid Unicode, and genuinely overlong routes.
+- Preserve exact identifiers through semantic navigation, action-result routing, direct loads, HTMX replacement, history restoration, back, and forward navigation.
+- Convert the Reference Application composite-values route from a retained `invalid-route` gap into a passing executable regression while retaining unrelated route and union mismatch behavior.
+- Keep GraphQL operations, public Causeway elements and events, strict CSP, route-lazy assets, Vaadin policy, and native fallback unchanged.
+
+## Capabilities
+
+### New Capabilities
+
+None.
+
+### Modified Capabilities
+
+- `generic-htmx-web-component-viewer`: Refine canonical bookmark routing so bounded long opaque identifiers round-trip consistently across browser and server codecs.
+- `reference-application-viewer-regression-suite`: Replace the retained composite-values invalid-route assertion with direct-load and history qualification for the exact authoritative identifier.
+
+## Impact
+
+The change affects the HTMX Java and browser route codecs, route unit tests, HTMX documentation, and focused Reference Application integration and Playwright coverage.
+It adds no dependency, public GraphQL field, route grammar, application configuration, asset, CSP source, or Vaadin surface.
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/specs/generic-htmx-web-component-viewer/spec.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/specs/generic-htmx-web-component-viewer/spec.md
new file mode 100644
index 00000000000..eec4cd4985a
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/specs/generic-htmx-web-component-viewer/spec.md
@@ -0,0 +1,30 @@
+## MODIFIED Requirements
+
+### Requirement: Canonical bookmark routing
+The viewer SHALL map a public logical type and opaque object identifier to one documented round-trippable route grammar beneath a configurable base path.
+Each browser-generated and server-parsed segment MUST use the same canonical UTF-8 percent encoding and MUST remain within the documented encoded-segment bound without interpreting or altering identifier content.
+
+#### Scenario: Direct object route is requested
+- **WHEN** `<base-path>/object/<logical-type>/<identifier>` contains independently canonical percent-encoded route segments
+- **THEN** the router renders the object page for that exact logical route identity
+- **AND** browser history represents the same canonical route
+
+#### Scenario: Semantic navigation is requested
+- **WHEN** a component publishes an object navigation or object-result event
+- **THEN** default route policy constructs the same canonical route from the exact advertised identity
+- **AND** HTMX replaces only the route region while pushing that route into browser history
+
+#### Scenario: Long authoritative identifier remains within the route bound
+- **WHEN** GraphQL returns a valid opaque identifier longer than the former decoded-character limit whose canonical encoded segment remains within the documented bound
+- **THEN** browser and server codecs preserve and round-trip the identifier exactly
+- **AND** direct load, HTMX replacement, history restoration, back, and forward reconstruct the same object context
+
+#### Scenario: Route encoding is invalid
+- **WHEN** a route contains malformed escapes, empty values, encoded separators, control characters, dot segments, malformed Unicode, overlong encoded segments, or a non-canonical encoding
+- **THEN** the viewer presents a bounded invalid-route state
+- **AND** does not disclose object state, authorization rules, submitted route content, or raw decoder exceptions
+
+#### Scenario: Viewer is mounted elsewhere
+- **WHEN** an application configures a valid non-root base path
+- **THEN** shell, object, asset, home, and history URLs consistently use that path
+- **AND** no route assumes deployment at the origin root
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/specs/reference-application-viewer-regression-suite/spec.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/specs/reference-application-viewer-regression-suite/spec.md
new file mode 100644
index 00000000000..8de61388e49
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/specs/reference-application-viewer-regression-suite/spec.md
@@ -0,0 +1,25 @@
+## ADDED Requirements
+
+### Requirement: Opaque bookmark route regression coverage
+The pinned Reference Application suite SHALL exercise the authoritative long memento identifier returned for `demo.CompositeValuesPage` through the generic HTMX canonical route.
+It MUST preserve the exact identifier, distinguish corrected routing from object-read failures, and retain unrelated bounded invalid-route behavior.
+
+#### Scenario: Composite-values result is routed
+- **WHEN** `demo.CompositeValueTypeMenu.compositeValueTypes` returns the `demo.CompositeValuesPage` identity
+- **THEN** its exact opaque identifier produces a canonical HTMX object route within the supported encoded bound
+- **AND** the route reaches ready or documented partial object state instead of `invalid-route`
+
+#### Scenario: Composite-values route reconstructs identity
+- **WHEN** the server renders the canonical composite-values route
+- **THEN** the route object context contains the same logical type and byte-for-byte identifier returned by GraphQL
+- **AND** representative composite value content remains visible through the authoritative object read
+
+#### Scenario: Composite-values history is traversed
+- **WHEN** navigation replaces the active object route with the composite-values route and the browser traverses back and forward
+- **THEN** each history entry restores its exact canonical logical identity and route state
+- **AND** stale work from the replaced route cannot overwrite the restored context
+
+#### Scenario: Malformed route remains bounded
+- **WHEN** the same qualification run requests malformed escapes, separators, controls, non-canonical encoding, or a segment beyond the supported encoded bound
+- **THEN** the viewer retains its non-disclosing `invalid-route` presentation
+- **AND** successful long opaque routing does not weaken route validation
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/tasks.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/tasks.md
new file mode 100644
index 00000000000..314deaa3c88
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/tasks.md
@@ -0,0 +1,66 @@
+## 1. Establish route-bound evidence
+
+- [ ] 1.1 Capture the authoritative `demo.CompositeValuesPage` identifier length and canonical encoded length without recording its protected content.
+- [ ] 1.2 Record the current browser and Java route validation units, accepted bound, and failure boundary.
+- [ ] 1.3 Define shared valid, boundary, overflow, Unicode, reserved-character, and malformed route vectors.
+
+## 2. Correct the Java route codec
+
+- [ ] 2.1 Replace the decoded UTF-16 character limit with bounded UTF-8 and canonical encoded-size validation.
+- [ ] 2.2 Preserve exact UTF-8 percent encoding and decode-then-reencode canonicality.
+- [ ] 2.3 Preserve rejection of empty values, dot segments, separators, controls, malformed UTF-8, malformed escapes, and non-canonical encodings.
+- [ ] 2.4 Preserve the bounded complete-path check before segment decoding.
+- [ ] 2.5 Keep invalid-route exceptions generic and free of submitted route content.
+
+## 3. Correct the browser route codec
+
+- [ ] 3.1 Apply the same UTF-8 and final encoded-size bounds before returning a canonical segment.
+- [ ] 3.2 Detect unpaired UTF-16 surrogates and convert native encoding failures into the bounded route error.
+- [ ] 3.3 Preserve the existing percent-encoding grammar for reserved punctuation.
+- [ ] 3.4 Keep canonical object paths independent of identity meaning and route producer.
+
+## 4. Add codec and controller verification
+
+- [ ] 4.1 Add Java round-trip coverage for long ASCII-oriented opaque identifiers within the encoded bound.
+- [ ] 4.2 Add Java exact-bound and one-character-overflow coverage.
+- [ ] 4.3 Add Java multibyte, malformed Unicode, canonical escape, separator, control, and whole-path bound coverage.
+- [ ] 4.4 Add browser vectors equivalent to the Java accepted and rejected cases.
+- [ ] 4.5 Add browser exact-bound and encoded-expansion overflow coverage.
+- [ ] 4.6 Verify full-page, HTMX fragment, context-path, and history-restore responses preserve a valid long identifier exactly.
+- [ ] 4.7 Verify invalid long or malformed routes still return non-disclosing `invalid-route` and canonical root history behavior.
+
+## 5. Qualify the pinned Reference Application
+
+- [ ] 5.1 Add focused integration evidence for the composite-values action result metadata and identifier bounds.
+- [ ] 5.2 Verify the server codec round-trips the exact GraphQL-returned composite identifier.
+- [ ] 5.3 Replace the browser `invalid-route` expectation with a ready or documented partial object-state assertion.
+- [ ] 5.4 Assert the rendered object context retains the exact returned logical type and identifier.
+- [ ] 5.5 Assert representative composite-value content remains visible after reconstruction.
+- [ ] 5.6 Exercise semantic route replacement to the long identifier rather than only a manually assembled URL.
+- [ ] 5.7 Exercise back and forward restoration around the long route and reject stale replacement.
+- [ ] 5.8 Retain focused malformed-route and unrelated raw-union mismatch assertions.
+- [ ] 5.9 Verify clean and incremental capability inventory generation remain byte-identical.
+
+## 6. Preserve compatibility and isolation
+
+- [ ] 6.1 Verify ordinary Petclinic direct, semantic, result, home, custom, and generic routes remain canonical.
+- [ ] 6.2 Verify configured non-root base paths and context paths remain correct.
+- [ ] 6.3 Verify public semantic navigation and result event payloads remain unchanged.
+- [ ] 6.4 Verify no GraphQL, metamodel bookmark, dependency, asset, CSP, Vaadin, or native fallback policy changes.
+- [ ] 6.5 Verify rejected route values do not enter HTML, headers, errors, diagnostics, or test evidence.
+
+## 7. Document the corrected contract
+
+- [ ] 7.1 Update HTMX route documentation with byte-oriented and encoded-segment bounds.
+- [ ] 7.2 Add a route-bound and canonicalization matrix with safe measured Reference Application evidence.
+- [ ] 7.3 Add reproducible focused and full qualification commands.
+- [ ] 7.4 Add implementation, compatibility, rollback, and retained-gap evidence.
+- [ ] 7.5 Record final gate results and the next recommended change.
+
+## 8. Run final qualification gates
+
+- [ ] 8.1 Run HTMX Java, browser route-policy, foundation, and web-component Maven suites.
+- [ ] 8.2 Run the full Petclinic integration and Playwright suites.
+- [ ] 8.3 Run the Reference Application clean package, integration, inventory, and Playwright suites.
+- [ ] 8.4 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
+- [ ] 8.5 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
diff --git a/openspec/planned-changes/web-component-viewer/README.md b/openspec/planned-changes/web-component-viewer/README.md
index d9b6f8635a4..85c16e6c8e2 100644
--- a/openspec/planned-changes/web-component-viewer/README.md
+++ b/openspec/planned-changes/web-component-viewer/README.md
@@ -7,7 +7,7 @@ The Reference Application regression suite and input-value hardening changes are
The action-dispatch correctness change is archived, completing the remaining Priority 0 correction identified by that broad capability inventory.
The versionless-identity and preparation correction is archived.
The union-projection correction is archived.
-The next change should address opaque-route handling before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
+The active `fix-webcomponent-opaque-route-correctness` change addresses long authoritative bookmarks before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
The older Vue, Svelte, metadata, diagnostics, performance-analysis, catalogue, and designer drafts remain queued behind that higher-priority qualification and default-adoption work.
Complete child directories contain `.openspec.yaml`, `proposal.md`, `design.md`, `tasks.md`, and delta specifications and can be promoted verbatim after review.
diff --git a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
index d640788c5a1..0b5aff3d9c6 100644
--- a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
+++ b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
@@ -8,7 +8,7 @@ The repository permits one active OpenSpec change at a time.
The Reference Application suite and input-value hardening are archived.
The archived `fix-webcomponent-action-dispatch-correctness` change completed the remaining Priority 0 correctness tranche identified by the pinned regression corpus.
The archived `fix-webcomponent-versionless-identity-preparation` change isolates concrete versionless identity.
-The archived `fix-webcomponent-union-projection-correctness` change precedes the separate opaque-route correction.
+The archived `fix-webcomponent-union-projection-correctness` change precedes the active `fix-webcomponent-opaque-route-correctness` correction.
Proposal-only drafts must be refined against checked-in capability evidence before promotion.
| Order | Proposal | Purpose | Promotion gate |
@@ -16,7 +16,7 @@ Proposal-only drafts must be refined against checked-in capability evidence befo
| 1 | `add-referenceapp-webcomponent-regression-suite` *(archived)* | Copy the pinned broad corpus, establish deterministic inventory, and expose real gaps. | Completed with reviewed classifications. |
| 2 | `harden-webcomponent-input-value-semantics` *(archived)* | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Completed against stable Reference Application fixtures. |
| 3 | `fix-webcomponent-action-dispatch-correctness` *(archived)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Completed with successful typed Reference Application interactions and unchanged public operations. |
-| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, `fix-webcomponent-union-projection-correctness` *(archived)*, then focused opaque-route handling | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
+| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, `fix-webcomponent-union-projection-correctness` *(archived)*, `fix-webcomponent-opaque-route-correctness` *(active)* | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
| 5 | `add-paged-graphql-reference-autocomplete` | Add honest server-side reference windows for large datasets. | Public GraphQL operation, identity, preparation, and ordering contracts are accepted. |
| 6 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
| 7 | `make-vaadin-default-for-webcomponent-viewer` | Flip the supported selection policy to Vaadin-first and remove pilot status. | All prerequisite suites pass in default and explicit native modes. |
(causeway) 11/15: fixes long opaque bookmark routing
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit 1557ae96ff308bb1451abc86d0d7eee13f9b4b5b
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 14:43:48 2026 +0100
fixes long opaque bookmark routing
---
.../evidence/REPRODUCING.md | 52 +++++++++++++
.../evidence/final-gate-results.md | 28 +++++++
.../evidence/implementation-report.md | 29 ++++++++
.../evidence/production-isolation.md | 13 ++++
.../evidence/route-bound-matrix.md | 33 +++++++++
.../tasks.md | 86 +++++++++++-----------
.../htmx/ReferenceAppHtmxPlaywrightTest.java | 27 ++++++-
.../ReferenceAppCapabilityInventory_IntegTest.java | 3 +-
.../ReferenceAppHtmxApplication_IntegTest.java | 46 ++++++++++++
.../referenceapp/referenceapp-targets.json | 3 +-
viewers/webcomponents/htmx/README.adoc | 7 +-
.../viewer/webcomponents/htmx/HtmxRouteCodec.java | 8 +-
.../resources/causeway-htmx/route-policy.mjs | 45 ++++++++++-
.../webcomponents/htmx/HtmxRouteCodecTest.java | 33 ++++++++-
.../htmx/HtmxViewerControllerTest.java | 24 ++++++
.../webcomponents/htmx/test/route-policy.test.mjs | 15 +++-
16 files changed, 392 insertions(+), 60 deletions(-)
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/REPRODUCING.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/REPRODUCING.md
new file mode 100644
index 00000000000..8f8fe4b0425
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/REPRODUCING.md
@@ -0,0 +1,52 @@
+# Reproducing opaque-route correctness
+
+Use Temurin 25 for Maven commands.
+Install current foundation and HTMX artifacts before running the separate Reference Application reactor.
+
+## Route codecs and controller
+
+```shell
+cd viewers/webcomponents/htmx
+node --test
+cd ../../..
+mvn -f viewers/webcomponents/pom.xml -pl htmx -am \
+ -Dtest=HtmxRouteCodecTest,HtmxViewerControllerTest \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+The tests cover shared canonical vectors, long opaque segments, exact boundaries, percent-encoded expansion, Unicode, reserved punctuation, malformed values, context paths, full pages, fragments, history restoration, and non-disclosing invalid routes.
+
+## Reference Application integration
+
+```shell
+mvn -f viewers/webcomponents/pom.xml -pl foundation,htmx -am -DskipTests install
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Dtest=ReferenceAppHtmxApplication_IntegTest#compositeViewModelIdentityRoundTripsThroughTheBoundedCanonicalRoute \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+The test obtains the authoritative identifier through GraphQL, records only safe lengths, round-trips it through `HtmxRouteCodec`, directly loads the canonical route, and reconstructs the same GraphQL identity and composite value.
+
+## Reference Application browser
+
+```shell
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest#scalarTemporalUrlProtectedAndCustomValueFamiliesRemainTyped \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+The journey dispatches the public semantic navigation event, waits for `demo.CompositeValuesPage`, compares the exact context identifier, verifies composite content, traverses back and forward, and retains malformed-route rejection.
+
+## Full qualification
+
+```shell
+mvn -f viewers/webcomponents/pom.xml -pl foundation,htmx -am test
+mvn -f viewers/webcomponents/pom.xml -pl sample-htmx-petclinic -am -Pplaywright test
+mvn -f regressiontests/referenceapp/pom.xml clean package
+mvn -f regressiontests/referenceapp/pom.xml -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+openspec validate fix-webcomponent-opaque-route-correctness --strict
+git diff --check
+```
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/final-gate-results.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/final-gate-results.md
new file mode 100644
index 00000000000..2a911b6849e
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/final-gate-results.md
@@ -0,0 +1,28 @@
+# Final gate results
+
+## Passed
+
+- HTMX route-policy Node suite: 5 tests passed with zero failures.
+- Web-component foundation and HTMX Maven reactor: `BUILD SUCCESS`.
+- Java route codec and controller focused tests: `BUILD SUCCESS`.
+- Pinned composite-values GraphQL, codec, direct-route, and reconstruction integration: `BUILD SUCCESS`.
+- Petclinic integration and Playwright reactor: `BUILD SUCCESS`.
+- Petclinic Playwright: 4 tests passed with zero failures, errors, or skips.
+- Reference Application ordinary clean package, integration tests, inventory tests, and deterministic fixtures: `BUILD SUCCESS`.
+- Clean and incremental capability inventory retained SHA-256 `75ef904a0d4fbc9c915c74866cdbd503743dab589f7525bbab126baf1eaa024a` byte-for-byte.
+- Reference Application Playwright: 9 tests passed with zero failures, errors, or skips.
+- Vaadin production-like pilot: 5 scenarios with zero axe, CSP, console, page, external-request, or overflow failures.
+- HTMX and Reference Application RAT checks: `BUILD SUCCESS`.
+- Strict OpenSpec validation, `git diff --check`, and production-isolation review: passed.
+
+## Corrected executable outcome
+
+The authoritative `demo.CompositeValuesPage` identifier measures 1,177 Java UTF-16 characters and 1,179 canonical encoded characters without exposing its value.
+The public semantic navigation event now reaches the same canonical route and exact object context instead of `invalid-route`.
+Direct load, GraphQL reconstruction, composite-value rendering, back, and forward retain the exact identity.
+Malformed route shape and encoded-separator unit vectors remain bounded and non-disclosing.
+
+## Retained warning and next step
+
+The standalone foundation RAT goal still reports the same pre-existing `vaadin-reference/README.adoc` and generated `vaadin-reference.js` resources, neither introduced nor modified here.
+The next recommended change is `add-paged-graphql-reference-autocomplete`.
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/implementation-report.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/implementation-report.md
new file mode 100644
index 00000000000..4112e7e076d
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/implementation-report.md
@@ -0,0 +1,29 @@
+# Opaque-route implementation report
+
+## Corrected policy
+
+The Java and browser codecs no longer reject identity based on the former 1,024 UTF-16-character ceiling.
+Both codecs bound source UTF-8 to 4,096 bytes and final canonical percent-encoded representation to 4,096 ASCII characters.
+The server additionally retains its complete raw-path bound and strict decode-then-reencode equality.
+
+Route generation rejects unpaired surrogates, separators, controls, dot segments, excessive UTF-8, and excessive encoded expansion before returning a path.
+Route parsing rejects malformed UTF-8 and escapes, encoded separators, controls, alternate percent spellings, excess segments, and excess complete paths.
+Every failure uses the unchanged generic route error and does not echo submitted content.
+
+## Reference Application outcome
+
+The pinned composite-values identifier safely measures 1,177 Java UTF-16 characters and 1,179 canonical encoded characters.
+It now survives GraphQL result identity, semantic navigation, browser canonicalization, HTMX replacement, server parsing, HTML attribute escaping, object-context reconstruction, GraphQL lookup, and browser back and forward restoration.
+The `complexNumber` property remains visible after reconstruction.
+A malformed encoded separator still reaches the non-disclosing `invalid-route` state.
+
+## Compatibility and rollback
+
+The route grammar, public navigation event, result event, logical type, identifier, base path, context path, response headers, custom-page precedence, generic fallback, and history policy are unchanged.
+Ordinary Petclinic and Reference Application routes continue through the same producer and parser.
+Rollback restores conservative rejection of long memento routes without data migration or persisted-state impact.
+
+## Retained scope
+
+Raw collection rows incompatible with an advertised union remain bounded and separate.
+Paged GraphQL reference autocomplete remains the next planned change.
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/production-isolation.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/production-isolation.md
new file mode 100644
index 00000000000..14cb6df215b
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/production-isolation.md
@@ -0,0 +1,13 @@
+# Production isolation verification
+
+The implementation changes only the existing HTMX Java and browser route codecs, their tests and documentation, and pinned Reference Application qualification.
+No Maven POM, npm manifest, lock file, dependency version, third-party source, GraphQL operation, generated GraphQL name, metamodel bookmark format, application fixture, or persisted data changed.
+
+No public `<causeway-*>` element, semantic event name, event detail, context API, canonical route grammar, custom-page contract, HTMX response header, browser-history policy, base-path property, context-path behavior, or Wicket comparison route changed.
+The authoritative identifier is preserved rather than transformed.
+
+No JavaScript asset URL, route-lazy boundary, Vaadin bundle, checksum, exact CSP hash, CSP directive, widget qualification policy, native fallback, or default-selection behavior changed.
+Rejected route content remains absent from markup, response headers, diagnostics, errors, logs, and evidence.
+
+The accepted per-segment envelope remains bounded at 4,096 canonical encoded characters.
+The change adds no server-side alias registry, session route state, query parameter, cookie, redirect, telemetry, CDN request, or application configuration.
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/route-bound-matrix.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/route-bound-matrix.md
new file mode 100644
index 00000000000..5c61d554156
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/route-bound-matrix.md
@@ -0,0 +1,33 @@
+# Route bound and canonicalization matrix
+
+## Safe Reference Application measurement
+
+The authoritative `demo.CompositeValuesPage` identifier returned by `demo.CompositeValueTypeMenu.compositeValueTypes` measures 1,177 Java UTF-16 characters.
+Its canonical UTF-8 percent-encoded segment measures 1,179 ASCII characters.
+The value itself is intentionally absent from evidence, diagnostics, operation summaries, and test output.
+The former decoded-character ceiling of 1,024 rejected it before GraphQL object reconstruction.
+The corrected encoded-segment ceiling of 4,096 accepts it without changing any byte of identity.
+
+## Shared codec policy
+
+| Case | Browser generation | Server generation and parsing |
+|---|---|---|
+| Ordinary ASCII and unreserved punctuation | Preserve unreserved bytes | Preserve unreserved bytes |
+| Space, query, fragment, and reserved punctuation | Uppercase UTF-8 percent encoding | Uppercase UTF-8 percent encoding |
+| Multibyte Unicode | Encode exact UTF-8 bytes without normalization | Decode strict UTF-8 and require exact re-encoding |
+| Long ASCII memento within 4,096 encoded characters | Accept | Accept |
+| Exactly 4,096 unreserved ASCII characters | Accept | Accept |
+| More than 4,096 UTF-8 bytes | Reject before encoding allocation | Reject before canonical path construction |
+| UTF-8 within 4,096 bytes but percent encoding exceeds 4,096 characters | Reject final representation | Reject final representation |
+| Empty, `.` or `..` | Reject | Reject |
+| Slash, backslash, ISO control, or C1 control | Reject | Reject literal or encoded form |
+| Unpaired UTF-16 surrogate | Reject with bounded route error | Reject with bounded route error |
+| Malformed UTF-8 or percent escape | Not constructible | Reject |
+| Lowercase or unnecessary percent escape | Not emitted | Reject through decode-then-reencode inequality |
+| Whole raw route beyond two bounded segments plus fixed syntax | Not emitted | Reject before segment decoding |
+
+## End-to-end paths
+
+The same `canonicalObjectPath` producer serves semantic navigation requests, object results, object homes, collection links, and ordinary anchors.
+The server parses every direct, HTMX, and history-restore request into `HtmxObjectRoute` before rendering one route context.
+No composite-values special case, query parameter, short token, hash, alias, session state, or server-side identity registry exists.
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/tasks.md b/openspec/changes/fix-webcomponent-opaque-route-correctness/tasks.md
index 314deaa3c88..637c861b34c 100644
--- a/openspec/changes/fix-webcomponent-opaque-route-correctness/tasks.md
+++ b/openspec/changes/fix-webcomponent-opaque-route-correctness/tasks.md
@@ -1,66 +1,66 @@
## 1. Establish route-bound evidence
-- [ ] 1.1 Capture the authoritative `demo.CompositeValuesPage` identifier length and canonical encoded length without recording its protected content.
-- [ ] 1.2 Record the current browser and Java route validation units, accepted bound, and failure boundary.
-- [ ] 1.3 Define shared valid, boundary, overflow, Unicode, reserved-character, and malformed route vectors.
+- [x] 1.1 Capture the authoritative `demo.CompositeValuesPage` identifier length and canonical encoded length without recording its protected content.
+- [x] 1.2 Record the current browser and Java route validation units, accepted bound, and failure boundary.
+- [x] 1.3 Define shared valid, boundary, overflow, Unicode, reserved-character, and malformed route vectors.
## 2. Correct the Java route codec
-- [ ] 2.1 Replace the decoded UTF-16 character limit with bounded UTF-8 and canonical encoded-size validation.
-- [ ] 2.2 Preserve exact UTF-8 percent encoding and decode-then-reencode canonicality.
-- [ ] 2.3 Preserve rejection of empty values, dot segments, separators, controls, malformed UTF-8, malformed escapes, and non-canonical encodings.
-- [ ] 2.4 Preserve the bounded complete-path check before segment decoding.
-- [ ] 2.5 Keep invalid-route exceptions generic and free of submitted route content.
+- [x] 2.1 Replace the decoded UTF-16 character limit with bounded UTF-8 and canonical encoded-size validation.
+- [x] 2.2 Preserve exact UTF-8 percent encoding and decode-then-reencode canonicality.
+- [x] 2.3 Preserve rejection of empty values, dot segments, separators, controls, malformed UTF-8, malformed escapes, and non-canonical encodings.
+- [x] 2.4 Preserve the bounded complete-path check before segment decoding.
+- [x] 2.5 Keep invalid-route exceptions generic and free of submitted route content.
## 3. Correct the browser route codec
-- [ ] 3.1 Apply the same UTF-8 and final encoded-size bounds before returning a canonical segment.
-- [ ] 3.2 Detect unpaired UTF-16 surrogates and convert native encoding failures into the bounded route error.
-- [ ] 3.3 Preserve the existing percent-encoding grammar for reserved punctuation.
-- [ ] 3.4 Keep canonical object paths independent of identity meaning and route producer.
+- [x] 3.1 Apply the same UTF-8 and final encoded-size bounds before returning a canonical segment.
+- [x] 3.2 Detect unpaired UTF-16 surrogates and convert native encoding failures into the bounded route error.
+- [x] 3.3 Preserve the existing percent-encoding grammar for reserved punctuation.
+- [x] 3.4 Keep canonical object paths independent of identity meaning and route producer.
## 4. Add codec and controller verification
-- [ ] 4.1 Add Java round-trip coverage for long ASCII-oriented opaque identifiers within the encoded bound.
-- [ ] 4.2 Add Java exact-bound and one-character-overflow coverage.
-- [ ] 4.3 Add Java multibyte, malformed Unicode, canonical escape, separator, control, and whole-path bound coverage.
-- [ ] 4.4 Add browser vectors equivalent to the Java accepted and rejected cases.
-- [ ] 4.5 Add browser exact-bound and encoded-expansion overflow coverage.
-- [ ] 4.6 Verify full-page, HTMX fragment, context-path, and history-restore responses preserve a valid long identifier exactly.
-- [ ] 4.7 Verify invalid long or malformed routes still return non-disclosing `invalid-route` and canonical root history behavior.
+- [x] 4.1 Add Java round-trip coverage for long ASCII-oriented opaque identifiers within the encoded bound.
+- [x] 4.2 Add Java exact-bound and one-character-overflow coverage.
+- [x] 4.3 Add Java multibyte, malformed Unicode, canonical escape, separator, control, and whole-path bound coverage.
+- [x] 4.4 Add browser vectors equivalent to the Java accepted and rejected cases.
+- [x] 4.5 Add browser exact-bound and encoded-expansion overflow coverage.
+- [x] 4.6 Verify full-page, HTMX fragment, context-path, and history-restore responses preserve a valid long identifier exactly.
+- [x] 4.7 Verify invalid long or malformed routes still return non-disclosing `invalid-route` and canonical root history behavior.
## 5. Qualify the pinned Reference Application
-- [ ] 5.1 Add focused integration evidence for the composite-values action result metadata and identifier bounds.
-- [ ] 5.2 Verify the server codec round-trips the exact GraphQL-returned composite identifier.
-- [ ] 5.3 Replace the browser `invalid-route` expectation with a ready or documented partial object-state assertion.
-- [ ] 5.4 Assert the rendered object context retains the exact returned logical type and identifier.
-- [ ] 5.5 Assert representative composite-value content remains visible after reconstruction.
-- [ ] 5.6 Exercise semantic route replacement to the long identifier rather than only a manually assembled URL.
-- [ ] 5.7 Exercise back and forward restoration around the long route and reject stale replacement.
-- [ ] 5.8 Retain focused malformed-route and unrelated raw-union mismatch assertions.
-- [ ] 5.9 Verify clean and incremental capability inventory generation remain byte-identical.
+- [x] 5.1 Add focused integration evidence for the composite-values action result metadata and identifier bounds.
+- [x] 5.2 Verify the server codec round-trips the exact GraphQL-returned composite identifier.
+- [x] 5.3 Replace the browser `invalid-route` expectation with a ready or documented partial object-state assertion.
+- [x] 5.4 Assert the rendered object context retains the exact returned logical type and identifier.
+- [x] 5.5 Assert representative composite-value content remains visible after reconstruction.
+- [x] 5.6 Exercise semantic route replacement to the long identifier rather than only a manually assembled URL.
+- [x] 5.7 Exercise back and forward restoration around the long route and reject stale replacement.
+- [x] 5.8 Retain focused malformed-route and unrelated raw-union mismatch assertions.
+- [x] 5.9 Verify clean and incremental capability inventory generation remain byte-identical.
## 6. Preserve compatibility and isolation
-- [ ] 6.1 Verify ordinary Petclinic direct, semantic, result, home, custom, and generic routes remain canonical.
-- [ ] 6.2 Verify configured non-root base paths and context paths remain correct.
-- [ ] 6.3 Verify public semantic navigation and result event payloads remain unchanged.
-- [ ] 6.4 Verify no GraphQL, metamodel bookmark, dependency, asset, CSP, Vaadin, or native fallback policy changes.
-- [ ] 6.5 Verify rejected route values do not enter HTML, headers, errors, diagnostics, or test evidence.
+- [x] 6.1 Verify ordinary Petclinic direct, semantic, result, home, custom, and generic routes remain canonical.
+- [x] 6.2 Verify configured non-root base paths and context paths remain correct.
+- [x] 6.3 Verify public semantic navigation and result event payloads remain unchanged.
+- [x] 6.4 Verify no GraphQL, metamodel bookmark, dependency, asset, CSP, Vaadin, or native fallback policy changes.
+- [x] 6.5 Verify rejected route values do not enter HTML, headers, errors, diagnostics, or test evidence.
## 7. Document the corrected contract
-- [ ] 7.1 Update HTMX route documentation with byte-oriented and encoded-segment bounds.
-- [ ] 7.2 Add a route-bound and canonicalization matrix with safe measured Reference Application evidence.
-- [ ] 7.3 Add reproducible focused and full qualification commands.
-- [ ] 7.4 Add implementation, compatibility, rollback, and retained-gap evidence.
-- [ ] 7.5 Record final gate results and the next recommended change.
+- [x] 7.1 Update HTMX route documentation with byte-oriented and encoded-segment bounds.
+- [x] 7.2 Add a route-bound and canonicalization matrix with safe measured Reference Application evidence.
+- [x] 7.3 Add reproducible focused and full qualification commands.
+- [x] 7.4 Add implementation, compatibility, rollback, and retained-gap evidence.
+- [x] 7.5 Record final gate results and the next recommended change.
## 8. Run final qualification gates
-- [ ] 8.1 Run HTMX Java, browser route-policy, foundation, and web-component Maven suites.
-- [ ] 8.2 Run the full Petclinic integration and Playwright suites.
-- [ ] 8.3 Run the Reference Application clean package, integration, inventory, and Playwright suites.
-- [ ] 8.4 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
-- [ ] 8.5 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
+- [x] 8.1 Run HTMX Java, browser route-policy, foundation, and web-component Maven suites.
+- [x] 8.2 Run the full Petclinic integration and Playwright suites.
+- [x] 8.3 Run the Reference Application clean package, integration, inventory, and Playwright suites.
+- [x] 8.4 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
+- [x] 8.5 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
diff --git a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
index 3879e743b29..7644561a53e 100644
--- a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
+++ b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
@@ -257,11 +257,32 @@ void representativeBooleanEnumTemporalResourceAndCustomValueFamiliesAreRoutable(
final String compositeId = invokeViewModel(
"demo_CompositeValueTypeMenu", "compositeValueTypes", "rich__demo_CompositeValuesPage");
- page.navigate(url("/htmx/object/demo.CompositeValuesPage/"
- + URLEncoder.encode(compositeId, StandardCharsets.UTF_8).replace("+", "%20")),
+ assertThat(compositeId.length()).isGreaterThan(1024).isLessThanOrEqualTo(4096);
+ page.evaluate("target => document.dispatchEvent(new CustomEvent('causeway-navigation-request', "
+ + "{bubbles: true, composed: true, cancelable: true, detail: {target}}))",
+ Map.of("logicalTypeName", "demo.CompositeValuesPage", "id", compositeId));
+ waitForLogicalType("demo.CompositeValuesPage");
+ final Locator compositeContext = page.locator("#causeway-route causeway-object-context");
+ assertThat(compositeContext.getAttribute("object-id")).isEqualTo(compositeId);
+ assertThat(page.evaluate("() => decodeURIComponent(location.pathname.substring(location.pathname.lastIndexOf('/') + 1))"))
+ .isEqualTo(compositeId);
+ final Locator complexNumber = page.locator("causeway-property[member='complexNumber']");
+ complexNumber.waitFor();
+ assertThat(complexNumber.count()).isEqualTo(1);
+ assertThat(complexNumber.innerText()).isNotBlank();
+
+ page.goBack();
+ waitForLogicalType("demo.CausewayPasswordEntity");
+ page.goForward();
+ waitForLogicalType("demo.CompositeValuesPage");
+ assertThat(page.locator("#causeway-route causeway-object-context").getAttribute("object-id"))
+ .isEqualTo(compositeId);
+
+ page.navigate(url("/htmx/object/type/id/extra"),
new Page.NavigateOptions().setWaitUntil(WaitUntilState.DOMCONTENTLOADED));
page.waitForFunction("() => document.querySelector(\"[data-testid='causeway-route-page']\")?.dataset.routeState === 'invalid-route'");
- assertThat(page.locator(ROUTE_PAGE).innerText()).containsIgnoringCase("invalid");
+ assertThat(page.locator(ROUTE_PAGE).innerText()).containsIgnoringCase("invalid")
+ .doesNotContain("id/extra");
}
@Test
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
index 89e5ca5b463..6eec2ca7468 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
@@ -118,7 +118,8 @@ private void assertJourneyTargetsExist(final JsonNode introspection) throws Exce
"collection-associated-actions", "collection-stale-partial",
"boolean-nullable", "numeric-decimal", "numeric-integer", "temporal-local-date",
"temporal-offset-date-time", "temporal-zoned-date-time", "enum",
- "reference-autocomplete", "url", "protected-password", "blob", "clob", "custom-value");
+ "reference-autocomplete", "url", "protected-password", "blob", "clob", "custom-value",
+ "opaque-route");
}
private JsonNode graphQL(final String query) throws Exception {
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
index c3c9447ab2d..045b16b9758 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
@@ -28,6 +28,9 @@
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.ActiveProfiles;
+import org.apache.causeway.viewer.webcomponents.htmx.HtmxObjectRoute;
+import org.apache.causeway.viewer.webcomponents.htmx.HtmxRouteCodec;
+
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(
@@ -315,6 +318,49 @@ void polymorphicCollectionsCompleteUnionMembershipAndAcceptFragments() throws Ex
assertThat(first.at("/name/get").asText()).isNotBlank();
}
+ @Test
+ void compositeViewModelIdentityRoundTripsThroughTheBoundedCanonicalRoute() throws Exception {
+ final JsonNode opened = graphQL("""
+ mutation {
+ demo_CompositeValueTypeMenu__compositeValueTypes {
+ _meta { id logicalTypeName title }
+ }
+ }
+ """);
+ assertNoGraphQLErrors(opened);
+ final JsonNode metadata = opened.at(
+ "/data/demo_CompositeValueTypeMenu__compositeValueTypes/_meta");
+ final String identifier = metadata.path("id").asText();
+ assertThat(metadata.path("logicalTypeName").asText()).isEqualTo("demo.CompositeValuesPage");
+ assertThat(identifier.length()).isGreaterThan(1024).isLessThanOrEqualTo(4096);
+
+ final HtmxRouteCodec codec = new HtmxRouteCodec("/htmx");
+ final HtmxObjectRoute route = new HtmxObjectRoute("demo.CompositeValuesPage", identifier);
+ final String canonicalPath = codec.objectPath(route);
+ assertThat(canonicalPath.substring(canonicalPath.lastIndexOf('/') + 1).length())
+ .isLessThanOrEqualTo(4096);
+ assertThat(codec.parseObjectPath(canonicalPath)).isEqualTo(route);
+
+ final HttpResponse<String> page = get(canonicalPath);
+ assertThat(page.statusCode()).isEqualTo(200);
+ assertThat(page.body())
+ .contains("data-route-state=\"loading\"")
+ .contains("logical-type=\"demo.CompositeValuesPage\"")
+ .doesNotContain("data-route-state=\"invalid-route\"");
+
+ final JsonNode reconstructed = graphQL("""
+ { rich { demo_CompositeValuesPage(object: {id: %s}) {
+ _meta { id logicalTypeName title }
+ complexNumber { get }
+ } } }
+ """.formatted(OBJECT_MAPPER.writeValueAsString(identifier)));
+ assertNoGraphQLErrors(reconstructed);
+ assertThat(reconstructed.at("/data/rich/demo_CompositeValuesPage/_meta/id").asText())
+ .isEqualTo(identifier);
+ assertThat(reconstructed.at("/data/rich/demo_CompositeValuesPage/complexNumber/get").isMissingNode())
+ .isFalse();
+ }
+
@Test
void exactDecimalPropertyMutationUsesAdvertisedStringAndRestoresFixture() throws Exception {
final JsonNode open = graphQL("""
diff --git a/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json b/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
index 22fc77f122b..60631a164dc 100644
--- a/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
+++ b/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
@@ -40,6 +40,7 @@
{"family": "protected-password", "rootField": "demo_CausewayPasswords", "member": "entities"},
{"family": "blob", "rootField": "demo_CausewayBlobs", "member": "entities"},
{"family": "clob", "rootField": "demo_CausewayClobs", "member": "entities"},
- {"family": "custom-value", "rootField": "demo_CompositeValuesPage", "member": "complexNumber"}
+ {"family": "custom-value", "rootField": "demo_CompositeValuesPage", "member": "complexNumber"},
+ {"family": "opaque-route", "rootField": "demo_CompositeValuesPage", "member": "objectIdentifier"}
]
}
diff --git a/viewers/webcomponents/htmx/README.adoc b/viewers/webcomponents/htmx/README.adoc
index b36e9548367..28b51698046 100644
--- a/viewers/webcomponents/htmx/README.adoc
+++ b/viewers/webcomponents/htmx/README.adoc
@@ -37,8 +37,11 @@ Applications adding other third-party resources must deliberately supply an equi
== Canonical routes
The canonical object route is `<base-path>/object/<logical-type>/<identifier>`.
-The public logical type and opaque identifier are independently UTF-8 percent-encoded as path segments.
-Parsing rejects empty values, malformed escapes, encoded separators, backslashes, controls, dot segments, overlong values, and non-canonical spellings.
+The public logical type and opaque identifier are independently UTF-8 percent-encoded as path segments without interpreting or normalizing identity.
+Each source segment is bounded to 4,096 UTF-8 bytes and each final canonical encoded segment is bounded to 4,096 ASCII characters.
+The encoded bound is normally decisive and permits long ASCII-oriented view-model mementos while bounding browser history, request, decoding, and rendering cost.
+Browser generation and server parsing reject empty values, malformed Unicode or escapes, encoded separators, backslashes, controls, dot segments, overlong UTF-8 or encoded values, and non-canonical spellings.
+Deployments with a proxy or container in front of the viewer must permit the documented canonical route size without decoding path separators.
An ordinary browser request receives a complete document containing one GraphQL client, stable menu bars, announcements, result presentation, and the requested route page.
A request carrying `HX-Request: true` receives only the route fragment and an `HX-Push-Url` response header.
diff --git a/viewers/webcomponents/htmx/src/main/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxRouteCodec.java b/viewers/webcomponents/htmx/src/main/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxRouteCodec.java
index e956a883241..61ec8306b71 100644
--- a/viewers/webcomponents/htmx/src/main/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxRouteCodec.java
+++ b/viewers/webcomponents/htmx/src/main/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxRouteCodec.java
@@ -23,9 +23,10 @@
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
+
public final class HtmxRouteCodec {
- static final int MAX_DECODED_LENGTH = 1024;
+ static final int MAX_UTF8_BYTES = 4096;
static final int MAX_ENCODED_LENGTH = 4096;
private final String basePath;
@@ -164,7 +165,7 @@ public static String normalizeBasePath(final String configured) {
}
private static void validateDecoded(final String value) {
- if (value == null || value.isEmpty() || value.length() > MAX_DECODED_LENGTH
+ if (value == null || value.isEmpty() || value.length() > MAX_UTF8_BYTES
|| ".".equals(value) || "..".equals(value)) {
throw invalid();
}
@@ -176,6 +177,9 @@ private static void validateDecoded(final String value) {
}
offset += Character.charCount(codePoint);
}
+ if (value.getBytes(StandardCharsets.UTF_8).length > MAX_UTF8_BYTES) {
+ throw invalid();
+ }
}
private static boolean isUnreserved(final int value) {
diff --git a/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/route-policy.mjs b/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/route-policy.mjs
index f518a3fc70b..fa8a06a96d5 100644
--- a/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/route-policy.mjs
+++ b/viewers/webcomponents/htmx/src/main/resources/META-INF/resources/causeway-htmx/route-policy.mjs
@@ -17,13 +17,50 @@
* under the License.
*/
+const MAX_UTF8_BYTES = 4096;
+const MAX_ENCODED_LENGTH = 4096;
+const INVALID_ROUTE_MESSAGE = 'The requested application route is invalid.';
+
export function encodeRouteSegment(value) {
const text = String(value ?? '');
- if (!text || text.length > 1024 || text === '.' || text === '..' || /[\\/\u0000-\u001f\u007f]/u.test(text)) {
- throw new Error('The requested application route is invalid.');
+ if (!text || text.length > MAX_UTF8_BYTES || text === '.' || text === '..'
+ || /[\\/\u0000-\u001f\u007f-\u009f]/u.test(text) || hasUnpairedSurrogate(text)) {
+ throw invalidRoute();
+ }
+ if (new TextEncoder().encode(text).length > MAX_UTF8_BYTES) {
+ throw invalidRoute();
+ }
+ let encoded;
+ try {
+ encoded = encodeURIComponent(text).replace(/[!'()*]/g, character =>
+ `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
+ } catch {
+ throw invalidRoute();
}
- return encodeURIComponent(text).replace(/[!'()*]/g, character =>
- `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
+ if (encoded.length > MAX_ENCODED_LENGTH) {
+ throw invalidRoute();
+ }
+ return encoded;
+}
+
+function hasUnpairedSurrogate(text) {
+ for (let index = 0; index < text.length; index += 1) {
+ const current = text.charCodeAt(index);
+ if (current >= 0xd800 && current <= 0xdbff) {
+ const next = text.charCodeAt(index + 1);
+ if (!(next >= 0xdc00 && next <= 0xdfff)) {
+ return true;
+ }
+ index += 1;
+ } else if (current >= 0xdc00 && current <= 0xdfff) {
+ return true;
+ }
+ }
+ return false;
+}
+
+function invalidRoute() {
+ return new Error(INVALID_ROUTE_MESSAGE);
}
export function canonicalObjectPath(basePath, target) {
diff --git a/viewers/webcomponents/htmx/src/test/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxRouteCodecTest.java b/viewers/webcomponents/htmx/src/test/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxRouteCodecTest.java
index 92de7584247..c7f33fb071e 100644
--- a/viewers/webcomponents/htmx/src/test/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxRouteCodecTest.java
+++ b/viewers/webcomponents/htmx/src/test/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxRouteCodecTest.java
@@ -41,6 +41,31 @@ void roundTripsUnicodeLogicalTypeAndOpaqueIdentifier() {
assertThat(codec.parseObjectPath(path)).isEqualTo(route);
}
+ @Test
+ void roundTripsLongOpaqueIdentifierWithinCanonicalEncodedBound() {
+ final var identifier = "memento-" + "a".repeat(3000);
+ final var route = new HtmxObjectRoute("demo.CompositeValuesPage", identifier);
+
+ final var path = codec.objectPath(route);
+
+ assertThat(path).endsWith(identifier);
+ assertThat(codec.parseObjectPath(path)).isEqualTo(route);
+ }
+
+ @Test
+ void acceptsExactEncodedBoundaryAndRejectsOverflowOrExpansion() {
+ assertThat(HtmxRouteCodec.encodeSegment("a".repeat(HtmxRouteCodec.MAX_ENCODED_LENGTH)))
+ .hasSize(HtmxRouteCodec.MAX_ENCODED_LENGTH);
+ assertThatThrownBy(() -> HtmxRouteCodec.encodeSegment("a".repeat(HtmxRouteCodec.MAX_ENCODED_LENGTH + 1)))
+ .isInstanceOf(InvalidHtmxRouteException.class);
+ assertThatThrownBy(() -> HtmxRouteCodec.encodeSegment("é".repeat(2049)))
+ .isInstanceOf(InvalidHtmxRouteException.class);
+ assertThatThrownBy(() -> HtmxRouteCodec.encodeSegment(" ".repeat(1366)))
+ .isInstanceOf(InvalidHtmxRouteException.class);
+ assertThat(HtmxRouteCodec.encodeSegment("!'()*~"))
+ .isEqualTo("%21%27%28%29%2A~");
+ }
+
@Test
void supportsConfiguredDeploymentBasePath() {
assertThat(codec.basePath()).isEqualTo("/apps/petclinic");
@@ -68,14 +93,18 @@ static Stream<String> invalidPaths() {
"/apps/petclinic/object/type/%2F",
"/apps/petclinic/object/type/%5C",
"/apps/petclinic/object/type/%00",
+ "/apps/petclinic/object/type/%C2%80",
+ "/apps/petclinic/object/type/%ED%A0%80",
"/apps/petclinic/object/type/%2E%2E",
"/apps/petclinic/object/type/%41",
"/other/object/type/id");
}
@Test
- void rejectsOverlongValuesAndInvalidBasePaths() {
- assertThatThrownBy(() -> codec.objectPath(new HtmxObjectRoute("type", "x".repeat(1025))))
+ void rejectsOverlongValuesMalformedUnicodeAndInvalidBasePaths() {
+ assertThatThrownBy(() -> codec.objectPath(new HtmxObjectRoute("type", "x".repeat(4097))))
+ .isInstanceOf(InvalidHtmxRouteException.class);
+ assertThatThrownBy(() -> codec.objectPath(new HtmxObjectRoute("type", "\ud800")))
.isInstanceOf(InvalidHtmxRouteException.class);
assertThatThrownBy(() -> new HtmxRouteCodec("/"))
.isInstanceOf(IllegalArgumentException.class);
diff --git a/viewers/webcomponents/htmx/src/test/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxViewerControllerTest.java b/viewers/webcomponents/htmx/src/test/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxViewerControllerTest.java
index 99e222a754c..fcdf1dbb26f 100644
--- a/viewers/webcomponents/htmx/src/test/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxViewerControllerTest.java
+++ b/viewers/webcomponents/htmx/src/test/java/org/apache/causeway/viewer/webcomponents/htmx/HtmxViewerControllerTest.java
@@ -52,6 +52,26 @@ void returnsCompleteStableShellForOrdinaryObjectRequest() {
assertThat(response.getHeaders().getFirst("HX-Push-Url")).isNull();
}
+ @Test
+ void preservesLongOpaqueIdentityAcrossFullFragmentAndHistoryResponses() {
+ final var controller = controller(List.of());
+ final var identifier = "memento-" + "a".repeat(3000);
+ final var route = new HtmxObjectRoute("demo.CompositeValuesPage", identifier);
+ final var canonicalPath = codec.objectPath(route);
+
+ final var full = controller.route(request("/app" + canonicalPath, "/app", false));
+ final var fragment = controller.route(request("/app" + canonicalPath, "/app", true));
+ final var historyRequest = request("/app" + canonicalPath, "/app", true);
+ historyRequest.addHeader("HX-History-Restore-Request", "true");
+ final var history = controller.route(historyRequest);
+
+ assertThat(full.getBody()).contains("object-id=\"" + identifier + "\"");
+ assertThat(fragment.getBody()).contains("object-id=\"" + identifier + "\"");
+ assertThat(fragment.getHeaders().getFirst("HX-Push-Url")).isEqualTo("/app" + canonicalPath);
+ assertThat(history.getBody()).contains("object-id=\"" + identifier + "\"");
+ assertThat(history.getHeaders().getFirst("HX-Push-Url")).isNull();
+ }
+
@Test
void addsOnlyPinnedReferenceWidgetStyleHashesWhenPilotIsEnabled() {
properties.setVaadinReferenceWidgets(true);
@@ -101,11 +121,15 @@ void rendersBoundedInvalidAndLandingStates() {
final var controller = controller(List.of());
final var invalid = controller.route(request("/htmx/object/type/%2F", "", true));
+ final var overlong = controller.route(request("/htmx/object/type/" + "x".repeat(4097), "", true));
final var landing = controller.route(request("/htmx", "", false));
assertThat(invalid.getBody()).contains("data-route-state=\"invalid-route\"")
.doesNotContain("%2F");
assertThat(invalid.getHeaders().getFirst("HX-Push-Url")).isEqualTo("/htmx");
+ assertThat(overlong.getBody()).contains("data-route-state=\"invalid-route\"")
+ .doesNotContain("x".repeat(256));
+ assertThat(overlong.getHeaders().getFirst("HX-Push-Url")).isEqualTo("/htmx");
assertThat(landing.getBody()).contains("data-route-state=\"landing\"")
.contains("data-causeway-home-message");
}
diff --git a/viewers/webcomponents/htmx/test/route-policy.test.mjs b/viewers/webcomponents/htmx/test/route-policy.test.mjs
index 2c74838bf95..78161bd5e4f 100644
--- a/viewers/webcomponents/htmx/test/route-policy.test.mjs
+++ b/viewers/webcomponents/htmx/test/route-policy.test.mjs
@@ -32,6 +32,17 @@ test('canonical route independently encodes public identity', () => {
canonicalObjectPath('/app/htmx/', {logicalTypeName: 'petclinic.Pet Owner∕β', id: 'owner ?#42 café'}),
'/app/htmx/object/petclinic.Pet%20Owner%E2%88%95%CE%B2/owner%20%3F%2342%20caf%C3%A9'
);
+ assert.equal(encodeRouteSegment("!'()*~"), '%21%27%28%29%2A~');
+});
+
+test('long opaque routes honor UTF-8 and canonical encoded bounds', () => {
+ const longIdentifier = `memento-${'a'.repeat(3000)}`;
+ assert.equal(encodeRouteSegment(longIdentifier), longIdentifier);
+ assert.equal(encodeRouteSegment('a'.repeat(4096)).length, 4096);
+ assert.throws(() => encodeRouteSegment('a'.repeat(4097)), /invalid/);
+ assert.throws(() => encodeRouteSegment('é'.repeat(2049)), /invalid/);
+ assert.throws(() => encodeRouteSegment(' '.repeat(1366)), /invalid/);
+ assert.equal(encodeRouteSegment('é'.repeat(455)).length, 2730);
});
test('shared cross-viewer route fixtures retain canonical HTMX meaning', async () => {
@@ -45,8 +56,8 @@ test('shared cross-viewer route fixtures retain canonical HTMX meaning', async (
assert.match(fixture, /fallbackElement: causeway-object/);
});
-test('route encoding rejects separators controls empties and dot segments', () => {
- for (const value of ['', '.', '..', 'one/two', 'one\\two', 'one\u0000two']) {
+test('route encoding rejects separators controls malformed Unicode empties and dot segments', () => {
+ for (const value of ['', '.', '..', 'one/two', 'one\\two', 'one\u0000two', 'one\u0080two', '\ud800', '\udc00']) {
assert.throws(() => encodeRouteSegment(value), /invalid/);
}
});
(causeway) 08/15: fixes polymorphic GraphQL projections
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit d0ea6ad465eaf04011c1f433564ad14fffae2409
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 13:37:12 2026 +0100
fixes polymorphic GraphQL projections
---
.../design.md | 24 ++-
.../evidence/REPRODUCING.md | 60 ++++++
.../evidence/final-gate-results.md | 28 +++
.../evidence/implementation-report.md | 28 +++
.../evidence/production-isolation.md | 13 ++
.../evidence/union-shape-matrix.md | 31 +++
.../proposal.md | 7 +-
.../spec.md | 37 ++--
.../spec.md | 20 ++
.../tasks.md | 102 ++++-----
.../planned-changes/web-component-viewer/README.md | 2 +-
.../web-component-viewer/vaadin-default-roadmap.md | 4 +-
.../htmx/ReferenceAppHtmxPlaywrightTest.java | 27 +--
.../ReferenceAppCapabilityInventory_IntegTest.java | 3 +-
.../ReferenceAppHtmxApplication_IntegTest.java | 55 +++++
.../referenceapp/referenceapp-targets.json | 2 +
.../model/registry/GraphQLTypeRegistry.java | 18 +-
.../graphql/model/types/TypeMapperDefault.java | 18 +-
.../registry/GraphQLTypeRegistryUnionTest.java | 62 ++++++
viewers/webcomponents/foundation/USAGE.adoc | 7 +-
.../foundation/src/graphql-client.mjs | 5 +-
.../foundation/src/interaction-operations.mjs | 70 +++++++
.../foundation/src/object-context-controller.mjs | 187 +++++++++++++++--
viewers/webcomponents/foundation/src/selection.mjs | 72 ++++++-
.../foundation/test/collection.test.mjs | 231 ++++++++++++++++++++-
.../foundation/test/identity-selection.test.mjs | 33 +++
.../foundation/test/interaction-command.test.mjs | 33 +++
.../foundation/test/interaction.test.mjs | 33 +++
.../foundation/test/selection.test.mjs | 49 ++++-
29 files changed, 1129 insertions(+), 132 deletions(-)
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/design.md b/openspec/changes/fix-webcomponent-union-projection-correctness/design.md
index 5cac1a39934..1cb63f7c1d2 100644
--- a/openspec/changes/fix-webcomponent-union-projection-correctness/design.md
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/design.md
@@ -5,7 +5,9 @@ GraphQL permits `__typename` directly on a union, but concrete metadata and memb
The foundation selection tree and executable renderer currently represent fields and arguments only, so `resultSelectionForType(...)` falls back to `__typename` and abstract collections are rejected locally.
The pinned Reference Application exposes raw-list collection fixtures through `rich__demo_ValueHolder__gqlv_union`.
-The runtime rows are concrete `demo.CollectionTypeOfChildVm` objects with valid metadata, but the viewer cannot select that metadata without fragments.
+Incremental metamodel construction registers that generated union name more than once, while the current registry retains only the first possible-type set.
+The raw-list runtime rows are concrete `demo.CollectionTypeOfChildVm` objects, which do not implement `demo.ValueHolder`; introspection therefore correctly omits that type after union membership is completed.
+The viewer must distinguish this schema/runtime mismatch from its own inability to render valid fragments.
A broad union can advertise many possible domain types, so blindly expanding every possible type would create large operations and excessive introspection.
Mutating actions must never be executed once to discover a result type and again to obtain its value.
@@ -13,24 +15,33 @@ Mutating actions must never be executed once to discover a result type and again
**Goals:**
+- Merge repeated generated union registration so introspection advertises every discovered concrete type.
- Render schema-validated inline fragments through the internal selection model.
- Describe advertised concrete possible types and their metadata without application-specific type lists.
- Project bounded small unions directly.
- Probe broad abstract collection rows with `__typename` and replay the same side-effect-free window or list read once using fragments for observed concrete types.
- Merge concrete row metadata and supported requested columns and preserve hydration coverage.
- Retain cancellation, stale-response, lazy activation, windowing, partial errors, and bounded operation policy.
-- Prove the Reference Application polymorphic collection without changing public GraphQL or component contracts.
+- Prove valid fragment planning in foundation fixtures and classify the Reference Application raw-list schema/runtime mismatch without changing public GraphQL names or component contracts.
**Non-Goals:**
- Repeating mutating actions or property mutations to discover result types.
-- Adding GraphQL schema fields, changing union membership, or changing Causeway metamodel type inference.
+- Adding GraphQL schema fields or generated names, or changing Causeway metamodel type inference beyond merging discovered union membership.
- Providing sorting, filtering, paging beyond existing windows, or unbounded fragment expansion.
- Correcting opaque route encoding or long composite bookmark handling.
- Changing action dispatch, value codecs, Vaadin adapters, dependencies, CSP, or public events.
## Decisions
+### Merge repeated generated union membership
+
+The GraphQL type registry will transform an existing immutable union by adding possible types from a later registration, deduplicated by GraphQL type name, and replace the stored union before schema construction completes.
+The existing resolver registration remains keyed to the same generated union name and later registrations receive the merged union.
+
+The rejected alternative is retaining the first union unchanged, because a runtime resolver can then return a valid metamodel type that GraphQL rejects as absent from the schema union.
+The other rejected alternative is generating context-specific union names, because that changes public generated-name grammar and multiplies structurally equivalent types.
+
### Add a reserved inline-fragment selection node
Internal selections will represent fragments under a reserved `__fragments` map keyed by advertised concrete GraphQL type name.
@@ -47,6 +58,12 @@ A larger or incomplete union remains typename-only unless a side-effect-free col
The rejected alternative is expanding every possible type, because broad domain unions can make request and introspection cost proportional to the complete metamodel.
+### Preserve schema/runtime mismatch as a bounded error
+
+If a typename probe cannot resolve because the runtime object is not a member of the advertised union, the collection retains the GraphQL error locally and does not manufacture a fragment.
+The pinned raw-list Reference Application fixture intentionally remains such a mismatch because `CollectionTypeOfChildVm` does not implement the declared `ValueHolder` interface.
+The declared `typeOf` companion collection remains a concrete supported collection.
+
### Probe and replay broad collection reads once
An activated abstract collection first performs the same bounded list or window operation with `__typename` only.
@@ -81,6 +98,7 @@ This change publishes the existing semantic navigation event with the exact retu
- [A broad union creates excessive introspection] → Introspect only distinct observed types and enforce fixed type and fragment limits.
- [Fragment selections break selection merging or hydration coverage] → Extend merge, difference, and coverage helpers with focused nested-fragment tests.
- [One concrete type lacks a requested column] → Omit that column from its fragment and preserve rows from other concrete types.
+- [Concurrent or repeated union registration loses membership] → Transform and replace the registry entry by name and cover deduplication with a focused model test.
- [A malicious or stale typename is returned] → Require exact membership in the introspected possible-type set before constructing a fragment.
- [Action semantics are accidentally repeated] → Restrict probe/replay to side-effect-free object and collection reads and test that mutation execution remains single-shot.
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/REPRODUCING.md b/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/REPRODUCING.md
new file mode 100644
index 00000000000..24aa2cdaf62
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/REPRODUCING.md
@@ -0,0 +1,60 @@
+# Reproducing union projection evidence
+
+Use Temurin 25 for the GraphQL and copied Reference Application reactors.
+Install current GraphQL model and web-component artifacts before running the separate Reference Application reactor.
+
+## GraphQL model
+
+```shell
+mvn -f viewers/graphql/pom.xml -pl model -am test
+mvn -f viewers/graphql/pom.xml -pl model -am -DskipTests install
+```
+
+`GraphQLTypeRegistryUnionTest` proves possible-type merging and deduplication by generated union name.
+
+## Foundation
+
+```shell
+cd viewers/webcomponents/foundation
+node --test
+```
+
+Focused selection, interaction, and collection coverage verifies inline-fragment rendering, validation, direct expansion, broad probe and replay, mixed concrete rows, missing columns, unadvertised typenames, changed replay types, windows, caching, cancellation, and hydration.
+
+## Reference Application integration
+
+```shell
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Dtest=ReferenceAppHtmxApplication_IntegTest#polymorphicCollectionsCompleteUnionMembershipAndAcceptFragments \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+The test records the pinned 28-member `ValueHolder` union, valid typename and concrete-fragment operations, invalid direct metadata selection, and concrete `typeOf` behavior.
+
+## Reference Application browser
+
+```shell
+mvn -f viewers/webcomponents/pom.xml \
+ -pl foundation,htmx -am -DskipTests install
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest#populatedPagedConfiguredPolymorphicAndRouteReplacedCollectionsRemainVisible \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+The `ActionChoicesFromPage.objects` collection must reach `ready`, expose concrete object links, and retain a fragment selection for `rich__demo_ActionChoicesFromEntity`.
+The declared `CollectionTypeOfPage.children` collection remains concrete and ready, while unreadable `otherChildren` remains a bounded local error.
+
+## Full qualification
+
+```shell
+mvn -f viewers/webcomponents/pom.xml -pl foundation,htmx -am test
+mvn -f viewers/graphql/pom.xml -pl model -am test
+mvn -f viewers/webcomponents/pom.xml -pl sample-htmx-petclinic -am -Pplaywright test
+mvn -f regressiontests/referenceapp/pom.xml clean package
+mvn -f regressiontests/referenceapp/pom.xml -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+openspec validate fix-webcomponent-union-projection-correctness --strict
+git diff --check
+```
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/final-gate-results.md b/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/final-gate-results.md
new file mode 100644
index 00000000000..79abb13e9fe
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/final-gate-results.md
@@ -0,0 +1,28 @@
+# Final gate results
+
+## Passed
+
+- Foundation Node suite: 148 tests passed with zero failures.
+- Web-component foundation and HTMX Maven tests: `BUILD SUCCESS`.
+- GraphQL model reactor, merged-union registry test, and existing model tests: `BUILD SUCCESS`.
+- Pinned Reference Application union membership and fragment integration: `BUILD SUCCESS`.
+- Petclinic integration and Playwright reactor: `BUILD SUCCESS`.
+- Petclinic Playwright: 4 tests passed with zero failures, errors, or skips.
+- Reference Application ordinary clean package, integration tests, inventory tests, and deterministic fixtures: `BUILD SUCCESS`.
+- Incremental capability inventory retained SHA-256 `75ef904a0d4fbc9c915c74866cdbd503743dab589f7525bbab126baf1eaa024a`, identical to the clean baseline.
+- Reference Application Playwright: 9 tests passed with zero failures, errors, or skips.
+- Vaadin production-like pilot: 5 scenarios with zero axe, CSP, console, page, external-request, or overflow failures.
+- GraphQL model and Reference Application RAT checks: `BUILD SUCCESS`.
+- Strict OpenSpec validation and `git diff --check`: passed.
+
+## Corrected executable outcomes
+
+`rich__demo_ValueHolder__gqlv_union` advertises 28 deduplicated concrete types rather than one first-registration member.
+`demo.ActionChoicesFromPage.objects` reaches `ready` through bounded typename probing and a concrete `rich__demo_ActionChoicesFromEntity` fragment.
+Concrete rows preserve semantic identity, object links, values, and hydrated contexts.
+Declared `demo.CollectionTypeOfPage.children` remains a ready concrete collection, while unreadable raw `otherChildren` remains an explicit bounded local error.
+
+## Retained gap and warning
+
+Long opaque composite routes remain the next focused correction.
+The standalone foundation RAT goal still reports the same pre-existing `vaadin-reference/README.adoc` and generated `vaadin-reference.js` resources, neither introduced nor modified here.
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/implementation-report.md b/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/implementation-report.md
new file mode 100644
index 00000000000..b5c10d96745
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/implementation-report.md
@@ -0,0 +1,28 @@
+# Union projection implementation report
+
+## GraphQL model correction
+
+Repeated registration of one generated union now merges possible types by GraphQL name instead of returning the first immutable union unchanged.
+Fields refer to the union by stable `GraphQLTypeReference`, allowing the registry entry to be replaced as incremental metamodel discovery adds members without creating duplicate named schema types.
+The runtime resolver derives the concrete generated type, verifies that it is advertised by the completed union, and resolves it from the built schema.
+
+## Foundation correction
+
+The internal selection grammar now supports a reserved `__fragments` map.
+Structural and interaction renderers sort fragment names, validate parent abstract kind, advertised membership, concrete type description, and nested fields, and emit `__typename` with GraphQL inline fragments.
+Selection merge, difference, and runtime hydration coverage retain fragment structure.
+
+Small abstract collections with at most eight advertised types use direct fragments.
+Broader collections issue one typename-only side-effect-free probe, describe at most sixteen observed advertised types and requested wrappers, and replay identical list or window arguments once.
+Only replay rows are published.
+Unexpected probe typenames are rejected, changed replay types become bounded partial projections, and cancellation or stale generations stop both stages.
+Mutating abstract action results remain single-shot and typename-only when direct expansion is unavailable.
+
+## Reference Application outcomes
+
+`rich__demo_ValueHolder__gqlv_union` now advertises 28 deterministic concrete entity types instead of the first discovered member only.
+`demo.ActionChoicesFromPage.objects` reaches `ready` through a typename probe and concrete `rich__demo_ActionChoicesFromEntity` fragment, renders semantic object links, and preserves typed row values.
+`demo.CollectionTypeOfPage.children` remains a supported concrete `typeOf` collection.
+Its raw `otherChildren` collection exposes no readable `get` capability and remains a bounded local error rather than an invalid speculative union operation.
+
+The long opaque composite bookmark remains a separate `invalid-route` gap.
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/production-isolation.md b/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/production-isolation.md
new file mode 100644
index 00000000000..c5d89ca8e26
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/production-isolation.md
@@ -0,0 +1,13 @@
+# Production isolation verification
+
+No Maven POM, npm package manifest, lock file, dependency version, or third-party source changed.
+No public GraphQL field, argument, scalar, generated type name, lookup grammar, or operation placement changed.
+The possible-type membership of an existing generated union is corrected to include every concrete type discovered during metamodel construction.
+
+No public `<causeway-*>` element, context method, semantic event name, event detail, result kind, canonical route, browser history policy, HTMX lifecycle, or asset URL changed.
+The `__fragments` node is an internal selection representation and is not application-facing markup or API.
+No Vaadin input, generated bundle, checksum, exact CSP hash, qualification policy, route-lazy trigger, native fallback, or default-selection policy changed.
+
+Broad polymorphic probing is restricted to activated side-effect-free collection reads and bounded to one replay.
+Mutating interactions remain single-shot.
+Rollback requires no persisted-data, route, application configuration, dependency, or asset migration.
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/union-shape-matrix.md b/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/union-shape-matrix.md
new file mode 100644
index 00000000000..4d825339e8f
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/union-shape-matrix.md
@@ -0,0 +1,31 @@
+# Union shape matrix
+
+## Registration evidence
+
+The generated union `rich__demo_ValueHolder__gqlv_union` was registered repeatedly while the Reference Application metamodel was built.
+Before correction, introspection retained only the first registration and advertised one possible type, `rich__demo_ActionChoicesFromEntity`.
+After correction, the pinned corpus advertises 28 distinct concrete entity types, including `rich__demo_ActionChoicesFromEntity`.
+Repeated names are deduplicated and fields refer to the generated union through one stable type reference, so schema construction contains no duplicate named types.
+
+## Executable operation shapes
+
+| Shape | Expected behavior |
+|---|---|
+| `objects { get { __typename } }` on `demo.ActionChoicesFromPage` | Returns `rich__demo_ActionChoicesFromEntity` rows. |
+| `objects { get { _meta { id } } }` | Rejected because `_meta` is not a field of `rich__demo_ValueHolder__gqlv_union`. |
+| `objects { get { __typename ... on rich__demo_ActionChoicesFromEntity { _meta { id logicalTypeName title } name { get } } } }` | Returns concrete identity and value through a valid advertised fragment. |
+| `children { get { __typename _meta { id logicalTypeName title } } }` on `demo.CollectionTypeOfPage` | Uses the concrete type supplied by `@Collection(typeOf=...)`; no union projection is required. |
+| `otherChildren` on `demo.CollectionTypeOfPage` | Exposes no readable `get` capability because the raw collection lacks usable element type metadata; the viewer retains a bounded local error. |
+
+## Client bounds
+
+The direct fragment limit is eight advertised concrete types.
+The broad collection probe accepts at most sixteen distinct observed advertised typenames.
+A broad collection performs at most one typename probe and one fragment replay with identical list or window arguments.
+An unadvertised probe typename is rejected before fragment construction.
+A type appearing only during replay remains typename-only with a local partial-projection error and does not trigger another request.
+
+## Retained route gap
+
+The long opaque identifier returned for `demo.CompositeValuesPage` still reaches `invalid-route`.
+Union projection preserves the identifier exactly and does not alter route encoding, decoding, or length policy.
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/proposal.md b/openspec/changes/fix-webcomponent-union-projection-correctness/proposal.md
index 4d9669ea854..b689c0fb1c9 100644
--- a/openspec/changes/fix-webcomponent-union-projection-correctness/proposal.md
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/proposal.md
@@ -5,6 +5,7 @@ The generic web-component viewer cannot currently render valid inline fragments
## What Changes
+- Merge repeated rich GraphQL union registration so `possibleTypes` retains every concrete type discovered during incremental metamodel construction.
- Extend targeted introspection to retain advertised union and interface possible types and describe only the concrete types needed by an executable projection.
- Add an internal selection representation and renderer for validated GraphQL inline fragments with `__typename` discrimination.
- Project small bounded abstract result sets directly through advertised concrete fragments.
@@ -12,7 +13,7 @@ The generic web-component viewer cannot currently render valid inline fragments
- Preserve a bounded typename-only outcome when a safe concrete projection cannot be planned, and never repeat a mutating action to discover its result type.
- Normalize concrete rows and values through existing metadata, identity, hydration, rendering, error, cancellation, and stale-response contracts.
- Add focused foundation and pinned Reference Application coverage while retaining the separate opaque-route gap.
-- Keep GraphQL schema changes, action placement, paging, Vaadin policy, and route encoding outside this change.
+- Keep GraphQL field names, generated type names, action placement, paging, Vaadin policy, and route encoding outside this change.
## Capabilities
@@ -22,10 +23,12 @@ None.
### Modified Capabilities
+- `rich-graphql-object-interaction-correctness`: Require repeated generated union registration to preserve the complete discovered concrete membership.
- `domain-web-components`: Require valid bounded inline-fragment projection and concrete semantic normalization for advertised union and interface values.
-- `reference-application-viewer-regression-suite`: Require successful representative polymorphic property and collection journeys without invalid direct union metadata selection.
+- `reference-application-viewer-regression-suite`: Require valid fragment evidence where schema membership permits it and an explicit bounded schema/runtime mismatch for the retained raw-list fixture.
## Impact
The change affects internal targeted introspection, executable selection rendering, abstract property and collection read planning, action-result projection policy, row hydration coverage, and the pinned Reference Application regression suite.
Public Causeway elements, semantic events, GraphQL fields and generated names, canonical routes, HTMX lifecycle, dependencies, Vaadin qualification policy, CSP inputs, and production asset URLs remain unchanged.
+The advertised membership of an existing generated union is corrected to include all concrete types discovered for that union name.
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md b/openspec/changes/fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md
index ab25a67ef97..cf6e7aa5ff6 100644
--- a/openspec/changes/fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md
@@ -1,28 +1,33 @@
## ADDED Requirements
### Requirement: Polymorphic projection regression coverage
-The pinned Reference Application suite SHALL exercise representative abstract property and collection values through valid concrete GraphQL fragments.
-It MUST preserve deterministic concrete-row identity and member evidence, bounded partial behavior, and the separate opaque-route gap.
+The pinned Reference Application suite SHALL distinguish valid concrete and union projection from a runtime object that is not a member of its advertised union.
+It MUST preserve deterministic concrete-row evidence, bounded schema mismatch behavior, and the separate opaque-route gap.
-#### Scenario: Type-of collection is activated
-- **WHEN** the browser activates the representative `demo.CollectionTypeOfPage` collection exposed through `rich__demo_ValueHolder__gqlv_union`
-- **THEN** the viewer reaches a supported ready or documented partial state without selecting `_meta` directly on the union
-- **AND** concrete `demo.CollectionTypeOfChildVm` rows render their semantic identities and advertised values
+#### Scenario: Declared type-of collection is activated
+- **WHEN** the browser activates `demo.CollectionTypeOfPage.children`, whose `typeOf` metadata supplies the concrete row type
+- **THEN** concrete `demo.CollectionTypeOfChildVm` rows render their semantic identities through the ordinary concrete projection
+- **AND** union probing is not used for that collection
-#### Scenario: Raw collection lacks a declared Java generic
-- **WHEN** the companion collection relies on runtime union typenames rather than a Java generic signature
-- **THEN** the same bounded probe and fragment policy applies
-- **AND** no application-specific concrete-type list is embedded in the viewer
+#### Scenario: Raw collection exposes incompatible runtime rows
+- **WHEN** the companion raw collection is advertised as `rich__demo_ValueHolder__gqlv_union` but returns `demo.CollectionTypeOfChildVm`, which does not implement `demo.ValueHolder`
+- **THEN** GraphQL and the viewer retain a bounded local schema/runtime mismatch
+- **AND** the viewer does not manufacture union membership or an application-specific fragment
-#### Scenario: Polymorphic operation remains bounded
-- **WHEN** the Reference Application union advertises more possible types than are present in one collection window
-- **THEN** evidence records the advertised count, observed concrete types, introspection operations, and final fragment operation
-- **AND** the viewer describes and selects only the bounded required concrete closure
+#### Scenario: Generated union membership is completed incrementally
+- **WHEN** the Reference Application schema repeatedly discovers concrete `demo.ValueHolder` implementations
+- **THEN** introspection advertises the deterministic merged set rather than only the first registration
+- **AND** every advertised fragment name is a valid member of the completed union
+
+#### Scenario: Invalid direct union metadata is rejected
+- **WHEN** a reproduction selects `_meta` directly from `rich__demo_ValueHolder__gqlv_union`
+- **THEN** GraphQL rejects that operation as invalid
+- **AND** valid viewer planning uses typename and concrete fragments only
#### Scenario: Existing collection behavior remains stable
-- **WHEN** the full collection journey also reaches concrete versionless rows, configured columns, lazy tabs, stale windows, partial errors, and route replacement
+- **WHEN** the full collection journey also reaches concrete versionless rows, configured collections, lazy tabs, stale windows, partial errors, and route replacement
- **THEN** those established behaviors retain their passing assertions
-- **AND** polymorphic probing does not make inactive collections eager
+- **AND** polymorphic planning does not make inactive collections eager
#### Scenario: Opaque composite route remains separate
- **WHEN** a projected concrete result carries the long opaque identifier retained by the corpus
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/specs/rich-graphql-object-interaction-correctness/spec.md b/openspec/changes/fix-webcomponent-union-projection-correctness/specs/rich-graphql-object-interaction-correctness/spec.md
new file mode 100644
index 00000000000..a574bcf2dfc
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/specs/rich-graphql-object-interaction-correctness/spec.md
@@ -0,0 +1,20 @@
+## ADDED Requirements
+
+### Requirement: Complete incremental union registration
+Rich GraphQL SHALL preserve the union of concrete possible types discovered by every registration of the same generated interface or union name during metamodel construction.
+It MUST deduplicate possible types by GraphQL name and MUST retain one deterministic generated abstract type and resolver registration.
+
+#### Scenario: Later registration discovers another concrete type
+- **WHEN** a generated union name is registered after an existing registration with one or more additional concrete object types
+- **THEN** the schema registry replaces the stored union with merged possible-type membership
+- **AND** introspection advertises both the earlier and later concrete types
+
+#### Scenario: Registration repeats an existing concrete type
+- **WHEN** another registration contributes a concrete type name already present on the generated union
+- **THEN** the stored union contains that type exactly once
+- **AND** schema construction remains deterministic
+
+#### Scenario: Runtime resolver returns a merged concrete type
+- **WHEN** the union resolver identifies a concrete type contributed by a later registration
+- **THEN** GraphQL validates that type against the completed union membership
+- **AND** a client can select it through an advertised inline fragment
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/tasks.md b/openspec/changes/fix-webcomponent-union-projection-correctness/tasks.md
index bd4de36f1ae..b67a9e458bd 100644
--- a/openspec/changes/fix-webcomponent-union-projection-correctness/tasks.md
+++ b/openspec/changes/fix-webcomponent-union-projection-correctness/tasks.md
@@ -1,76 +1,78 @@
## 1. Capture executable union evidence
-- [ ] 1.1 Capture targeted introspection for `rich__demo_ValueHolder__gqlv_union`, its advertised possible-type count, and representative concrete metadata.
-- [ ] 1.2 Execute typename-only and concrete-fragment operations for both `demo.CollectionTypeOfPage` collections.
-- [ ] 1.3 Record invalid direct union metadata selection and the retained opaque-route gap.
+- [x] 1.1 Capture targeted introspection for `rich__demo_ValueHolder__gqlv_union`, its advertised possible-type count, and representative concrete metadata.
+- [x] 1.2 Execute typename-only and concrete-fragment operations for both `demo.CollectionTypeOfPage` collections.
+- [x] 1.3 Record invalid direct union metadata selection and the retained opaque-route gap.
+- [x] 1.4 Confirm repeated generated union registration currently retains incomplete first-registration membership.
## 2. Extend the internal selection model
-- [ ] 2.1 Define a reserved deterministic inline-fragment selection node.
-- [ ] 2.2 Render `__typename` and sorted `... on Type` fragments with GraphQL-name validation.
-- [ ] 2.3 Reject fragment names not advertised by a union or interface.
-- [ ] 2.4 Validate each fragment against its described concrete type and nested fields.
-- [ ] 2.5 Extend selection merge, difference, emptiness, and coverage helpers for fragments.
-- [ ] 2.6 Preserve scalar, enum, concrete object, resource, and argument rendering behavior.
+- [x] 2.1 Define a reserved deterministic inline-fragment selection node.
+- [x] 2.2 Render `__typename` and sorted `... on Type` fragments with GraphQL-name validation.
+- [x] 2.3 Reject fragment names not advertised by a union or interface.
+- [x] 2.4 Validate each fragment against its described concrete type and nested fields.
+- [x] 2.5 Extend selection merge, difference, emptiness, and coverage helpers for fragments.
+- [x] 2.6 Preserve scalar, enum, concrete object, resource, and argument rendering behavior.
## 3. Describe bounded concrete type closures
-- [ ] 3.1 Add helpers that expose advertised abstract possible-type names deterministically.
-- [ ] 3.2 Describe observed concrete object types and metadata through cached one-type introspection.
-- [ ] 3.3 Describe only requested concrete member wrappers and nested result types needed by row columns.
-- [ ] 3.4 Enforce fixed direct-fragment and observed-type limits.
-- [ ] 3.5 Reject returned typenames absent from the advertised possible-type set.
-- [ ] 3.6 Preserve GraphQL Java good-faith introspection behavior.
+- [x] 3.1 Add helpers that expose advertised abstract possible-type names deterministically.
+- [x] 3.2 Describe observed concrete object types and metadata through cached one-type introspection.
+- [x] 3.3 Describe only requested concrete member wrappers and nested result types needed by row columns.
+- [x] 3.4 Enforce fixed direct-fragment and observed-type limits.
+- [x] 3.5 Reject returned typenames absent from the advertised possible-type set.
+- [x] 3.6 Preserve GraphQL Java good-faith introspection behavior.
+- [x] 3.7 Merge repeated rich GraphQL union registrations by concrete type name and add focused model coverage.
## 4. Plan abstract result selections
-- [ ] 4.1 Build direct inline fragments for bounded fully described unions and interfaces.
-- [ ] 4.2 Retain typename-only projection when direct expansion is incomplete or exceeds the bound.
-- [ ] 4.3 Select each concrete metadata subset through the existing version-aware helper.
-- [ ] 4.4 Preserve single-shot execution for mutating action results.
-- [ ] 4.5 Normalize concrete fragment results without inventing identity for typename-only values.
+- [x] 4.1 Build direct inline fragments for bounded fully described unions and interfaces.
+- [x] 4.2 Retain typename-only projection when direct expansion is incomplete or exceeds the bound.
+- [x] 4.3 Select each concrete metadata subset through the existing version-aware helper.
+- [x] 4.4 Preserve single-shot execution for mutating action results.
+- [x] 4.5 Normalize concrete fragment results without inventing identity for typename-only values.
## 5. Add polymorphic collection probe and replay
-- [ ] 5.1 Replace the abstract-row rejection with a typename-only list or window probe.
-- [ ] 5.2 Collect distinct observed advertised concrete types under the configured bound.
-- [ ] 5.3 Build and execute one concrete-fragment replay with identical collection arguments.
-- [ ] 5.4 Include requested columns only where each concrete type advertises the member wrapper.
-- [ ] 5.5 Publish only the replay result while retaining probe and replay operation evidence.
-- [ ] 5.6 Preserve lazy activation, caching, window state, ordering, cancellation, stale generations, and route disposal.
-- [ ] 5.7 Report replay rows with unobserved typenames as bounded partial projections without retry loops.
-- [ ] 5.8 Preserve hydrated-row coverage using the matching concrete fragment selection.
+- [x] 5.1 Replace the abstract-row rejection with a typename-only list or window probe.
+- [x] 5.2 Collect distinct observed advertised concrete types under the configured bound.
+- [x] 5.3 Build and execute one concrete-fragment replay with identical collection arguments.
+- [x] 5.4 Include requested columns only where each concrete type advertises the member wrapper.
+- [x] 5.5 Publish only the replay result while retaining probe and replay operation evidence.
+- [x] 5.6 Preserve lazy activation, caching, window state, ordering, cancellation, stale generations, and route disposal.
+- [x] 5.7 Report replay rows with unobserved typenames as bounded partial projections without retry loops.
+- [x] 5.8 Preserve hydrated-row coverage using the matching concrete fragment selection.
## 6. Add focused foundation coverage
-- [ ] 6.1 Add inline-fragment rendering, ordering, validation, merge, and difference tests.
-- [ ] 6.2 Add small-union direct selection and broad-union typename fallback tests.
-- [ ] 6.3 Add abstract legacy-list and bounded-window probe and replay tests.
-- [ ] 6.4 Add mixed concrete row, missing column, unadvertised typename, and changed replay type tests.
-- [ ] 6.5 Add cancellation, stale response, cache, and inactive collection tests for two-stage reads.
-- [ ] 6.6 Add single-shot mutating abstract action-result coverage.
+- [x] 6.1 Add inline-fragment rendering, ordering, validation, merge, and difference tests.
+- [x] 6.2 Add small-union direct selection and broad-union typename fallback tests.
+- [x] 6.3 Add abstract legacy-list and bounded-window probe and replay tests.
+- [x] 6.4 Add mixed concrete row, missing column, unadvertised typename, and changed replay type tests.
+- [x] 6.5 Add cancellation, stale response, cache, and inactive collection tests for two-stage reads.
+- [x] 6.6 Add single-shot mutating abstract action-result coverage.
## 7. Qualify against the pinned Reference Application
-- [ ] 7.1 Add or refine deterministic target-catalogue entries for declared and runtime polymorphic collections.
-- [ ] 7.2 Add integration assertions for union possible types, invalid direct selection, probe typenames, and valid observed fragments.
-- [ ] 7.3 Convert polymorphic browser assertions to successful concrete row identity and value behavior where supported.
-- [ ] 7.4 Preserve concrete versionless rows, configured collections, partial errors, lazy tabs, stale windows, and route replacement.
-- [ ] 7.5 Preserve the explicit opaque composite `invalid-route` assertion.
-- [ ] 7.6 Update capability inventory classifications only where executable evidence changes.
-- [ ] 7.7 Verify clean and incremental inventory generation remain byte-identical.
+- [x] 7.1 Add or refine deterministic target-catalogue entries for declared and runtime polymorphic collections.
+- [x] 7.2 Add integration assertions for merged union membership, invalid direct selection, concrete type-of rows, and the raw-list schema/runtime mismatch.
+- [x] 7.3 Convert declared type-of browser assertions to successful concrete rows and retain the incompatible raw-list union as a bounded local error.
+- [x] 7.4 Preserve concrete versionless rows, configured collections, partial errors, lazy tabs, stale windows, and route replacement.
+- [x] 7.5 Preserve the explicit opaque composite `invalid-route` assertion.
+- [x] 7.6 Update capability inventory classifications only where executable evidence changes.
+- [x] 7.7 Verify clean and incremental inventory generation remain byte-identical.
## 8. Document compatibility and isolation
-- [ ] 8.1 Document fragment selection grammar, bounds, probe/replay behavior, and non-repeatable outcome policy.
-- [ ] 8.2 Record representative introspection and operation evidence with reproducible commands.
-- [ ] 8.3 Verify no public GraphQL, Causeway element, event, route, HTMX, Vaadin, dependency, CSP, or asset-policy contract changes.
+- [x] 8.1 Document fragment selection grammar, bounds, probe/replay behavior, and non-repeatable outcome policy.
+- [x] 8.2 Record representative introspection and operation evidence with reproducible commands.
+- [x] 8.3 Verify no public GraphQL, Causeway element, event, route, HTMX, Vaadin, dependency, CSP, or asset-policy contract changes.
## 9. Run final qualification gates
-- [ ] 9.1 Run the complete foundation Node suite and web-component foundation and HTMX Maven tests.
-- [ ] 9.2 Run relevant GraphQL model and integration tests.
-- [ ] 9.3 Run the full Petclinic integration and Playwright suites.
-- [ ] 9.4 Run the Reference Application clean package, integration, capability inventory, and Playwright suites.
-- [ ] 9.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
-- [ ] 9.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
+- [x] 9.1 Run the complete foundation Node suite and web-component foundation and HTMX Maven tests.
+- [x] 9.2 Run relevant GraphQL model and integration tests.
+- [x] 9.3 Run the full Petclinic integration and Playwright suites.
+- [x] 9.4 Run the Reference Application clean package, integration, capability inventory, and Playwright suites.
+- [x] 9.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
+- [x] 9.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
diff --git a/openspec/planned-changes/web-component-viewer/README.md b/openspec/planned-changes/web-component-viewer/README.md
index c5bdce7d7db..9bb43beab38 100644
--- a/openspec/planned-changes/web-component-viewer/README.md
+++ b/openspec/planned-changes/web-component-viewer/README.md
@@ -6,7 +6,7 @@ The foundation, domain-component, rich GraphQL correctness, value-semantics, col
The Reference Application regression suite and input-value hardening changes are archived.
The action-dispatch correctness change is archived, completing the remaining Priority 0 correction identified by that broad capability inventory.
The versionless-identity and preparation correction is archived.
-The next change should be a focused union-projection correction, followed by opaque-route handling before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
+The current active change is `fix-webcomponent-union-projection-correctness`, followed by opaque-route handling before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
The older Vue, Svelte, metadata, diagnostics, performance-analysis, catalogue, and designer drafts remain queued behind that higher-priority qualification and default-adoption work.
Complete child directories contain `.openspec.yaml`, `proposal.md`, `design.md`, `tasks.md`, and delta specifications and can be promoted verbatim after review.
diff --git a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
index 14a79b20fc0..828d5dd7918 100644
--- a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
+++ b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
@@ -8,7 +8,7 @@ The repository permits one active OpenSpec change at a time.
The Reference Application suite and input-value hardening are archived.
The archived `fix-webcomponent-action-dispatch-correctness` change completed the remaining Priority 0 correctness tranche identified by the pinned regression corpus.
The archived `fix-webcomponent-versionless-identity-preparation` change isolates concrete versionless identity.
-The next change should correct union projection before the separate opaque-route correction.
+The active `fix-webcomponent-union-projection-correctness` change precedes the separate opaque-route correction.
Proposal-only drafts must be refined against checked-in capability evidence before promotion.
| Order | Proposal | Purpose | Promotion gate |
@@ -16,7 +16,7 @@ Proposal-only drafts must be refined against checked-in capability evidence befo
| 1 | `add-referenceapp-webcomponent-regression-suite` *(archived)* | Copy the pinned broad corpus, establish deterministic inventory, and expose real gaps. | Completed with reviewed classifications. |
| 2 | `harden-webcomponent-input-value-semantics` *(archived)* | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Completed against stable Reference Application fixtures. |
| 3 | `fix-webcomponent-action-dispatch-correctness` *(archived)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Completed with successful typed Reference Application interactions and unchanged public operations. |
-| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, then focused union-projection and opaque-route changes | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
+| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, `fix-webcomponent-union-projection-correctness` *(active)*, then focused opaque-route handling | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
| 5 | `add-paged-graphql-reference-autocomplete` | Add honest server-side reference windows for large datasets. | Public GraphQL operation, identity, preparation, and ordering contracts are accepted. |
| 6 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
| 7 | `make-vaadin-default-for-webcomponent-viewer` | Flip the supported selection policy to Vaadin-first and remove pilot status. | All prerequisite suites pass in default and explicit native modes. |
diff --git a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
index 500ebf79e51..3879e743b29 100644
--- a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
+++ b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
@@ -347,16 +347,21 @@ void populatedPagedConfiguredPolymorphicAndRouteReplacedCollectionsRemainVisible
.isEqualTo(pageRows);
assertThat(waitForCollectionOutcome("moreChildren")).isEqualTo("ready");
+ openObject("demo.ActionChoicesFromPage", invokeViewModel(
+ "demo_ActionMenu", "choicesFrom", "rich__demo_ActionChoicesFromPage"));
+ assertThat(waitForCollectionOutcome("objects")).isEqualTo("ready");
+ final Locator polymorphicObjects = page.locator("causeway-collection[member='objects']");
+ assertThat(polymorphicObjects.locator("causeway-object-link").count()).isGreaterThan(0);
+ final String polymorphicSelection = (String) polymorphicObjects
+ .evaluate("element => JSON.stringify(element.collectionState.rowSelection)");
+ assertThat(polymorphicSelection).contains("rich__demo_ActionChoicesFromEntity", "_meta");
+
openObject("demo.CollectionTypeOfPage", invokeViewModel(
"demo_CollectionMenu", "typeOf", "rich__demo_CollectionTypeOfPage"));
final String typeOfChildrenState = waitForCollectionOutcome("children");
- assertThat(typeOfChildrenState).isIn("ready", "partial-error", "error");
- if ("ready".equals(typeOfChildrenState)) {
- assertThat(page.locator("causeway-collection[member='children'] causeway-object-link").count())
- .isGreaterThan(0);
- } else {
- assertThat(page.locator("causeway-collection[member='children']").innerText()).isNotBlank();
- }
+ assertThat(typeOfChildrenState).isEqualTo("ready");
+ assertThat(page.locator("causeway-collection[member='children'] causeway-object-link").count())
+ .isGreaterThan(0);
final Locator otherChildren = page.locator("causeway-collection[member='otherChildren']");
assertThat(otherChildren.count()).isEqualTo(1);
assertThat(otherChildren.evaluate("element => element.collectionState.status")).isEqualTo("idle");
@@ -364,12 +369,8 @@ void populatedPagedConfiguredPolymorphicAndRouteReplacedCollectionsRemainVisible
if (panelId != null) {
page.locator("[role=tab][aria-controls='" + panelId + "']").click();
final String otherChildrenState = waitForCollectionOutcome("otherChildren");
- assertThat(otherChildrenState).isIn("ready", "partial-error", "error");
- if ("ready".equals(otherChildrenState)) {
- assertThat(otherChildren.locator("causeway-object-link").count()).isGreaterThan(0);
- } else {
- assertThat(otherChildren.innerText()).isNotBlank();
- }
+ assertThat(otherChildrenState).isEqualTo("error");
+ assertThat(otherChildren.innerText()).containsIgnoringCase("not readable");
}
openShell();
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
index ebc086b22c2..89e5ca5b463 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
@@ -114,7 +114,8 @@ private void assertJourneyTargetsExist(final JsonNode introspection) throws Exce
"property-text", "property-multiline", "property-hidden", "property-disabled",
"property-editing", "property-validation", "property-cancel-stale",
"collection-empty-populated", "collection-paging-columns",
- "collection-polymorphism", "collection-associated-actions", "collection-stale-partial",
+ "collection-polymorphism", "polymorphic-union-valid", "polymorphic-union-unreadable",
+ "collection-associated-actions", "collection-stale-partial",
"boolean-nullable", "numeric-decimal", "numeric-integer", "temporal-local-date",
"temporal-offset-date-time", "temporal-zoned-date-time", "enum",
"reference-autocomplete", "url", "protected-password", "blob", "clob", "custom-value");
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
index 7c619ba7804..c3c9447ab2d 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
@@ -260,6 +260,61 @@ void versionlessViewModelsAdvertiseIdentityAndSupportConcreteCollectionRows() th
assertThat(firstRow.at("/value/get").asText()).isNotBlank();
}
+ @Test
+ void polymorphicCollectionsCompleteUnionMembershipAndAcceptFragments() throws Exception {
+ final JsonNode unionType = graphQL("""
+ { __type(name: "rich__demo_ValueHolder__gqlv_union") {
+ kind
+ possibleTypes { kind name }
+ } }
+ """);
+ assertNoGraphQLErrors(unionType);
+ final JsonNode possibleTypes = unionType.at("/data/__type/possibleTypes");
+ assertThat(possibleTypes.isArray()).isTrue();
+ assertThat(possibleTypes.size()).isEqualTo(28);
+ assertThat(possibleTypes.findValuesAsText("name"))
+ .contains("rich__demo_ActionChoicesFromEntity")
+ .doesNotContain("rich__demo_CollectionTypeOfChildVm");
+ final JsonNode opened = graphQL("""
+ { rich { demo_ActionMenu {
+ choicesFrom { invoke { results { _meta { id logicalTypeName title } } } }
+ } } }
+ """);
+ assertNoGraphQLErrors(opened);
+ final String pageId = opened.at("/data/rich/demo_ActionMenu/choicesFrom/invoke/results/_meta/id").asText();
+ assertThat(pageId).isNotBlank();
+
+ final String target = "demo_ActionChoicesFromPage(object: {id: "
+ + OBJECT_MAPPER.writeValueAsString(pageId) + "})";
+ final JsonNode probe = graphQL("{ rich { " + target
+ + " { objects { get { __typename } } } } }");
+ assertNoGraphQLErrors(probe);
+ assertThat(probe.at("/data/rich/demo_ActionChoicesFromPage/objects/get").findValuesAsText("__typename"))
+ .containsOnly("rich__demo_ActionChoicesFromEntity");
+
+ final JsonNode invalid = graphQL("{ rich { " + target
+ + " { objects { get { _meta { id } } } } } }");
+ assertThat(invalid.at("/errors/0/message").asText()).contains("_meta", "ValueHolder");
+
+ final JsonNode projected = graphQL("""
+ { rich { %s {
+ objects { get {
+ __typename
+ ... on rich__demo_ActionChoicesFromEntity {
+ _meta { id logicalTypeName title }
+ name { get }
+ }
+ } }
+ } } }
+ """.formatted(target));
+ assertNoGraphQLErrors(projected);
+ final JsonNode first = projected.at("/data/rich/demo_ActionChoicesFromPage/objects/get/0");
+ assertThat(first.path("__typename").asText()).isEqualTo("rich__demo_ActionChoicesFromEntity");
+ assertThat(first.at("/_meta/logicalTypeName").asText()).isEqualTo("demo.ActionChoicesFromEntity");
+ assertThat(first.at("/_meta/id").asText()).isNotBlank();
+ assertThat(first.at("/name/get").asText()).isNotBlank();
+ }
+
@Test
void exactDecimalPropertyMutationUsesAdvertisedStringAndRestoresFixture() throws Exception {
final JsonNode open = graphQL("""
diff --git a/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json b/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
index 39fbab1382a..22fc77f122b 100644
--- a/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
+++ b/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
@@ -24,6 +24,8 @@
{"family": "collection-empty-populated", "rootField": "demo_CollectionLayoutPagedPage", "member": "moreChildren"},
{"family": "collection-paging-columns", "rootField": "demo_CollectionLayoutPagedPage", "member": "children"},
{"family": "collection-polymorphism", "rootField": "demo_CollectionTypeOfPage", "member": "children"},
+ {"family": "polymorphic-union-valid", "rootField": "demo_ActionChoicesFromPage", "member": "objects"},
+ {"family": "polymorphic-union-unreadable", "rootField": "demo_CollectionTypeOfPage", "member": "otherChildren"},
{"family": "collection-associated-actions", "rootField": "demo_CollectionTypeOfPage", "member": "otherChildren"},
{"family": "collection-stale-partial", "rootField": "demo_CollectionLayoutPagedPage", "member": "children"},
{"family": "boolean-nullable", "rootField": "demo_WrapperBooleans", "member": "entities"},
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java
index 7b3f7920487..32364dbecf1 100644
--- a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistry.java
@@ -33,6 +33,7 @@
import graphql.schema.GraphQLNamedType;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLType;
+import graphql.schema.GraphQLTypeReference;
import graphql.schema.GraphQLUnionType;
import static graphql.schema.GraphQLEnumType.newEnum;
@@ -160,8 +161,21 @@ void addTypeIfNotAlreadyPresent(final GraphQLInputObjectType typeToAdd) {
public GraphQLUnionType addUnionTypeIfNotAlreadyPresent(final GraphQLUnionType typeToAdd) {
var existing = lookup(typeToAdd.getName(), GraphQLUnionType.class);
if (existing.isPresent()) {
- log.debug("GraphQLUnionType for {} already present", typeToAdd.getName());
- return existing.get();
+ var existingType = existing.get();
+ var mergedType = existingType.transform(builder -> typeToAdd.getTypes().forEach(type -> {
+ if (type instanceof GraphQLObjectType objectType) {
+ builder.possibleType(objectType);
+ } else if (type instanceof GraphQLTypeReference typeReference) {
+ builder.possibleType(typeReference);
+ }
+ }));
+ if (mergedType.getTypes().size() != existingType.getTypes().size()) {
+ graphQLTypes.remove(existingType);
+ graphQLTypes.add(mergedType);
+ log.debug("Merged GraphQLUnionType {} from {} to {} possible types",
+ typeToAdd.getName(), existingType.getTypes().size(), mergedType.getTypes().size());
+ }
+ return mergedType;
}
add(typeToAdd);
return typeToAdd;
diff --git a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/types/TypeMapperDefault.java b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/types/TypeMapperDefault.java
index fdd7a3b07a8..195b998da65 100644
--- a/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/types/TypeMapperDefault.java
+++ b/viewers/graphql/model/src/main/java/org/apache/causeway/viewer/graphql/model/types/TypeMapperDefault.java
@@ -41,7 +41,6 @@
import graphql.schema.GraphQLList;
import graphql.schema.GraphQLOutputType;
import graphql.schema.GraphQLTypeReference;
-import graphql.schema.GraphQLUnionType;
import jakarta.inject.Inject;
import jakarta.inject.Provider;
import lombok.RequiredArgsConstructor;
@@ -176,11 +175,6 @@ private GraphQLOutputType polymorphicOutputTypeFor(
}
var unionTypeName = TypeNames.polymorphicTypeNameFor(declaredType, schemaType);
- var existing = context.graphQLTypeRegistry.lookup(unionTypeName, GraphQLUnionType.class);
- if (existing.isPresent()) {
- return existing.get();
- }
-
var unionBuilder = newUnionType()
.name(unionTypeName)
.description("Concrete rich object types assignable to " + declaredType.logicalTypeName());
@@ -198,17 +192,21 @@ private GraphQLOutputType polymorphicOutputTypeFor(
if (pojo instanceof ManagedObject managedObject) {
pojo = managedObject.getPojo();
}
- if (pojo == null || !declaredType.isAssignableFrom(pojo.getClass())) {
+ if (pojo == null) {
return null;
}
var runtimeSpecification = context.specificationLoader.loadSpecification(pojo.getClass());
if (runtimeSpecification == null) {
return null;
}
- return environment.getSchema().getObjectType(
- TypeNames.objectTypeNameFor(runtimeSpecification, schemaType));
+ var runtimeTypeName = TypeNames.objectTypeNameFor(runtimeSpecification, schemaType);
+ var isAdvertised = unionType.getTypes().stream()
+ .anyMatch(possibleType -> possibleType.getName().equals(runtimeTypeName));
+ return isAdvertised
+ ? environment.getSchema().getObjectType(runtimeTypeName)
+ : null;
});
- return unionType;
+ return typeRef(unionTypeName);
}
@Override
diff --git a/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java b/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java
new file mode 100644
index 00000000000..25ea4b4e431
--- /dev/null
+++ b/viewers/graphql/model/src/test/java/org/apache/causeway/viewer/graphql/model/registry/GraphQLTypeRegistryUnionTest.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.causeway.viewer.graphql.model.registry;
+
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.Test;
+
+import graphql.schema.GraphQLTypeReference;
+import graphql.schema.GraphQLUnionType;
+
+import static graphql.schema.GraphQLUnionType.newUnionType;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+
+class GraphQLTypeRegistryUnionTest {
+
+ @Test
+ void repeatedUnionRegistrationMergesPossibleTypesByName() {
+ var registry = new GraphQLTypeRegistry(null);
+ var first = union("ValueHolder", "FirstType");
+ var second = union("ValueHolder", "SecondType", "FirstType");
+
+ assertSame(first, registry.addUnionTypeIfNotAlreadyPresent(first));
+ var merged = registry.addUnionTypeIfNotAlreadyPresent(second);
+
+ assertEquals(Set.of("FirstType", "SecondType"), names(merged));
+ assertSame(merged, registry.lookup("ValueHolder", GraphQLUnionType.class).orElseThrow());
+ assertEquals(1, registry.getGraphQLTypes().size());
+ }
+
+ private static GraphQLUnionType union(final String name, final String... possibleTypes) {
+ var builder = newUnionType().name(name);
+ for (var possibleType : possibleTypes) {
+ builder.possibleType(GraphQLTypeReference.typeRef(possibleType));
+ }
+ return builder.build();
+ }
+
+ private static Set<String> names(final GraphQLUnionType unionType) {
+ return unionType.getTypes().stream()
+ .map(type -> type.getName())
+ .collect(Collectors.toSet());
+ }
+}
diff --git a/viewers/webcomponents/foundation/USAGE.adoc b/viewers/webcomponents/foundation/USAGE.adoc
index d0b8944706e..e92ceb2e4a3 100644
--- a/viewers/webcomponents/foundation/USAGE.adoc
+++ b/viewers/webcomponents/foundation/USAGE.adoc
@@ -101,6 +101,8 @@ One browser client serializes these initial targeted discovery requests so objec
Descriptions include member kind, advertised wrapper fields, output type reference, named type, innermost type kind, collection element type, concrete object metadata, and reachable value-shape fields.
Concrete property values, preparation values, action results, and rows use one metadata-selection policy that requests the advertised subset of `id`, `logicalTypeName`, `title`, and `version`.
+Interface and union descriptions retain their advertised possible types.
+The internal `__fragments` selection node renders only validated sorted inline fragments and is never exposed as a public component API.
Descriptions are cached by generated type name within one `<causeway-graphql-client>` instance.
Several object contexts under the same provider therefore share schema descriptions while retaining independent object snapshots.
The cache is memory-only and is not shared across browser sessions or users.
@@ -426,7 +428,10 @@ Secondary operations are cached by member and structural row selection, support
Without columns, concrete object-valued rows request the advertised `_meta` subset and render object links when `id` and `logicalTypeName` are both present.
`title` and `version` remain optional, so versionless view-model rows stay hydratable without an invented concurrency token.
Declared columns merge their property wrappers into the secondary operation and use the configured value renderer for returned values.
-Abstract rows that require concrete GraphQL fragments fail locally before a speculative operation and remain assigned to the separate union-projection correction.
+An abstract row type with at most eight advertised concrete types uses direct validated fragments.
+A broader abstract collection performs one typename-only probe, describes at most sixteen observed advertised concrete types, and replays the identical side-effect-free list or window read once with concrete fragments.
+Only the replay result is published, and an unobserved replay type remains a bounded partial projection without another retry.
+Mutating interactions never use probe and replay; an abstract result that exceeds the direct bound remains a successful typename-only result.
Hidden cells emit no content, disabled cells expose their reasons, and row or member errors remain local while successful cells continue to render.
An empty result renders the live `No items` status.
diff --git a/viewers/webcomponents/foundation/src/graphql-client.mjs b/viewers/webcomponents/foundation/src/graphql-client.mjs
index 848d7ecab55..528c91698e6 100644
--- a/viewers/webcomponents/foundation/src/graphql-client.mjs
+++ b/viewers/webcomponents/foundation/src/graphql-client.mjs
@@ -569,12 +569,13 @@ function referencedInteractionTypeNames(typeDescription, generatedTypeName, sche
const kind = innermostType(typeRef)?.kind;
const choiceValue = ['choices', 'default', 'autoComplete'].includes(fieldName)
&& ['OBJECT', 'INTERFACE', 'UNION'].includes(kind);
- const concreteObjectValue = ['get', 'rows'].includes(fieldName) && kind === 'OBJECT';
+ const objectValue = ['get', 'rows'].includes(fieldName)
+ && ['OBJECT', 'INTERFACE', 'UNION'].includes(kind);
const objectMetadata = fieldName === '_meta' && kind === 'OBJECT';
if (typeName && (schemaNames.isReachableSupportType(generatedTypeName, typeName)
|| kind === 'ENUM' && typeName.startsWith('rich__')
|| choiceValue
- || concreteObjectValue
+ || objectValue
|| objectMetadata)) {
result.add(typeName);
}
diff --git a/viewers/webcomponents/foundation/src/interaction-operations.mjs b/viewers/webcomponents/foundation/src/interaction-operations.mjs
index eb210c5115a..3d1f63d8e1b 100644
--- a/viewers/webcomponents/foundation/src/interaction-operations.mjs
+++ b/viewers/webcomponents/foundation/src/interaction-operations.mjs
@@ -19,6 +19,9 @@
import {assertGraphQLName} from './schema-names.mjs';
import {fieldsByName, namedType} from './introspection.mjs';
+import {INLINE_FRAGMENTS} from './selection.mjs';
+
+export const MAX_DIRECT_FRAGMENT_TYPES = 8;
export function buildDescribeOperationRootsOperation() {
return Object.freeze({
@@ -208,6 +211,23 @@ export function resultSelectionForType(typeRef, types) {
if (!typeDescription) {
return {__typename: true};
}
+ if (['INTERFACE', 'UNION'].includes(kind)) {
+ const possibleTypes = [...(typeDescription.possibleTypes ?? [])]
+ .map(candidate => candidate.name)
+ .sort();
+ if (possibleTypes.length === 0
+ || possibleTypes.length > MAX_DIRECT_FRAGMENT_TYPES
+ || possibleTypes.some(typeName => !types.has(typeName))) {
+ return {__typename: true};
+ }
+ return {
+ __typename: true,
+ [INLINE_FRAGMENTS]: Object.fromEntries(possibleTypes.map(typeName => {
+ const concreteRef = {kind: 'OBJECT', name: typeName, ofType: null};
+ return [typeName, metadataSelectionForType(concreteRef, types) ?? {__typename: true}];
+ }))
+ };
+ }
const metadataSelection = metadataSelectionForType(typeRef, types);
if (metadataSelection) {
return metadataSelection;
@@ -235,6 +255,18 @@ function renderExecutableSelection({
const fields = fieldsByName(typeDescription);
const lines = [];
for (const fieldName of Object.keys(selection).sort()) {
+ if (fieldName === INLINE_FRAGMENTS) {
+ lines.push(renderExecutableFragments({
+ fragments: selection[fieldName],
+ typeDescription,
+ types,
+ variables,
+ declarations,
+ variablePrefix,
+ indentation
+ }));
+ continue;
+ }
assertGraphQLName(fieldName, 'selection field');
if (fieldName === '__typename' && selection[fieldName] === true) {
lines.push(`${indentation}__typename`);
@@ -275,6 +307,44 @@ function renderExecutableSelection({
return lines.join('\n');
}
+function renderExecutableFragments({
+ fragments,
+ typeDescription,
+ types,
+ variables,
+ declarations,
+ variablePrefix,
+ indentation
+}) {
+ if (!['INTERFACE', 'UNION'].includes(typeDescription.kind)) {
+ throw new Error(`Inline fragments are unavailable on GraphQL type '${typeDescription.name}'.`);
+ }
+ const advertised = new Set((typeDescription.possibleTypes ?? []).map(candidate => candidate.name));
+ const lines = [];
+ for (const typeName of Object.keys(fragments ?? {}).sort()) {
+ assertGraphQLName(typeName, 'inline fragment type');
+ if (!advertised.has(typeName)) {
+ throw new Error(`Type '${typeName}' is not advertised by GraphQL type '${typeDescription.name}'.`);
+ }
+ const concreteType = types.get(typeName) ?? null;
+ if (!concreteType || concreteType.kind !== 'OBJECT') {
+ throw new Error(`Inline fragment type '${typeName}' is not a described GraphQL object.`);
+ }
+ lines.push(`${indentation}... on ${typeName} {`);
+ lines.push(renderExecutableSelection({
+ selection: fragments[typeName],
+ typeDescription: concreteType,
+ types,
+ variables,
+ declarations,
+ variablePrefix: `${variablePrefix}${declarations.length}`,
+ indentation: `${indentation} `
+ }));
+ lines.push(`${indentation}}`);
+ }
+ return lines.join('\n');
+}
+
function normalizeCommandNode(value) {
if (value === true) {
return {args: {}, select: true};
diff --git a/viewers/webcomponents/foundation/src/object-context-controller.mjs b/viewers/webcomponents/foundation/src/object-context-controller.mjs
index cdfe071f560..de520fec19d 100644
--- a/viewers/webcomponents/foundation/src/object-context-controller.mjs
+++ b/viewers/webcomponents/foundation/src/object-context-controller.mjs
@@ -30,9 +30,18 @@ import {fieldsByName, namedType} from './introspection.mjs';
import {
argumentsFromValues,
commandSelection,
+ MAX_DIRECT_FRAGMENT_TYPES,
+ metadataSelectionForType,
resultSelectionForType
} from './interaction-operations.mjs';
-import {deepMerge, differenceSelection, isSelectionEmpty, mergeSelections} from './selection.mjs';
+import {
+ deepMerge,
+ differenceSelection,
+ INLINE_FRAGMENTS,
+ isSelectionEmpty,
+ mergeSelections,
+ selectionForRuntimeType
+} from './selection.mjs';
import {fetchStructuralResource, StructuralResourceError} from './structural-resource.mjs';
import {InteractionResultKind, InteractionStatus, ObjectContextStatus, RequirementStatus} from './types.mjs';
@@ -523,18 +532,15 @@ export class ObjectContextController extends EventTarget {
if (!descriptor || descriptor.kind !== 'collection' || (!usesWindow && !descriptor.fields.has('get'))) {
throw new Error(`Collection '${member}' is not readable on '${description.logicalTypeName}'.`);
}
- if (['INTERFACE', 'UNION'].includes(descriptor.value?.typeKind)) {
- throw new Error(`Collection '${member}' uses an abstract row type that requires concrete fragment projection.`);
- }
+ const abstractRows = ['INTERFACE', 'UNION'].includes(descriptor.value?.typeKind);
const requestedOffset = usesWindow ? integerAtLeast(offset, 0, 'Collection window offset') : 0;
const requestedSize = usesWindow
? integerAtLeast(size ?? descriptor.window.sizeDefault, 1, 'Collection window size')
: null;
- const rowSelection = collectionRowSelection(descriptor, columns, description.types);
- const selection = usesWindow
- ? null
- : {[member]: {get: rowSelection}};
- const cacheKey = JSON.stringify({member, rowSelection, offset: requestedOffset, size: requestedSize, usesWindow});
+ let rowSelection = abstractRows
+ ? {__typename: true}
+ : collectionRowSelection(descriptor, columns, description.types);
+ const cacheKey = JSON.stringify({member, columns, offset: requestedOffset, size: requestedSize, usesWindow});
if (!force && this.secondaryCache.has(cacheKey)) {
const cached = this.secondaryCache.get(cacheKey);
if (!cached.abortController.signal.aborted) {
@@ -559,12 +565,12 @@ export class ObjectContextController extends EventTarget {
this.secondaryRequests.set(requestKey, {abortController, generation: requestGeneration});
}
- const readPromise = usesWindow
+ const readCollection = selection => usesWindow
? this.client.readCollectionWindow({
description,
identity: this.identity,
member,
- rowSelection,
+ rowSelection: selection,
offset: requestedOffset,
size: requestedSize,
signal: abortController.signal
@@ -572,10 +578,57 @@ export class ObjectContextController extends EventTarget {
: this.client.readObject({
description,
identity: this.identity,
- selection,
+ selection: {[member]: {get: selection}},
+ signal: abortController.signal
+ });
+ const readPromise = (async () => {
+ const advertisedTypeNames = [...(descriptor.value?.typeDescription?.possibleTypes ?? [])]
+ .map(candidate => candidate.name)
+ .sort();
+ const directTypeNames = abstractRows
+ && advertisedTypeNames.length > 0
+ && advertisedTypeNames.length <= MAX_DIRECT_FRAGMENT_TYPES
+ ? advertisedTypeNames
+ : null;
+ if (directTypeNames) {
+ rowSelection = await polymorphicCollectionRowSelection({
+ client: this.client,
+ description,
+ descriptor,
+ columns,
+ observedTypeNames: directTypeNames,
signal: abortController.signal
});
- const promise = readPromise.then(async result => {
+ }
+ let result = await readCollection(rowSelection);
+ let probeOperation = null;
+ let projectedTypeNames = directTypeNames ? new Set(directTypeNames) : null;
+ if (abstractRows && !directTypeNames) {
+ const probeData = result.data?.[member] ?? null;
+ const probeRows = usesWindow ? probeData?.window?.rows : probeData?.get;
+ const observedTypeNames = [...new Set((probeRows ?? [])
+ .map(row => row?.__typename)
+ .filter(Boolean))].sort();
+ if (observedTypeNames.length > 0) {
+ if (requestKey != null && requestGeneration !== this.secondaryRequests.get(requestKey)?.generation) {
+ throw obsoleteRequestError();
+ }
+ rowSelection = await polymorphicCollectionRowSelection({
+ client: this.client,
+ description,
+ descriptor,
+ columns,
+ observedTypeNames,
+ signal: abortController.signal
+ });
+ probeOperation = result.operation;
+ projectedTypeNames = new Set(observedTypeNames);
+ result = await readCollection(rowSelection);
+ }
+ }
+ return {result, probeOperation, projectedTypeNames};
+ })();
+ const promise = readPromise.then(async ({result, probeOperation, projectedTypeNames}) => {
if (requestKey != null && requestGeneration !== this.secondaryRequests.get(requestKey)?.generation) {
throw obsoleteRequestError();
}
@@ -587,6 +640,13 @@ export class ObjectContextController extends EventTarget {
const firstObjectRow = rows.find?.(row => row?._meta?.logicalTypeName);
let rowDescription = null;
let errors = result.errors;
+ if (projectedTypeNames) {
+ const unprojected = rows.filter(row => row?.__typename && !projectedTypeNames.has(row.__typename));
+ if (unprojected.length > 0) {
+ errors = Object.freeze([...errors, asGraphQLError(new Error(
+ 'The collection changed to an unprojected concrete type after its bounded typename probe.'))]);
+ }
+ }
if (firstObjectRow) {
try {
rowDescription = await this.client.describeObject(firstObjectRow._meta.logicalTypeName);
@@ -605,7 +665,8 @@ export class ObjectContextController extends EventTarget {
errors,
rowDescription,
rowSelection,
- selection,
+ selection: usesWindow ? null : {[member]: {get: rowSelection}},
+ probeOperation,
operation: result.operation
});
}).finally(() => {
@@ -634,7 +695,7 @@ export class ObjectContextController extends EventTarget {
client: this.client,
logicalTypeName: metadata.logicalTypeName,
objectId: metadata.id,
- hydration: {data: row, selection: rowSelection},
+ hydration: {data: row, selection: selectionForRuntimeType(rowSelection, row.__typename)},
fetchImpl: this.fetchImpl
});
}
@@ -1153,6 +1214,102 @@ function obsoleteRequestError() {
return error;
}
+const MAX_OBSERVED_POLYMORPHIC_TYPES = 16;
+
+async function polymorphicCollectionRowSelection({
+ client,
+ description,
+ descriptor,
+ columns,
+ observedTypeNames,
+ signal
+}) {
+ if (observedTypeNames.length > MAX_OBSERVED_POLYMORPHIC_TYPES) {
+ throw new Error(`Collection row projection exceeds the ${MAX_OBSERVED_POLYMORPHIC_TYPES}-type bound.`);
+ }
+ const abstractType = descriptor.value?.typeDescription ?? null;
+ const advertised = new Set(abstractType?.possibleTypes?.map(candidate => candidate.name) ?? []);
+ for (const typeName of observedTypeNames) {
+ if (!advertised.has(typeName)) {
+ throw new Error(`Type '${typeName}' is not advertised by abstract row type '${abstractType?.name ?? 'unknown'}'.`);
+ }
+ }
+
+ await describeInto(client, description.types, observedTypeNames, signal);
+ const supportTypeNames = new Set();
+ for (const typeName of observedTypeNames) {
+ const concreteType = description.types.get(typeName);
+ const concreteFields = fieldsByName(concreteType);
+ for (const fieldName of ['_meta', ...columns.map(column => typeof column === 'string' ? column : column?.member)]) {
+ const field = fieldName ? concreteFields.get(fieldName) : null;
+ if (field) {
+ supportTypeNames.add(namedType(field.type));
+ }
+ }
+ }
+ await describeInto(client, description.types, [...supportTypeNames].filter(Boolean), signal);
+
+ const nestedTypeNames = new Set();
+ for (const supportTypeName of supportTypeNames) {
+ const supportType = description.types.get(supportTypeName);
+ for (const field of supportType?.fields ?? []) {
+ if (field.name === 'get' && ['OBJECT', 'INTERFACE', 'UNION'].includes(innermostType(field.type)?.kind)) {
+ nestedTypeNames.add(namedType(field.type));
+ }
+ }
+ }
+ await describeInto(client, description.types, [...nestedTypeNames].filter(Boolean), signal);
+ const nestedMetadataTypeNames = [...nestedTypeNames]
+ .map(typeName => fieldsByName(description.types.get(typeName)).get('_meta'))
+ .filter(Boolean)
+ .map(field => namedType(field.type));
+ await describeInto(client, description.types, nestedMetadataTypeNames, signal);
+
+ const fragments = Object.fromEntries(observedTypeNames.map(typeName => {
+ const concreteType = description.types.get(typeName);
+ const concreteFields = fieldsByName(concreteType);
+ const concreteRef = {kind: 'OBJECT', name: typeName, ofType: null};
+ const fragment = {...(metadataSelectionForType(concreteRef, description.types) ?? {__typename: true})};
+ for (const column of columns) {
+ const member = typeof column === 'string' ? column : column?.member;
+ const memberField = member ? concreteFields.get(member) : null;
+ const wrapper = memberField ? description.types.get(namedType(memberField.type)) ?? null : null;
+ if (!member || !wrapper) {
+ continue;
+ }
+ const wrapperFields = fieldsByName(wrapper);
+ const memberSelection = Object.fromEntries(
+ ['hidden', 'disabled', 'datatype']
+ .filter(fieldName => wrapperFields.has(fieldName))
+ .map(fieldName => [fieldName, true]));
+ const getField = wrapperFields.get('get');
+ if (getField) {
+ memberSelection.get = resultSelectionForType(getField.type, description.types) ?? true;
+ }
+ if (Object.keys(memberSelection).length > 0) {
+ fragment[member] = memberSelection;
+ }
+ }
+ return [typeName, fragment];
+ }));
+ return {__typename: true, [INLINE_FRAGMENTS]: fragments};
+}
+
+async function describeInto(client, types, typeNames, signal) {
+ const missing = [...new Set(typeNames)].filter(typeName => typeName && !types.has(typeName));
+ if (missing.length === 0) {
+ return;
+ }
+ const described = await client.describeTypes(missing, {signal});
+ for (const typeName of missing) {
+ const typeDescription = described.get(typeName) ?? null;
+ if (!typeDescription) {
+ throw new Error(`GraphQL type '${typeName}' required by a polymorphic projection is unavailable.`);
+ }
+ types.set(typeName, typeDescription);
+ }
+}
+
function collectionRowSelection(descriptor, columns, types) {
const value = descriptor.value;
const elementTypeRef = value?.elementTypeRef ?? value?.typeRef ?? null;
diff --git a/viewers/webcomponents/foundation/src/selection.mjs b/viewers/webcomponents/foundation/src/selection.mjs
index 1481ac8f239..23adbca5d6b 100644
--- a/viewers/webcomponents/foundation/src/selection.mjs
+++ b/viewers/webcomponents/foundation/src/selection.mjs
@@ -17,8 +17,11 @@
* under the License.
*/
+import {fieldsByName, namedType} from './introspection.mjs';
import {assertGraphQLName} from './schema-names.mjs';
+export const INLINE_FRAGMENTS = '__fragments';
+
export function mergeSelections(...selections) {
const result = {};
for (const selection of selections) {
@@ -66,29 +69,85 @@ export function isSelectionEmpty(selection) {
return Object.keys(selection ?? {}).length === 0;
}
-export function renderSelectionSet(selection, indentation = ' ') {
+export function renderSelectionSet(selection, indentation = ' ', {
+ typeDescription = null,
+ types = null,
+ strict = false
+} = {}) {
const lines = [];
+ const fields = fieldsByName(typeDescription);
for (const field of Object.keys(selection).sort()) {
+ if (field === INLINE_FRAGMENTS) {
+ lines.push(...renderInlineFragments(selection[field], indentation, typeDescription, types));
+ continue;
+ }
assertGraphQLName(field, 'selection field');
const value = selection[field];
+ const fieldDescription = typeDescription ? fields.get(field) : null;
+ if (strict && typeDescription && field !== '__typename' && !fieldDescription) {
+ throw new Error(`Field '${field}' is unavailable on GraphQL type '${typeDescription.name}'.`);
+ }
if (value === true) {
lines.push(`${indentation}${field}`);
} else {
+ const childType = fieldDescription && types ? types.get(namedType(fieldDescription.type)) ?? null : null;
+ if (strict && fieldDescription && !childType) {
+ throw new Error(`Selection for '${typeDescription.name}.${field}' requires an undescribed GraphQL type '${namedType(fieldDescription.type)}'.`);
+ }
lines.push(`${indentation}${field} {`);
- lines.push(renderSelectionSet(value, `${indentation} `));
+ lines.push(renderSelectionSet(value, `${indentation} `, {typeDescription: childType, types, strict}));
lines.push(`${indentation}}`);
}
}
return lines.join('\n');
}
+function renderInlineFragments(fragments, indentation, typeDescription, types) {
+ if (!typeDescription || !['INTERFACE', 'UNION'].includes(typeDescription.kind) || !types) {
+ throw new Error('Inline fragments require a described GraphQL interface or union.');
+ }
+ const advertised = new Set((typeDescription.possibleTypes ?? []).map(candidate => candidate.name));
+ const lines = [];
+ for (const typeName of Object.keys(fragments ?? {}).sort()) {
+ assertGraphQLName(typeName, 'inline fragment type');
+ if (!advertised.has(typeName)) {
+ throw new Error(`Type '${typeName}' is not advertised by GraphQL type '${typeDescription.name}'.`);
+ }
+ const concreteType = types.get(typeName) ?? null;
+ if (!concreteType || concreteType.kind !== 'OBJECT') {
+ throw new Error(`Inline fragment type '${typeName}' is not a described GraphQL object.`);
+ }
+ lines.push(`${indentation}... on ${typeName} {`);
+ lines.push(renderSelectionSet(fragments[typeName], `${indentation} `, {
+ typeDescription: concreteType,
+ types,
+ strict: true
+ }));
+ lines.push(`${indentation}}`);
+ }
+ return lines;
+}
+
+export function selectionForRuntimeType(selection, typeName) {
+ const fragments = selection?.[INLINE_FRAGMENTS] ?? {};
+ const common = Object.fromEntries(
+ Object.entries(selection ?? {}).filter(([field]) => field !== INLINE_FRAGMENTS));
+ return mergeSelections(common, typeName ? fragments[typeName] ?? {} : {});
+}
+
export function buildObjectReadOperation({description, identity, selection, schemaNames}) {
if (isSelectionEmpty(selection)) {
throw new Error('Cannot build a GraphQL object read with an empty selection.');
}
const objectField = assertGraphQLName(description.generatedFieldName, 'object field');
const lookupArgument = assertGraphQLName(schemaNames.lookupArgumentName, 'lookup argument');
- const nestedSelection = renderSelectionSet(selection, schemaNames.richRootField ? ' ' : ' ');
+ const nestedSelection = renderSelectionSet(
+ selection,
+ schemaNames.richRootField ? ' ' : ' ',
+ {
+ typeDescription: description.types?.get(description.generatedTypeName) ?? null,
+ types: description.types ?? null
+ });
const objectRead = schemaNames.richRootField
? ` ${assertGraphQLName(schemaNames.richRootField, 'rich root field')} {\n ${objectField}(${lookupArgument}: $object) {\n${nestedSelection}\n }\n }`
: ` ${objectField}(${lookupArgument}: $object) {\n${nestedSelection}\n }`;
@@ -115,7 +174,12 @@ export function buildCollectionWindowReadOperation({
const collectionField = assertGraphQLName(member, 'collection field');
const lookupArgument = assertGraphQLName(schemaNames.lookupArgumentName, 'lookup argument');
const rowIndentation = schemaNames.richRootField ? ' ' : ' ';
- const renderedRows = renderSelectionSet(rowSelection, rowIndentation);
+ const collection = description.members?.get(member) ?? null;
+ const rowType = collection?.value?.typeDescription ?? null;
+ const renderedRows = renderSelectionSet(
+ rowSelection,
+ rowIndentation,
+ {typeDescription: rowType, types: description.types ?? null});
const windowSelection = `offset\n${rowIndentation.slice(2)}requestedSize\n${rowIndentation.slice(2)}returnedCount\n${rowIndentation.slice(2)}totalCount\n${rowIndentation.slice(2)}maximumSize\n${rowIndentation.slice(2)}hasPrevious\n${rowIndentation.slice(2)}hasNext\n${rowIndentation.slice(2)}ordering\n${rowIndentation.slice(2)}rows {\n${renderedRows}\n${rowIndentation.slice(2)}}`;
const objectRead = schemaNames.richRootField
? ` ${assertGraphQLName(schemaNames.richRootField, 'rich root field')} {\n ${objectField}(${lookupArgument}: $object) {\n ${collectionField} {\n window(offset: $offset, size: $size) {\n ${windowSelection}\n }\n }\n }\n }`
diff --git a/viewers/webcomponents/foundation/test/collection.test.mjs b/viewers/webcomponents/foundation/test/collection.test.mjs
index 62daac967ef..0dd148ecd26 100644
--- a/viewers/webcomponents/foundation/test/collection.test.mjs
+++ b/viewers/webcomponents/foundation/test/collection.test.mjs
@@ -28,6 +28,7 @@ import {
createWindowedRichSchemaTypes,
DEPARTMENT_LOGICAL_TYPE,
DEPARTMENT_OBJECT_FIELD,
+ departmentObjectData,
graphQLObjectResponse,
STAFF_LOGICAL_TYPE,
STAFF_OBJECT_FIELD,
@@ -217,16 +218,22 @@ test('collection secondary reads prefer bounded windows and expose semantic rang
assert.equal(executor.windowCalls.length, 1, 'an identical window should use the secondary cache');
});
-test('abstract collection rows fail locally before a speculative metadata operation', async () => {
+test('small abstract collection selects advertised fragments without a probe', async () => {
const types = createRichSchemaTypes();
+ const unionTypeName = 'rich__university_staff_SmallUnion';
const collectionType = types.get('rich__university_dept_Department__staffMembers__gqlv_collection');
collectionType.fields.find(candidate => candidate.name === 'get').type = {
- kind: 'LIST', name: null, ofType: {kind: 'UNION', name: 'rich__university_staff_StaffUnion', ofType: null}
+ kind: 'LIST', name: null, ofType: {kind: 'UNION', name: unionTypeName, ofType: null}
};
- types.set('rich__university_staff_StaffUnion', {
- kind: 'UNION', name: 'rich__university_staff_StaffUnion', description: null, fields: []
+ types.set(unionTypeName, {
+ kind: 'UNION', name: unionTypeName, description: null, fields: [],
+ possibleTypes: [{kind: 'OBJECT', name: 'rich__university_staff_StaffMember'}]
+ });
+ const staff = {...row(), __typename: 'rich__university_staff_StaffMember'};
+ const executor = createRichSchemaFixtureExecutor({
+ types,
+ readResponses: [graphQLObjectResponse(), collectionResponse([staff])]
});
- const executor = createRichSchemaFixtureExecutor({types, readResponses: [graphQLObjectResponse()]});
const context = new ObjectContextController({
client: new CausewayGraphQLClient({executor}),
logicalTypeName: DEPARTMENT_LOGICAL_TYPE,
@@ -235,10 +242,216 @@ test('abstract collection rows fail locally before a speculative metadata operat
context.registerRequirement({kind: 'collection', member: 'staffMembers'});
await waitFor(() => context.state.status === 'ready');
- await assert.rejects(
- context.loadCollection({member: 'staffMembers'}),
- /abstract row type that requires concrete fragment projection/);
- assert.equal(executor.readCalls.length, 1);
+ const loaded = await context.loadCollection({member: 'staffMembers'});
+
+ assert.equal(executor.readCalls.length, 2);
+ assert.equal(loaded.probeOperation, null);
+ assert.match(loaded.operation.document, /\.\.\. on rich__university_staff_StaffMember/);
+ assert.equal(loaded.rows[0]._meta.id, 'staff-1');
+});
+
+test('abstract collection rows probe typenames then replay concrete fragments', async () => {
+ const types = createRichSchemaTypes();
+ const unionTypeName = 'rich__university_staff_StaffUnion';
+ const collectionType = types.get('rich__university_dept_Department__staffMembers__gqlv_collection');
+ collectionType.fields.find(candidate => candidate.name === 'get').type = {
+ kind: 'LIST', name: null, ofType: {kind: 'UNION', name: unionTypeName, ofType: null}
+ };
+ types.set(unionTypeName, {
+ kind: 'UNION', name: unionTypeName, description: null, fields: [],
+ possibleTypes: [
+ {kind: 'OBJECT', name: 'rich__university_dept_Department'},
+ {kind: 'OBJECT', name: 'rich__university_staff_StaffMember'},
+ ...Array.from({length: 7}, (_, index) => ({kind: 'OBJECT', name: `rich__university_staff_Unobserved${index}`}))
+ ]
+ });
+ const staff = {...row(), __typename: 'rich__university_staff_StaffMember'};
+ const department = {...departmentObjectData(), __typename: 'rich__university_dept_Department'};
+ const executor = createRichSchemaFixtureExecutor({
+ types,
+ readResponses: [
+ graphQLObjectResponse(),
+ collectionResponse([{__typename: staff.__typename}, {__typename: department.__typename}]),
+ collectionResponse([staff, department])
+ ]
+ });
+ const context = new ObjectContextController({
+ client: new CausewayGraphQLClient({executor}),
+ logicalTypeName: DEPARTMENT_LOGICAL_TYPE,
+ objectId: '42'
+ });
+ context.registerRequirement({kind: 'collection', member: 'staffMembers'});
+ await waitFor(() => context.state.status === 'ready');
+
+ const loaded = await context.loadCollection({member: 'staffMembers', columns: ['name', 'status']});
+
+ assert.equal(executor.readCalls.length, 3);
+ assert.match(loaded.probeOperation.document, /__typename/);
+ assert.doesNotMatch(loaded.probeOperation.document, /\.\.\. on/);
+ assert.match(loaded.operation.document, /\.\.\. on rich__university_dept_Department/);
+ assert.match(loaded.operation.document, /\.\.\. on rich__university_staff_StaffMember/);
+ assert.match(loaded.operation.document, /_meta/);
+ assert.match(loaded.operation.document, /name\s*\{/);
+ const staffFragment = loaded.operation.document.slice(
+ loaded.operation.document.indexOf('... on rich__university_staff_StaffMember'));
+ assert.doesNotMatch(staffFragment, /status\s*\{/);
+ assert.equal(loaded.rows[0]._meta.id, 'staff-1');
+ assert.equal(loaded.rows[1]._meta.id, '42');
+ const rowContext = context.createHydratedRowContext(loaded.rows[0], loaded.rowSelection);
+ assert.equal(rowContext.identity.id, 'staff-1');
+ rowContext.disconnect();
+});
+
+test('abstract bounded windows probe and replay identical arguments once', async () => {
+ const types = createWindowedRichSchemaTypes();
+ const unionTypeName = 'rich__university_staff_StaffWindowUnion';
+ const unionRef = {kind: 'UNION', name: unionTypeName, ofType: null};
+ types.get('rich__university_dept_Department__staffMembers__gqlv_collection')
+ .fields.find(candidate => candidate.name === 'get').type = {kind: 'LIST', name: null, ofType: unionRef};
+ types.get('rich__university_dept_Department__staffMembers__gqlv_collection_window')
+ .fields.find(candidate => candidate.name === 'rows').type = {kind: 'LIST', name: null, ofType: unionRef};
+ types.set(unionTypeName, {
+ kind: 'UNION', name: unionTypeName, description: null, fields: [],
+ possibleTypes: [
+ {kind: 'OBJECT', name: 'rich__university_staff_StaffMember'},
+ ...Array.from({length: 8}, (_, index) => ({kind: 'OBJECT', name: `rich__university_staff_WindowUnobserved${index}`}))
+ ]
+ });
+ const staff = {...row(), __typename: 'rich__university_staff_StaffMember'};
+ const executor = createRichSchemaFixtureExecutor({
+ types,
+ readResponses: [graphQLObjectResponse()],
+ windowResponses: [
+ collectionWindowResponse({rows: [{__typename: staff.__typename}], offset: 4, requestedSize: 2, totalCount: 5}),
+ collectionWindowResponse({rows: [staff], offset: 4, requestedSize: 2, totalCount: 5})
+ ]
+ });
+ const context = new ObjectContextController({
+ client: new CausewayGraphQLClient({executor}),
+ logicalTypeName: DEPARTMENT_LOGICAL_TYPE,
+ objectId: '42'
+ });
+ context.registerRequirement({kind: 'collection', member: 'staffMembers'});
+ await waitFor(() => context.state.status === 'ready');
+
+ const loaded = await context.loadCollection({member: 'staffMembers', columns: ['name'], offset: 4, size: 2});
+
+ assert.equal(executor.windowCalls.length, 2);
+ assert.deepEqual(executor.windowCalls[0].variables, executor.windowCalls[1].variables);
+ assert.match(executor.windowCalls[0].document, /__typename/);
+ assert.match(executor.windowCalls[1].document, /\.\.\. on rich__university_staff_StaffMember/);
+ assert.equal(loaded.window.offset, 4);
+ assert.equal(loaded.rows[0]._meta.id, 'staff-1');
+});
+
+test('abstract collection reports a replay type not observed by its bounded probe', async () => {
+ const types = createRichSchemaTypes();
+ const unionTypeName = 'rich__university_staff_ChangingUnion';
+ const collectionType = types.get('rich__university_dept_Department__staffMembers__gqlv_collection');
+ collectionType.fields.find(candidate => candidate.name === 'get').type = {
+ kind: 'LIST', name: null, ofType: {kind: 'UNION', name: unionTypeName, ofType: null}
+ };
+ types.set(unionTypeName, {
+ kind: 'UNION', name: unionTypeName, description: null, fields: [],
+ possibleTypes: [
+ {kind: 'OBJECT', name: 'rich__university_dept_Department'},
+ {kind: 'OBJECT', name: 'rich__university_staff_StaffMember'},
+ ...Array.from({length: 7}, (_, index) => ({kind: 'OBJECT', name: `rich__university_staff_Changing${index}`}))
+ ]
+ });
+ const executor = createRichSchemaFixtureExecutor({
+ types,
+ readResponses: [
+ graphQLObjectResponse(),
+ collectionResponse([{__typename: 'rich__university_staff_StaffMember'}]),
+ collectionResponse([{...departmentObjectData(), __typename: 'rich__university_dept_Department'}])
+ ]
+ });
+ const context = new ObjectContextController({
+ client: new CausewayGraphQLClient({executor}),
+ logicalTypeName: DEPARTMENT_LOGICAL_TYPE,
+ objectId: '42'
+ });
+ context.registerRequirement({kind: 'collection', member: 'staffMembers'});
+ await waitFor(() => context.state.status === 'ready');
+
+ const loaded = await context.loadCollection({member: 'staffMembers'});
+
+ assert.equal(executor.readCalls.length, 3);
+ assert.equal(loaded.errors.length, 1);
+ assert.match(loaded.errors[0].message, /unprojected concrete type/);
+});
+
+test('abstract collection rejects a probe typename not advertised by its union', async () => {
+ const types = createRichSchemaTypes();
+ const unionTypeName = 'rich__university_staff_AdvertisedUnion';
+ const collectionType = types.get('rich__university_dept_Department__staffMembers__gqlv_collection');
+ collectionType.fields.find(candidate => candidate.name === 'get').type = {
+ kind: 'LIST', name: null, ofType: {kind: 'UNION', name: unionTypeName, ofType: null}
+ };
+ types.set(unionTypeName, {
+ kind: 'UNION', name: unionTypeName, description: null, fields: [],
+ possibleTypes: [
+ {kind: 'OBJECT', name: 'rich__university_staff_StaffMember'},
+ ...Array.from({length: 8}, (_, index) => ({kind: 'OBJECT', name: `rich__university_staff_Advertised${index}`}))
+ ]
+ });
+ const executor = createRichSchemaFixtureExecutor({
+ types,
+ readResponses: [graphQLObjectResponse(), collectionResponse([{__typename: 'rich__university_staff_Other'}])]
+ });
+ const context = new ObjectContextController({
+ client: new CausewayGraphQLClient({executor}),
+ logicalTypeName: DEPARTMENT_LOGICAL_TYPE,
+ objectId: '42'
+ });
+ context.registerRequirement({kind: 'collection', member: 'staffMembers'});
+ await waitFor(() => context.state.status === 'ready');
+
+ await assert.rejects(context.loadCollection({member: 'staffMembers'}), /not advertised/);
+ assert.equal(executor.readCalls.length, 2);
+});
+
+test('abstract collection aborts an in-flight fragment replay', async () => {
+ const types = createRichSchemaTypes();
+ const unionTypeName = 'rich__university_staff_CancellableUnion';
+ const collectionType = types.get('rich__university_dept_Department__staffMembers__gqlv_collection');
+ collectionType.fields.find(candidate => candidate.name === 'get').type = {
+ kind: 'LIST', name: null, ofType: {kind: 'UNION', name: unionTypeName, ofType: null}
+ };
+ types.set(unionTypeName, {
+ kind: 'UNION', name: unionTypeName, description: null, fields: [],
+ possibleTypes: [
+ {kind: 'OBJECT', name: 'rich__university_staff_StaffMember'},
+ ...Array.from({length: 8}, (_, index) => ({kind: 'OBJECT', name: `rich__university_staff_Cancellable${index}`}))
+ ]
+ });
+ const executor = createRichSchemaFixtureExecutor({
+ types,
+ readResponses: [
+ graphQLObjectResponse(),
+ collectionResponse([{__typename: 'rich__university_staff_StaffMember'}]),
+ request => new Promise((resolve, reject) => request.signal.addEventListener('abort', () => {
+ const error = new Error('Aborted');
+ error.name = 'AbortError';
+ reject(error);
+ }, {once: true}))
+ ]
+ });
+ const context = new ObjectContextController({
+ client: new CausewayGraphQLClient({executor}),
+ logicalTypeName: DEPARTMENT_LOGICAL_TYPE,
+ objectId: '42'
+ });
+ context.registerRequirement({kind: 'collection', member: 'staffMembers'});
+ await waitFor(() => context.state.status === 'ready');
+ const abortController = new AbortController();
+
+ const loading = context.loadCollection({member: 'staffMembers', signal: abortController.signal});
+ await waitFor(() => executor.readCalls.length === 3);
+ abortController.abort();
+
+ await assert.rejects(loading, error => error?.name === 'AbortError');
});
test('collection secondary reads discard responses superseded for the same consumer', async () => {
diff --git a/viewers/webcomponents/foundation/test/identity-selection.test.mjs b/viewers/webcomponents/foundation/test/identity-selection.test.mjs
index 5d3220f78d6..da89cb7ab26 100644
--- a/viewers/webcomponents/foundation/test/identity-selection.test.mjs
+++ b/viewers/webcomponents/foundation/test/identity-selection.test.mjs
@@ -64,6 +64,39 @@ test('partial metadata remains bounded without inventing identity minimums', ()
assert.equal(JSON.stringify(resultSelectionForType(named('Example'), types)).includes('logicalTypeName'), false);
});
+test('bounded described unions select concrete metadata through inline fragments', () => {
+ const union = type('ExampleUnion', [], 'UNION');
+ union.possibleTypes = [{kind: 'OBJECT', name: 'Versioned'}, {kind: 'OBJECT', name: 'Versionless'}];
+ const types = new Map([
+ ['ExampleUnion', union],
+ ['Versioned', type('Versioned', [field('_meta', named('VersionedMeta'))])],
+ ['VersionedMeta', type('VersionedMeta', ['id', 'logicalTypeName', 'version'].map(name => field(name, scalar('String'))))],
+ ['Versionless', type('Versionless', [field('_meta', named('VersionlessMeta'))])],
+ ['VersionlessMeta', type('VersionlessMeta', ['id', 'logicalTypeName', 'title'].map(name => field(name, scalar('String'))))]
+ ]);
+
+ assert.deepEqual(resultSelectionForType(named('ExampleUnion', 'UNION'), types), {
+ __typename: true,
+ __fragments: {
+ Versioned: {_meta: {id: true, logicalTypeName: true, version: true}},
+ Versionless: {_meta: {id: true, logicalTypeName: true, title: true}}
+ }
+ });
+});
+
+test('broad or incompletely described abstract types use typename-only projections', () => {
+ const possibleTypes = Array.from({length: 9}, (_, index) => ({kind: 'OBJECT', name: `Type${index}`}));
+ const broadType = type('BroadUnion', [], 'UNION');
+ broadType.possibleTypes = possibleTypes;
+ const broad = new Map([['BroadUnion', broadType]]);
+ const incompleteType = type('IncompleteUnion', [], 'UNION');
+ incompleteType.possibleTypes = [{kind: 'OBJECT', name: 'Missing'}];
+ const incomplete = new Map([['IncompleteUnion', incompleteType]]);
+
+ assert.deepEqual(resultSelectionForType(named('BroadUnion', 'UNION'), broad), {__typename: true});
+ assert.deepEqual(resultSelectionForType(named('IncompleteUnion', 'UNION'), incomplete), {__typename: true});
+});
+
test('missing descriptions and abstract types use typename-only projections', () => {
const missing = new Map();
const union = new Map([['ExampleUnion', type('ExampleUnion', [], 'UNION')]]);
diff --git a/viewers/webcomponents/foundation/test/interaction-command.test.mjs b/viewers/webcomponents/foundation/test/interaction-command.test.mjs
index 5916755c9d8..8538cff5d5d 100644
--- a/viewers/webcomponents/foundation/test/interaction-command.test.mjs
+++ b/viewers/webcomponents/foundation/test/interaction-command.test.mjs
@@ -222,6 +222,39 @@ test('versionless preparation and autocomplete select only advertised identity m
context.disconnect();
});
+test('broad abstract mutation outcomes execute once and remain typename-only', async () => {
+ const description = fixtureDescription();
+ const unionTypeName = 'rich__example_BroadResultUnion';
+ const unionRef = {kind: 'UNION', name: unionTypeName, ofType: null};
+ description.types.set(unionTypeName, {
+ kind: 'UNION', name: unionTypeName, description: null, fields: [],
+ possibleTypes: Array.from({length: 9}, (_, index) => ({kind: 'OBJECT', name: `Result${index}`}))
+ });
+ const mutationType = graphType('Mutation', [
+ field('example_Object__rename', unionRef, [
+ argument('_target', named(description.generatedInputTypeName)), argument('newName', scalar('String'))
+ ])
+ ]);
+ let executions = 0;
+ const client = {
+ describeObject: async () => description,
+ describeMutation: async () => mutationType,
+ executeMutationInteraction: async request => {
+ executions += 1;
+ assert.deepEqual(request.resultSelection, {__typename: true});
+ return {data: {__typename: 'Result8'}, errors: [], operation: {}};
+ }
+ };
+ const context = new ObjectContextController({client, logicalTypeName: 'example.Object', objectId: '42'});
+
+ const result = await context.invokeAction('rename', {newName: 'Updated'});
+
+ assert.equal(executions, 1);
+ assert.equal(result.status, 'success');
+ assert.deepEqual(result.data.value, {__typename: 'Result8'});
+ context.disconnect();
+});
+
test('transient validation aborts obsolete generations', async () => {
const description = fixtureDescription();
let call = 0;
diff --git a/viewers/webcomponents/foundation/test/interaction.test.mjs b/viewers/webcomponents/foundation/test/interaction.test.mjs
index fe0c30e38ea..6a9532eef41 100644
--- a/viewers/webcomponents/foundation/test/interaction.test.mjs
+++ b/viewers/webcomponents/foundation/test/interaction.test.mjs
@@ -93,6 +93,39 @@ test('interaction operations derive typed variables from introspected fields', (
assert.ok(Object.values(mutation.variables).includes('Updated'));
});
+test('interaction operations render and validate inline fragments', () => {
+ const union = {...type('ActionResultUnion', []), kind: 'UNION', possibleTypes: [{kind: 'OBJECT', name: 'ResultType'}]};
+ const resultType = type('ResultType', [field('_meta', named('ResultMeta'))]);
+ const resultMeta = type('ResultMeta', [field('id', scalar('ID'))]);
+ const mutationType = type('Mutation', [field('run', {kind: 'UNION', name: union.name, ofType: null})]);
+ const types = new Map([
+ ['Mutation', mutationType], [union.name, union], [resultType.name, resultType], [resultMeta.name, resultMeta]
+ ]);
+
+ const operation = buildMutationInteractionOperation({
+ mutationType,
+ fieldName: 'run',
+ args: {},
+ resultSelection: {
+ __typename: true,
+ __fragments: {ResultType: {_meta: {id: true}}}
+ },
+ types,
+ operationName: 'CausewayRun'
+ });
+
+ assert.match(operation.document, /__typename/);
+ assert.match(operation.document, /\.\.\. on ResultType/);
+ assert.throws(() => buildMutationInteractionOperation({
+ mutationType,
+ fieldName: 'run',
+ args: {},
+ resultSelection: {__fragments: {OtherType: {__typename: true}}},
+ types,
+ operationName: 'CausewayInvalidRun'
+ }), /not advertised/);
+});
+
test('editor registry selects standard inputs and supports application overrides', () => {
const text = renderCausewayEditor({
name: 'name', value: 'Classics', choices: [], enumValues: [], inputType: scalar('String'),
diff --git a/viewers/webcomponents/foundation/test/selection.test.mjs b/viewers/webcomponents/foundation/test/selection.test.mjs
index c82a2372c41..af16a28ca63 100644
--- a/viewers/webcomponents/foundation/test/selection.test.mjs
+++ b/viewers/webcomponents/foundation/test/selection.test.mjs
@@ -25,8 +25,11 @@ import {
buildObjectReadOperation,
deepMerge,
differenceSelection,
+ INLINE_FRAGMENTS,
isSelectionEmpty,
- mergeSelections
+ mergeSelections,
+ renderSelectionSet,
+ selectionForRuntimeType
} from '../src/selection.mjs';
const description = {
@@ -51,6 +54,50 @@ test('merges, deduplicates and differences structural selections', () => {
assert.equal(isSelectionEmpty(differenceSelection(merged, merged)), true);
});
+test('merges, differences and resolves deterministic inline fragment selections', () => {
+ const first = {__typename: true, [INLINE_FRAGMENTS]: {TypeB: {_meta: {id: true}}}};
+ const second = {[INLINE_FRAGMENTS]: {TypeA: {_meta: {title: true}}, TypeB: {name: {get: true}}}};
+ const merged = mergeSelections(first, second);
+
+ assert.deepEqual(merged, {
+ __typename: true,
+ [INLINE_FRAGMENTS]: {
+ TypeB: {_meta: {id: true}, name: {get: true}},
+ TypeA: {_meta: {title: true}}
+ }
+ });
+ assert.deepEqual(differenceSelection(merged, first), {
+ [INLINE_FRAGMENTS]: {TypeB: {name: {get: true}}, TypeA: {_meta: {title: true}}}
+ });
+ assert.deepEqual(selectionForRuntimeType(merged, 'TypeB'), {
+ __typename: true, _meta: {id: true}, name: {get: true}
+ });
+});
+
+test('renders sorted validated inline fragments and rejects unadvertised types or fields', () => {
+ const union = {kind: 'UNION', name: 'ResultUnion', fields: [], possibleTypes: [
+ {kind: 'OBJECT', name: 'TypeB'}, {kind: 'OBJECT', name: 'TypeA'}
+ ]};
+ const types = new Map([
+ ['ResultUnion', union],
+ ['TypeA', {kind: 'OBJECT', name: 'TypeA', fields: [{name: 'name', args: [], type: {kind: 'SCALAR', name: 'String'}}]}],
+ ['TypeB', {kind: 'OBJECT', name: 'TypeB', fields: [{name: 'code', args: [], type: {kind: 'SCALAR', name: 'String'}}]}]
+ ]);
+ const rendered = renderSelectionSet({
+ __typename: true,
+ [INLINE_FRAGMENTS]: {TypeB: {code: true}, TypeA: {name: true}}
+ }, ' ', {typeDescription: union, types});
+
+ assert.ok(rendered.indexOf('... on TypeA') < rendered.indexOf('... on TypeB'));
+ assert.match(rendered, /\.\.\. on TypeA \{\n\s+name/);
+ assert.throws(() => renderSelectionSet({
+ [INLINE_FRAGMENTS]: {Other: {name: true}}
+ }, ' ', {typeDescription: union, types}), /not advertised/);
+ assert.throws(() => renderSelectionSet({
+ [INLINE_FRAGMENTS]: {TypeA: {missing: true}}
+ }, ' ', {typeDescription: union, types}), /unavailable/);
+});
+
test('builds a combined-rich object lookup operation', () => {
const operation = buildObjectReadOperation({
description,
(causeway) 05/15: fixes versionless web component identity preparation
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit 7b9a7a2510d114b6696565ebf49b1eb02dcda18b
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 12:23:27 2026 +0100
fixes versionless web component identity preparation
---
.../evidence/REPRODUCING.md | 53 +++++++++++++++
.../evidence/final-gate-results.md | 30 +++++++++
.../evidence/implementation-report.md | 28 ++++++++
.../evidence/metadata-shape-matrix.md | 47 +++++++++++++
.../evidence/production-isolation.md | 11 +++
.../tasks.md | 78 +++++++++++-----------
.../planned-changes/web-component-viewer/README.md | 2 +-
.../web-component-viewer/vaadin-default-roadmap.md | 4 +-
.../htmx/ReferenceAppHtmxPlaywrightTest.java | 56 +++++++++++-----
.../ReferenceAppCapabilityInventory_IntegTest.java | 1 +
.../ReferenceAppHtmxApplication_IntegTest.java | 45 +++++++++++++
.../referenceapp/referenceapp-targets.json | 3 +
viewers/webcomponents/foundation/USAGE.adoc | 7 +-
.../foundation/src/graphql-client.mjs | 2 +
.../foundation/src/interaction-operations.mjs | 30 +++++----
.../foundation/src/object-context-controller.mjs | 46 ++++++-------
.../foundation/test/collection.test.mjs | 57 +++++++++++++++-
.../test/fixtures/rich-schema-fixture.mjs | 8 +++
.../foundation/test/identity-selection.test.mjs | 76 +++++++++++++++++++++
.../foundation/test/interaction-command.test.mjs | 73 ++++++++++++++++++++
.../foundation/test/object-context.test.mjs | 25 +++++++
21 files changed, 581 insertions(+), 101 deletions(-)
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/REPRODUCING.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/REPRODUCING.md
new file mode 100644
index 00000000000..bade37bfdb0
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/REPRODUCING.md
@@ -0,0 +1,53 @@
+# Reproducing versionless identity evidence
+
+Use Temurin 25 for the copied Reference Application reactor.
+Install the local parent and support artifacts when they are not already present, using `-Dmaven.install.skip=false` as documented by the archived regression-suite evidence.
+
+## Foundation tests
+
+```shell
+cd viewers/webcomponents/foundation
+node --test
+```
+
+The focused coverage is in `identity-selection.test.mjs`, `object-context.test.mjs`, `interaction-command.test.mjs`, `collection.test.mjs`, and `graphql-client.test.mjs`.
+
+## Reference Application integration
+
+```shell
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Dtest=ReferenceAppHtmxApplication_IntegTest#versionlessViewModelsAdvertiseIdentityAndSupportConcreteCollectionRows \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+This test uses separate one-type introspection requests for the versioned entity and two versionless view models, then executes the representative concrete collection-row query.
+
+## Reference Application browser journey
+
+Install the current viewer artifact before starting the copied launcher.
+
+```shell
+mvn -f viewers/webcomponents/pom.xml \
+ -pl foundation,htmx -am -DskipTests install
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest#populatedPagedConfiguredPolymorphicAndRouteReplacedCollectionsRemainVisible \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+The deterministic paged concrete view-model collection must reach `ready` and render navigable object links.
+The polymorphic target remains bounded and the composite bookmark retains its separate visible route-gap assertion.
+
+## Full qualification
+
+```shell
+mvn -f viewers/webcomponents/pom.xml -pl foundation,htmx -am test
+mvn -f viewers/graphql/pom.xml -pl model -am test
+mvn -f viewers/webcomponents/pom.xml -pl sample-htmx-petclinic -am -Pplaywright test
+mvn -f regressiontests/referenceapp/pom.xml clean package
+mvn -f regressiontests/referenceapp/pom.xml -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest \
+ -Dsurefire.failIfNoSpecifiedTests=false test
+openspec validate fix-webcomponent-versionless-identity-preparation --strict
+git diff --check
+```
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/final-gate-results.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/final-gate-results.md
new file mode 100644
index 00000000000..2622f66e82a
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/final-gate-results.md
@@ -0,0 +1,30 @@
+# Final gate results
+
+## Passed
+
+- Foundation Node suite: 137 tests passed with zero failures.
+- Web-component foundation and HTMX Maven tests: `BUILD SUCCESS`.
+- GraphQL model reactor and tests: `BUILD SUCCESS`.
+- Pinned Reference Application versionless metadata and concrete-row integration: `BUILD SUCCESS`.
+- Petclinic integration and Playwright reactor: `BUILD SUCCESS`.
+- Petclinic Playwright: 4 tests passed with zero failures, errors, or skips.
+- Reference Application ordinary clean package, integration tests, inventory tests, and deterministic fixtures: `BUILD SUCCESS`.
+- Incremental capability inventory generation retained SHA-256 `75ef904a0d4fbc9c915c74866cdbd503743dab589f7525bbab126baf1eaa024a`, identical to the clean baseline.
+- Reference Application Playwright: 9 tests passed with zero failures, errors, or skips.
+- Vaadin production-like pilot: 5 scenarios with zero axe, CSP, console, page, external-request, or overflow failures.
+- GraphQL model and Reference Application RAT checks: `BUILD SUCCESS`.
+- New foundation test source is approved as Apache License 2.0 by RAT.
+- Strict OpenSpec validation and `git diff --check`: passed.
+
+## Corrected executable outcomes
+
+`demo.ActionAutoCompletePage.selectTvCharacter` now returns versionless autocomplete candidates, accepts the selected typed identity, closes the prompt, and retains the authoritative route.
+`demo.CollectionLayoutPagedPage.children` and `moreChildren` now reach `ready` without requesting `_meta.version` from `demo.CollectionLayoutPagedChildVm`.
+The deterministic populated collection renders thirteen semantic object links.
+Versioned entity property and collection fixtures continue to request and preserve advertised versions.
+
+## Retained gaps and warning
+
+General union-fragment projection and long opaque composite routes remain separate focused changes.
+The standalone foundation RAT goal still reports the same pre-existing `vaadin-reference/README.adoc` and generated `vaadin-reference.js` resources.
+Neither resource is introduced or modified by this change, and RAT approves the newly added test file.
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/implementation-report.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/implementation-report.md
new file mode 100644
index 00000000000..d9b4e319552
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/implementation-report.md
@@ -0,0 +1,28 @@
+# Versionless identity implementation report
+
+## Implementation
+
+Targeted object description now follows concrete object-valued `get` and collection-window `rows` types to their advertised metadata descriptions.
+A shared `metadataSelectionForType(...)` helper derives the available subset of `id`, `logicalTypeName`, `title`, and `version`.
+Direct interaction results, object-valued properties, preparation values, choices, autocomplete results, and concrete collection rows use that shared policy.
+
+Versioned entity values retain `version`.
+Versionless view models omit it while preserving identity, title, pending-value conversion, validation, object-link rendering, and row hydration.
+Missing type descriptions and abstract results retain bounded typename-only selection, and an abstract collection row is rejected locally before a speculative metadata operation.
+Runtime response checks still require `id` and `logicalTypeName` before creating a hydrated row context or publishing navigable identity.
+
+## Reference Application correction
+
+The deterministic `demo.CollectionLayoutPagedPage.children` window now reaches `ready` rather than a missing-version GraphQL error.
+Its thirteen `demo.CollectionLayoutPagedChildVm` rows render as navigable semantic object links without `_meta.version`.
+`moreChildren` also reaches `ready`.
+Existing action choices and Action Semantics journeys continue to prepare and invoke concrete versionless values successfully.
+
+The collection polymorphism journey remains visibly bounded according to its effective shape, and the long `demo.CompositeValuesPage` bookmark continues to assert `invalid-route`.
+General union fragments and opaque route handling remain separate follow-on changes.
+
+## Compatibility
+
+No server GraphQL schema or generated name changed.
+No public Causeway element, context method, event, result kind, route, history policy, HTMX behavior, Vaadin selection policy, dependency, CSP hash, or asset URL changed.
+The correction is internal to targeted introspection and operation selection.
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/metadata-shape-matrix.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/metadata-shape-matrix.md
new file mode 100644
index 00000000000..bc4bfa463ff
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/metadata-shape-matrix.md
@@ -0,0 +1,47 @@
+# Metadata shape matrix
+
+## Reviewed concrete shapes
+
+| Target | Effective metadata type | Advertised fields relevant to identity | Required selection |
+|---|---|---|---|
+| `demo.BigDecimalEntity` | `rich__demo_BigDecimalEntity__gqlv_meta` | `id`, `logicalTypeName`, `title`, `version` | `_meta { id logicalTypeName title version }` |
+| `demo.ActionSemanticsVm` | `rich__demo_ActionSemanticsVm__gqlv_meta` | `id`, `logicalTypeName`, `title`; no `version` | `_meta { id logicalTypeName title }` |
+| `demo.CollectionLayoutPagedChildVm` | `rich__demo_CollectionLayoutPagedChildVm__gqlv_meta` | `id`, `logicalTypeName`, `title`; no `version` | `_meta { id logicalTypeName title }` |
+| `demo.ActionChoices` parameter choices | concrete choice object metadata | `id`, `logicalTypeName`, `title`; version availability follows the effective type | Advertised subset only |
+
+Targeted introspection is issued as one `__type` operation per metadata type to remain compatible with GraphQL Java's good-faith introspection limit.
+The checked-in integration test proves that the versioned entity advertises `version` and the two representative view models do not.
+
+## Representative executable row operation
+
+```graphql
+query {
+ rich {
+ demo_CollectionLayoutPagedPage(object: {id: "<page-id>"}) {
+ children {
+ get {
+ _meta { id logicalTypeName title }
+ value { get }
+ }
+ }
+ }
+ }
+}
+```
+
+The operation returns concrete `demo.CollectionLayoutPagedChildVm` rows with non-empty identifiers, logical type, title, and value.
+Adding `_meta.version` is invalid for this type.
+The corrected browser operation requests only the advertised metadata and reaches `ready` with thirteen navigable object links in the deterministic fixture.
+
+## Identity minimum and optional fields
+
+`id` and `logicalTypeName` are the minimum fields for a navigable bookmark or hydrated row context.
+`title` is optional and uses the established identifier presentation fallback.
+`version` is optional and remains an advertised concurrency value rather than part of semantic identity.
+The client never infers missing identity from a generated GraphQL type name and never manufactures a version.
+
+## Retained focused gaps
+
+`rich__demo_ValueHolder__gqlv_union` requires concrete fragments before member metadata can be projected and remains assigned to the union-projection change.
+The long opaque identifier returned for `demo.CompositeValuesPage` still reaches the visible `invalid-route` state and remains assigned to the route-handling change.
+Neither gap is evidence that concrete versionless identity failed.
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/production-isolation.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/production-isolation.md
new file mode 100644
index 00000000000..c66c73fe270
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/production-isolation.md
@@ -0,0 +1,11 @@
+# Production isolation verification
+
+No Maven POM, npm package manifest, lock file, dependency version, or third-party source changed.
+No public GraphQL query, mutation, type, field, argument, scalar, input, output, or generated-name contract changed.
+The implementation consumes additional concrete value types through the established one-type targeted-introspection mechanism.
+
+No public `<causeway-*>` element, context method, semantic event name, event detail, result kind, canonical route, browser history policy, HTMX lifecycle, or asset URL changed.
+No Vaadin input, generated bundle, checksum, exact CSP hash, qualification policy, route-lazy trigger, native fallback, or default-selection policy changed.
+
+The correction changes only internal field selection for concrete object metadata and bounded rejection of abstract row selection.
+Rollback requires no schema, persisted-data, route, application configuration, or asset migration.
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/tasks.md b/openspec/changes/fix-webcomponent-versionless-identity-preparation/tasks.md
index 80ff5b2f3db..b2ae1c228ab 100644
--- a/openspec/changes/fix-webcomponent-versionless-identity-preparation/tasks.md
+++ b/openspec/changes/fix-webcomponent-versionless-identity-preparation/tasks.md
@@ -1,62 +1,62 @@
## 1. Confirm executable versionless shapes
-- [ ] 1.1 Capture targeted introspection for representative versioned entity and versionless view-model metadata types.
-- [ ] 1.2 Identify concrete Reference Application property, preparation, choice or autocomplete, action-result, and collection-row targets that omit `version`.
-- [ ] 1.3 Record retained interface or union and opaque-route targets that remain outside this correction.
+- [x] 1.1 Capture targeted introspection for representative versioned entity and versionless view-model metadata types.
+- [x] 1.2 Identify concrete Reference Application property, preparation, choice or autocomplete, action-result, and collection-row targets that omit `version`.
+- [x] 1.3 Record retained interface or union and opaque-route targets that remain outside this correction.
## 2. Centralize metadata selection
-- [ ] 2.1 Add a shared helper that derives the advertised metadata subset for a concrete object type.
-- [ ] 2.2 Preserve `id`, `logicalTypeName`, `title`, and `version` only when each field is advertised.
-- [ ] 2.3 Return a bounded projection when an object type or metadata description is unavailable.
-- [ ] 2.4 Keep semantic identity minimum validation separate from optional version handling.
-- [ ] 2.5 Reuse the helper from direct interaction result selection without changing scalar, enum, resource, or union behavior.
+- [x] 2.1 Add a shared helper that derives the advertised metadata subset for a concrete object type.
+- [x] 2.2 Preserve `id`, `logicalTypeName`, `title`, and `version` only when each field is advertised.
+- [x] 2.3 Return a bounded projection when an object type or metadata description is unavailable.
+- [x] 2.4 Keep semantic identity minimum validation separate from optional version handling.
+- [x] 2.5 Reuse the helper from direct interaction result selection without changing scalar, enum, resource, or union behavior.
## 3. Correct property and preparation projections
-- [ ] 3.1 Replace unconditional object-valued property metadata selection with the shared advertised selection.
-- [ ] 3.2 Verify versioned property references continue to retain returned versions.
-- [ ] 3.3 Verify versionless property references remain renderable and convertible to pending identity values.
-- [ ] 3.4 Verify action and property defaults, choices, autocomplete, validity, and datatype preparation omit absent metadata fields.
-- [ ] 3.5 Preserve preparation cancellation, stale-response, validation, and protected-value behavior.
+- [x] 3.1 Replace unconditional object-valued property metadata selection with the shared advertised selection.
+- [x] 3.2 Verify versioned property references continue to retain returned versions.
+- [x] 3.3 Verify versionless property references remain renderable and convertible to pending identity values.
+- [x] 3.4 Verify action and property defaults, choices, autocomplete, validity, and datatype preparation omit absent metadata fields.
+- [x] 3.5 Preserve preparation cancellation, stale-response, validation, and protected-value behavior.
## 4. Correct collection-row projections
-- [ ] 4.1 Derive the base row selection from the concrete collection element type.
-- [ ] 4.2 Merge advertised row metadata with declared semantic columns without duplicate or speculative fields.
-- [ ] 4.3 Preserve versioned row hydration, windows, ordering, offsets, lazy activation, and partial errors.
-- [ ] 4.4 Support versionless concrete row hydration when `id` and `logicalTypeName` are advertised and returned.
-- [ ] 4.5 Retain bounded non-navigable or partial behavior for abstract rows that require the later union-projection change.
+- [x] 4.1 Derive the base row selection from the concrete collection element type.
+- [x] 4.2 Merge advertised row metadata with declared semantic columns without duplicate or speculative fields.
+- [x] 4.3 Preserve versioned row hydration, windows, ordering, offsets, lazy activation, and partial errors.
+- [x] 4.4 Support versionless concrete row hydration when `id` and `logicalTypeName` are advertised and returned.
+- [x] 4.5 Retain bounded non-navigable or partial behavior for abstract rows that require the later union-projection change.
## 5. Add focused foundation coverage
-- [ ] 5.1 Add versioned and versionless metadata-selection fixtures and unit tests.
-- [ ] 5.2 Add object-valued property tests proving absent `version` is not selected.
-- [ ] 5.3 Add preparation, choices, and autocomplete tests for concrete versionless values.
-- [ ] 5.4 Add versioned and versionless collection-row selection and hydration tests.
-- [ ] 5.5 Add missing metadata-description and missing identity-minimum tests.
-- [ ] 5.6 Add regression assertions that unions remain bounded and no version or bookmark is invented.
+- [x] 5.1 Add versioned and versionless metadata-selection fixtures and unit tests.
+- [x] 5.2 Add object-valued property tests proving absent `version` is not selected.
+- [x] 5.3 Add preparation, choices, and autocomplete tests for concrete versionless values.
+- [x] 5.4 Add versioned and versionless collection-row selection and hydration tests.
+- [x] 5.5 Add missing metadata-description and missing identity-minimum tests.
+- [x] 5.6 Add regression assertions that unions remain bounded and no version or bookmark is invented.
## 6. Qualify against the pinned Reference Application
-- [ ] 6.1 Add or refine deterministic target-catalogue entries for versionless preparation and row journeys.
-- [ ] 6.2 Convert missing-version browser assertions to successful typed interactions only where executable evidence supports the correction.
-- [ ] 6.3 Preserve invalid, cancelled, stale, responsive, accessibility, CSP, console, external-request, and route-disposal assertions.
-- [ ] 6.4 Preserve explicit union-projection and opaque-route known gaps.
-- [ ] 6.5 Update capability inventory classifications only where executable evidence changes.
-- [ ] 6.6 Verify clean and incremental inventory generation remain byte-identical.
+- [x] 6.1 Add or refine deterministic target-catalogue entries for versionless preparation and row journeys.
+- [x] 6.2 Convert missing-version browser assertions to successful typed interactions only where executable evidence supports the correction.
+- [x] 6.3 Preserve invalid, cancelled, stale, responsive, accessibility, CSP, console, external-request, and route-disposal assertions.
+- [x] 6.4 Preserve explicit union-projection and opaque-route known gaps.
+- [x] 6.5 Update capability inventory classifications only where executable evidence changes.
+- [x] 6.6 Verify clean and incremental inventory generation remain byte-identical.
## 7. Document compatibility and isolation
-- [ ] 7.1 Document the identity-versus-version contract and concrete metadata selection algorithm.
-- [ ] 7.2 Record representative introspection and operation evidence with reproducible commands.
-- [ ] 7.3 Verify no public GraphQL, Causeway element, event, route, HTMX, Vaadin, dependency, CSP, or asset-policy contract changes.
+- [x] 7.1 Document the identity-versus-version contract and concrete metadata selection algorithm.
+- [x] 7.2 Record representative introspection and operation evidence with reproducible commands.
+- [x] 7.3 Verify no public GraphQL, Causeway element, event, route, HTMX, Vaadin, dependency, CSP, or asset-policy contract changes.
## 8. Run final qualification gates
-- [ ] 8.1 Run the complete foundation Node suite and web-component foundation and HTMX Maven tests.
-- [ ] 8.2 Run relevant GraphQL model and integration tests.
-- [ ] 8.3 Run the full Petclinic integration and Playwright suites.
-- [ ] 8.4 Run the Reference Application clean package, integration, capability inventory, and Playwright suites.
-- [ ] 8.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
-- [ ] 8.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
+- [x] 8.1 Run the complete foundation Node suite and web-component foundation and HTMX Maven tests.
+- [x] 8.2 Run relevant GraphQL model and integration tests.
+- [x] 8.3 Run the full Petclinic integration and Playwright suites.
+- [x] 8.4 Run the Reference Application clean package, integration, capability inventory, and Playwright suites.
+- [x] 8.5 Run strict CSP, accessibility, keyboard, responsive, theme, external-request, console-error, page-error, and overflow gates.
+- [x] 8.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
diff --git a/openspec/planned-changes/web-component-viewer/README.md b/openspec/planned-changes/web-component-viewer/README.md
index ce85134be4a..b111d394730 100644
--- a/openspec/planned-changes/web-component-viewer/README.md
+++ b/openspec/planned-changes/web-component-viewer/README.md
@@ -5,7 +5,7 @@ They are held outside `openspec/changes/` because the repository permits only on
The foundation, domain-component, rich GraphQL correctness, value-semantics, collection-windowing, application-entry, composite-object, menubar, generic HTMX, theming, Vaadin evaluation, and Vaadin reference-widget pilot changes are archived.
The Reference Application regression suite and input-value hardening changes are archived.
The action-dispatch correctness change is archived, completing the remaining Priority 0 correction identified by that broad capability inventory.
-The next change should be a focused versionless-identity and preparation correction, followed by separate union-projection and opaque-route corrections before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
+The current active change is `fix-webcomponent-versionless-identity-preparation`, followed by separate union-projection and opaque-route corrections before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
The older Vue, Svelte, metadata, diagnostics, performance-analysis, catalogue, and designer drafts remain queued behind that higher-priority qualification and default-adoption work.
Complete child directories contain `.openspec.yaml`, `proposal.md`, `design.md`, `tasks.md`, and delta specifications and can be promoted verbatim after review.
diff --git a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
index 2bab7ff6c08..2421b0b409e 100644
--- a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
+++ b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
@@ -7,7 +7,7 @@ Native semantic editors remain rollback and fail-safe implementations, and defau
The repository permits one active OpenSpec change at a time.
The Reference Application suite and input-value hardening are archived.
The archived `fix-webcomponent-action-dispatch-correctness` change completed the remaining Priority 0 correctness tranche identified by the pinned regression corpus.
-The next change should isolate versionless identity and preparation before separate union-projection and opaque-route corrections.
+The active `fix-webcomponent-versionless-identity-preparation` change isolates concrete versionless identity before separate union-projection and opaque-route corrections.
Proposal-only drafts must be refined against checked-in capability evidence before promotion.
| Order | Proposal | Purpose | Promotion gate |
@@ -15,7 +15,7 @@ Proposal-only drafts must be refined against checked-in capability evidence befo
| 1 | `add-referenceapp-webcomponent-regression-suite` *(archived)* | Copy the pinned broad corpus, establish deterministic inventory, and expose real gaps. | Completed with reviewed classifications. |
| 2 | `harden-webcomponent-input-value-semantics` *(archived)* | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Completed against stable Reference Application fixtures. |
| 3 | `fix-webcomponent-action-dispatch-correctness` *(archived)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Completed with successful typed Reference Application interactions and unchanged public operations. |
-| 4 | Focused identity, union-projection, and opaque-route changes | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling. | Each retained gap has an executable focused contract and passing regression target. |
+| 4 | `fix-webcomponent-versionless-identity-preparation` *(active)*, then focused union-projection and opaque-route changes | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
| 5 | `add-paged-graphql-reference-autocomplete` | Add honest server-side reference windows for large datasets. | Public GraphQL operation, identity, preparation, and ordering contracts are accepted. |
| 6 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
| 7 | `make-vaadin-default-for-webcomponent-viewer` | Flip the supported selection policy to Vaadin-first and remove pilot status. | All prerequisite suites pass in default and explicit native modes. |
diff --git a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
index b09623cda59..500ebf79e51 100644
--- a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
+++ b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
@@ -129,8 +129,13 @@ void menusChoicesAutocompleteCancellationAndRouteDisposal() {
openObject("demo.ActionAutoCompletePage", invokeViewModel(
"demo_ActionAutoCompleteMenu", "autoComplete", "rich__demo_ActionAutoCompletePage"));
- page.waitForFunction("() => (globalThis.__referenceAppKnownGaps?.length || 0) > 0");
- assertThat(knownGapCount()).isGreaterThan(0);
+ objectAction("selectTvCharacter").click();
+ waitForPrompt("selectTvCharacter");
+ selectFirstAutocompleteChoice("tvCharacter", "Tom");
+ submitPrompt();
+ page.locator(PROMPT).waitFor(new Locator.WaitForOptions()
+ .setState(com.microsoft.playwright.options.WaitForSelectorState.DETACHED));
+ waitForLogicalType("demo.ActionAutoCompletePage");
openShell();
assertThat(openCandidateOverlays()).isZero();
@@ -335,32 +340,36 @@ void populatedPagedConfiguredPolymorphicAndRouteReplacedCollectionsRemainVisible
openObject("demo.CollectionLayoutPagedPage", invokeViewModel(
"demo_CollectionLayoutMenu", "paged", "rich__demo_CollectionLayoutPagedPage"));
final String childrenState = waitForCollectionOutcome("children");
- if ("ready".equals(childrenState)) {
- final int pageRows = page.locator("causeway-collection[member='children'] tbody tr").count();
- assertThat(pageRows).isBetween(1, 10);
- assertThat(page.locator("causeway-collection[member='children'] thead th").count()).isGreaterThan(0);
- } else {
- assertThat(childrenState).isIn("partial-error", "error");
- assertThat(knownGapCount()).isGreaterThan(0);
- }
- assertThat(waitForCollectionOutcome("moreChildren")).isIn("ready", "partial-error", "error");
+ assertThat(childrenState).isEqualTo("ready");
+ final int pageRows = page.locator("causeway-collection[member='children'] .causeway-collection-rows li").count();
+ assertThat(pageRows).isBetween(1, 20);
+ assertThat(page.locator("causeway-collection[member='children'] causeway-object-link").count())
+ .isEqualTo(pageRows);
+ assertThat(waitForCollectionOutcome("moreChildren")).isEqualTo("ready");
openObject("demo.CollectionTypeOfPage", invokeViewModel(
"demo_CollectionMenu", "typeOf", "rich__demo_CollectionTypeOfPage"));
final String typeOfChildrenState = waitForCollectionOutcome("children");
assertThat(typeOfChildrenState).isIn("ready", "partial-error", "error");
+ if ("ready".equals(typeOfChildrenState)) {
+ assertThat(page.locator("causeway-collection[member='children'] causeway-object-link").count())
+ .isGreaterThan(0);
+ } else {
+ assertThat(page.locator("causeway-collection[member='children']").innerText()).isNotBlank();
+ }
final Locator otherChildren = page.locator("causeway-collection[member='otherChildren']");
assertThat(otherChildren.count()).isEqualTo(1);
assertThat(otherChildren.evaluate("element => element.collectionState.status")).isEqualTo("idle");
final String panelId = (String) otherChildren.evaluate("element => element.closest('[role=tabpanel]')?.id || null");
if (panelId != null) {
page.locator("[role=tab][aria-controls='" + panelId + "']").click();
- assertThat(waitForCollectionOutcome("otherChildren")).isIn("ready", "partial-error", "error");
- }
- if ("ready".equals(typeOfChildrenState)) {
- assertThat(page.locator("causeway-collection tbody tr a[href*='/htmx/object/']").count()).isGreaterThan(0);
- } else {
- assertThat(knownGapCount()).isGreaterThan(0);
+ final String otherChildrenState = waitForCollectionOutcome("otherChildren");
+ assertThat(otherChildrenState).isIn("ready", "partial-error", "error");
+ if ("ready".equals(otherChildrenState)) {
+ assertThat(otherChildren.locator("causeway-object-link").count()).isGreaterThan(0);
+ } else {
+ assertThat(otherChildren.innerText()).isNotBlank();
+ }
}
openShell();
@@ -536,6 +545,19 @@ private void selectFirstAvailableChoice(final String parameterId) {
page.waitForFunction("selector => document.querySelector(selector)?.value?.id", parameter(parameterId));
}
+ private void selectFirstAutocompleteChoice(final String parameterId, final String search) {
+ final Locator control = page.locator(parameter(parameterId));
+ final Locator input = control.locator("vaadin-combo-box input");
+ input.fill(search);
+ page.waitForFunction("selector => { const element = document.querySelector(selector); return element?.dataset.widgetState === 'ready' && element.querySelector('vaadin-combo-box')?.items?.length > 0; }", parameter(parameterId));
+ final String label = (String) control.evaluate("element => element.querySelector('vaadin-combo-box').items[0].title");
+ input.fill(label);
+ input.focus();
+ page.keyboard().press("ArrowDown");
+ page.keyboard().press("Enter");
+ page.waitForFunction("selector => document.querySelector(selector)?.value?.id", parameter(parameterId));
+ }
+
private void submitPrompt() {
page.locator("[data-testid='action-prompt-submit']").click();
}
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
index 280b7e8870f..ebc086b22c2 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppCapabilityInventory_IntegTest.java
@@ -110,6 +110,7 @@ private void assertJourneyTargetsExist(final JsonNode introspection) throws Exce
"action-choices", "action-autocomplete", "action-defaults", "action-validation",
"action-parameterless", "action-parameterized", "action-scalar-outcome",
"action-object-outcome", "action-cancel-stale-concurrency",
+ "versionless-preparation", "versionless-action-result", "versionless-collection-row",
"property-text", "property-multiline", "property-hidden", "property-disabled",
"property-editing", "property-validation", "property-cancel-stale",
"collection-empty-populated", "collection-paging-columns",
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
index 767ada113b1..7c619ba7804 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
@@ -215,6 +215,51 @@ void directServiceAndParameterizedObjectActionMutationsUseAdvertisedShapes() thr
.isEqualTo("demo.ActionChoices");
}
+ @Test
+ void versionlessViewModelsAdvertiseIdentityAndSupportConcreteCollectionRows() throws Exception {
+ final JsonNode versionedMetadata = graphQL("""
+ { __type(name: "rich__demo_BigDecimalEntity__gqlv_meta") { fields { name } } }
+ """);
+ final JsonNode actionMetadata = graphQL("""
+ { __type(name: "rich__demo_ActionSemanticsVm__gqlv_meta") { fields { name } } }
+ """);
+ final JsonNode rowMetadata = graphQL("""
+ { __type(name: "rich__demo_CollectionLayoutPagedChildVm__gqlv_meta") { fields { name } } }
+ """);
+ assertNoGraphQLErrors(versionedMetadata);
+ assertNoGraphQLErrors(actionMetadata);
+ assertNoGraphQLErrors(rowMetadata);
+ assertThat(versionedMetadata.at("/data/__type/fields").findValuesAsText("name"))
+ .contains("id", "logicalTypeName", "title", "version");
+ assertThat(actionMetadata.at("/data/__type/fields").findValuesAsText("name"))
+ .contains("id", "logicalTypeName", "title")
+ .doesNotContain("version");
+ assertThat(rowMetadata.at("/data/__type/fields").findValuesAsText("name"))
+ .contains("id", "logicalTypeName", "title")
+ .doesNotContain("version");
+
+ final JsonNode opened = graphQL("""
+ { rich { demo_CollectionLayoutMenu {
+ paged { invoke { results { _meta { id logicalTypeName title } } } }
+ } } }
+ """);
+ assertNoGraphQLErrors(opened);
+ final String pageId = opened.at("/data/rich/demo_CollectionLayoutMenu/paged/invoke/results/_meta/id").asText();
+ assertThat(pageId).isNotBlank();
+
+ final JsonNode rows = graphQL("""
+ { rich { demo_CollectionLayoutPagedPage(object: {id: %s}) {
+ children { get { _meta { id logicalTypeName title } value { get } } }
+ } } }
+ """.formatted(OBJECT_MAPPER.writeValueAsString(pageId)));
+ assertNoGraphQLErrors(rows);
+ final JsonNode firstRow = rows.at("/data/rich/demo_CollectionLayoutPagedPage/children/get/0");
+ assertThat(firstRow.at("/_meta/id").asText()).isNotBlank();
+ assertThat(firstRow.at("/_meta/logicalTypeName").asText())
+ .isEqualTo("demo.CollectionLayoutPagedChildVm");
+ assertThat(firstRow.at("/value/get").asText()).isNotBlank();
+ }
+
@Test
void exactDecimalPropertyMutationUsesAdvertisedStringAndRestoresFixture() throws Exception {
final JsonNode open = graphQL("""
diff --git a/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json b/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
index 90cf2533701..39fbab1382a 100644
--- a/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
+++ b/regressiontests/referenceapp/support-jpa/src/main/resources/org/apache/causeway/regressiontests/referenceapp/referenceapp-targets.json
@@ -11,6 +11,9 @@
{"family": "action-scalar-outcome", "rootField": "demo_ActionSemanticsVm", "member": "queryPropertyForSafeAndRequestCacheable"},
{"family": "action-object-outcome", "rootField": "demo_ActionSemanticsVm", "member": "reportPropertyForSafe"},
{"family": "action-cancel-stale-concurrency", "rootField": "demo_ActionSemanticsVm", "member": "updatePropertyForIdempotent"},
+ {"family": "versionless-preparation", "rootField": "demo_ActionChoices", "member": "selectTvCharacter"},
+ {"family": "versionless-action-result", "rootField": "demo_ActionSemanticsVm", "member": "reportPropertyForSafe"},
+ {"family": "versionless-collection-row", "rootField": "demo_CollectionLayoutPagedPage", "member": "children"},
{"family": "property-text", "rootField": "demo_PropertyMaxLengthPage", "member": "name"},
{"family": "property-multiline", "rootField": "demo_PropertyLayoutMultiLinePage", "member": "propertyUsingAnnotation"},
{"family": "property-hidden", "rootField": "demo_PropertyLayoutHiddenPage", "member": "objects"},
diff --git a/viewers/webcomponents/foundation/USAGE.adoc b/viewers/webcomponents/foundation/USAGE.adoc
index 10c39f938bd..d0b8944706e 100644
--- a/viewers/webcomponents/foundation/USAGE.adoc
+++ b/viewers/webcomponents/foundation/USAGE.adoc
@@ -99,7 +99,8 @@ Application-entry discovery separately introspects the operation roots, configur
The read selects only menu metadata, bounded issues, and `_meta` identity for the supported object home; it does not project home members or invent a home action.
One browser client serializes these initial targeted discovery requests so object and menu contexts do not race a cold GraphQL schema, while the viewer initializes its lazy execution source once without changing data-fetcher or mutation execution policy.
-Descriptions include member kind, advertised wrapper fields, output type reference, named type, innermost type kind, collection element type, and reachable value-shape fields.
+Descriptions include member kind, advertised wrapper fields, output type reference, named type, innermost type kind, collection element type, concrete object metadata, and reachable value-shape fields.
+Concrete property values, preparation values, action results, and rows use one metadata-selection policy that requests the advertised subset of `id`, `logicalTypeName`, `title`, and `version`.
Descriptions are cached by generated type name within one `<causeway-graphql-client>` instance.
Several object contexts under the same provider therefore share schema descriptions while retaining independent object snapshots.
The cache is memory-only and is not shared across browser sessions or users.
@@ -422,8 +423,10 @@ A collection's primary object requirement contains only advertised `hidden` and
The `get` field is loaded through a context-owned secondary operation after activation.
Secondary operations are cached by member and structural row selection, support forced refresh, and are canceled when their component or object context is disconnected.
-Without columns, object-valued rows request `_meta` identity, logical type, title, and version and render object links.
+Without columns, concrete object-valued rows request the advertised `_meta` subset and render object links when `id` and `logicalTypeName` are both present.
+`title` and `version` remain optional, so versionless view-model rows stay hydratable without an invented concurrency token.
Declared columns merge their property wrappers into the secondary operation and use the configured value renderer for returned values.
+Abstract rows that require concrete GraphQL fragments fail locally before a speculative operation and remain assigned to the separate union-projection correction.
Hidden cells emit no content, disabled cells expose their reasons, and row or member errors remain local while successful cells continue to render.
An empty result renders the live `No items` status.
diff --git a/viewers/webcomponents/foundation/src/graphql-client.mjs b/viewers/webcomponents/foundation/src/graphql-client.mjs
index 2072e9dc489..848d7ecab55 100644
--- a/viewers/webcomponents/foundation/src/graphql-client.mjs
+++ b/viewers/webcomponents/foundation/src/graphql-client.mjs
@@ -569,10 +569,12 @@ function referencedInteractionTypeNames(typeDescription, generatedTypeName, sche
const kind = innermostType(typeRef)?.kind;
const choiceValue = ['choices', 'default', 'autoComplete'].includes(fieldName)
&& ['OBJECT', 'INTERFACE', 'UNION'].includes(kind);
+ const concreteObjectValue = ['get', 'rows'].includes(fieldName) && kind === 'OBJECT';
const objectMetadata = fieldName === '_meta' && kind === 'OBJECT';
if (typeName && (schemaNames.isReachableSupportType(generatedTypeName, typeName)
|| kind === 'ENUM' && typeName.startsWith('rich__')
|| choiceValue
+ || concreteObjectValue
|| objectMetadata)) {
result.add(typeName);
}
diff --git a/viewers/webcomponents/foundation/src/interaction-operations.mjs b/viewers/webcomponents/foundation/src/interaction-operations.mjs
index c69c94a0189..eb210c5115a 100644
--- a/viewers/webcomponents/foundation/src/interaction-operations.mjs
+++ b/viewers/webcomponents/foundation/src/interaction-operations.mjs
@@ -184,6 +184,21 @@ export function renderGraphQLType(typeRef) {
return assertGraphQLName(typeRef.name, 'GraphQL type');
}
+export function metadataSelectionForType(typeRef, types) {
+ if (innermostType(typeRef)?.kind !== 'OBJECT') {
+ return null;
+ }
+ const typeDescription = types.get(namedType(typeRef));
+ const metadataField = fieldsByName(typeDescription).get('_meta');
+ const metadataType = metadataField ? types.get(namedType(metadataField.type)) ?? null : null;
+ const metadataFields = fieldsByName(metadataType);
+ const selection = Object.fromEntries(
+ ['id', 'logicalTypeName', 'title', 'version']
+ .filter(fieldName => metadataFields.has(fieldName))
+ .map(fieldName => [fieldName, true]));
+ return Object.keys(selection).length > 0 ? {_meta: selection} : null;
+}
+
export function resultSelectionForType(typeRef, types) {
const kind = innermostType(typeRef)?.kind;
if (kind === 'SCALAR' || kind === 'ENUM') {
@@ -193,18 +208,9 @@ export function resultSelectionForType(typeRef, types) {
if (!typeDescription) {
return {__typename: true};
}
- const fields = fieldsByName(typeDescription);
- const metadataField = fields.get('_meta');
- const metadataType = metadataField ? types.get(namedType(metadataField.type)) ?? null : null;
- if (metadataType) {
- const metadataFields = fieldsByName(metadataType);
- const metadataSelection = Object.fromEntries(
- ['id', 'logicalTypeName', 'title', 'version']
- .filter(fieldName => metadataFields.has(fieldName))
- .map(fieldName => [fieldName, true]));
- if (Object.keys(metadataSelection).length > 0) {
- return {_meta: metadataSelection};
- }
+ const metadataSelection = metadataSelectionForType(typeRef, types);
+ if (metadataSelection) {
+ return metadataSelection;
}
const scalarFields = typeDescription.fields
.filter(field => ['SCALAR', 'ENUM'].includes(innermostType(field.type)?.kind))
diff --git a/viewers/webcomponents/foundation/src/object-context-controller.mjs b/viewers/webcomponents/foundation/src/object-context-controller.mjs
index 541b46f5021..cdfe071f560 100644
--- a/viewers/webcomponents/foundation/src/object-context-controller.mjs
+++ b/viewers/webcomponents/foundation/src/object-context-controller.mjs
@@ -27,7 +27,11 @@ import {
} from './action-dispatch.mjs';
import {createSemanticEvent, OBJECT_CONTEXT_STATE_EVENT} from './context-events.mjs';
import {fieldsByName, namedType} from './introspection.mjs';
-import {argumentsFromValues, commandSelection, resultSelectionForType} from './interaction-operations.mjs';
+import {
+ argumentsFromValues,
+ commandSelection,
+ resultSelectionForType
+} from './interaction-operations.mjs';
import {deepMerge, differenceSelection, isSelectionEmpty, mergeSelections} from './selection.mjs';
import {fetchStructuralResource, StructuralResourceError} from './structural-resource.mjs';
import {InteractionResultKind, InteractionStatus, ObjectContextStatus, RequirementStatus} from './types.mjs';
@@ -519,11 +523,14 @@ export class ObjectContextController extends EventTarget {
if (!descriptor || descriptor.kind !== 'collection' || (!usesWindow && !descriptor.fields.has('get'))) {
throw new Error(`Collection '${member}' is not readable on '${description.logicalTypeName}'.`);
}
+ if (['INTERFACE', 'UNION'].includes(descriptor.value?.typeKind)) {
+ throw new Error(`Collection '${member}' uses an abstract row type that requires concrete fragment projection.`);
+ }
const requestedOffset = usesWindow ? integerAtLeast(offset, 0, 'Collection window offset') : 0;
const requestedSize = usesWindow
? integerAtLeast(size ?? descriptor.window.sizeDefault, 1, 'Collection window size')
: null;
- const rowSelection = collectionRowSelection(columns);
+ const rowSelection = collectionRowSelection(descriptor, columns, description.types);
const selection = usesWindow
? null
: {[member]: {get: rowSelection}};
@@ -1084,7 +1091,7 @@ function translateRequirement(requirement, description) {
.filter(field => member.fields.has(field))
.map(field => [field, true])
);
- memberSelection.get = propertyValueSelection(member);
+ memberSelection.get = propertyValueSelection(member, description.types);
return {descriptor: member, selection: {[member.id]: memberSelection}};
}
if (requirement.kind === 'collection'
@@ -1099,31 +1106,12 @@ function translateRequirement(requirement, description) {
};
}
-function propertyValueSelection(member) {
+function propertyValueSelection(member, types) {
const value = member.value;
if (!value || value.typeKind === 'SCALAR' || value.typeKind === 'ENUM') {
return true;
}
- const typeFields = value.typeDescription?.fields ?? [];
- if (typeFields.some(field => field.name === '_meta')) {
- return {_meta: {id: true, logicalTypeName: true, title: true, version: true}};
- }
- const lobFields = typeFields
- .filter(field => ['name', 'mimeType', 'bytes', 'chars'].includes(field.name))
- .map(field => field.name);
- if (lobFields.length > 0) {
- return Object.fromEntries(lobFields.map(field => [field, true]));
- }
- const scalarFields = typeFields
- .filter(field => ['SCALAR', 'ENUM'].includes(innermostType(field.type)?.kind))
- .map(field => field.name);
- if (scalarFields.length > 0) {
- return Object.fromEntries(scalarFields.map(field => [field, true]));
- }
- if (value.typeDescription) {
- return {__typename: true};
- }
- return {_meta: {id: true, logicalTypeName: true, title: true, version: true}};
+ return resultSelectionForType(value.typeRef, types) ?? true;
}
function integerAtLeast(value, minimum, label) {
@@ -1165,8 +1153,14 @@ function obsoleteRequestError() {
return error;
}
-function collectionRowSelection(columns) {
- const selection = {_meta: {id: true, logicalTypeName: true, title: true, version: true}};
+function collectionRowSelection(descriptor, columns, types) {
+ const value = descriptor.value;
+ const elementTypeRef = value?.elementTypeRef ?? value?.typeRef ?? null;
+ const selection = {...(resultSelectionForType(elementTypeRef, types) ?? {__typename: true})};
+ const concreteObject = value?.typeKind === 'OBJECT' && value.typeDescription;
+ if (!concreteObject) {
+ return selection;
+ }
for (const column of columns) {
const member = typeof column === 'string' ? column : column?.member;
if (!member) {
diff --git a/viewers/webcomponents/foundation/test/collection.test.mjs b/viewers/webcomponents/foundation/test/collection.test.mjs
index 10e70ac4528..62daac967ef 100644
--- a/viewers/webcomponents/foundation/test/collection.test.mjs
+++ b/viewers/webcomponents/foundation/test/collection.test.mjs
@@ -23,6 +23,8 @@ import {installDomShim} from './dom-shim.mjs';
import {
collectionWindowResponse,
createRichSchemaFixtureExecutor,
+ createRichSchemaTypes,
+ createVersionlessRichSchemaTypes,
createWindowedRichSchemaTypes,
DEPARTMENT_LOGICAL_TYPE,
DEPARTMENT_OBJECT_FIELD,
@@ -41,9 +43,9 @@ const {
ObjectContextController
} = await import('../src/index.mjs');
-function row({id = 'staff-1', name = 'Dr Ada', code = 'ADA'} = {}) {
+function row({id = 'staff-1', name = 'Dr Ada', code = 'ADA', version = '3'} = {}) {
return {
- _meta: {id, logicalTypeName: STAFF_LOGICAL_TYPE, version: '3', title: name},
+ _meta: {id, logicalTypeName: STAFF_LOGICAL_TYPE, ...(version == null ? {} : {version}), title: name},
name: {hidden: false, disabled: null, datatype: 'String', get: name},
code: {hidden: false, disabled: null, datatype: 'String', get: code}
};
@@ -142,6 +144,33 @@ test('collection secondary reads are lazy, cached and hydrate row contexts', asy
assert.equal(codeState.data.get, 'ADA');
});
+test('versionless concrete collection rows retain identity, columns and hydration', async () => {
+ const staff = row({version: null});
+ const executor = createRichSchemaFixtureExecutor({
+ types: createVersionlessRichSchemaTypes(),
+ readResponses: [graphQLObjectResponse(), collectionResponse([staff])]
+ });
+ const context = new ObjectContextController({
+ client: new CausewayGraphQLClient({executor}),
+ logicalTypeName: DEPARTMENT_LOGICAL_TYPE,
+ objectId: '42'
+ });
+ context.registerRequirement({kind: 'collection', member: 'staffMembers'});
+ await waitFor(() => context.state.status === 'ready');
+
+ const loaded = await context.loadCollection({member: 'staffMembers', columns: ['name']});
+ const document = executor.readCalls[1].document;
+ assert.match(document, /_meta\s*\{[\s\S]*?id/);
+ assert.match(document, /logicalTypeName/);
+ assert.match(document, /title/);
+ assert.doesNotMatch(document, /version/);
+ assert.match(document, /name\s*\{/);
+ assert.equal(loaded.rows[0]._meta.version, undefined);
+ const rowContext = context.createHydratedRowContext(loaded.rows[0], loaded.rowSelection);
+ assert.equal(rowContext.identity.id, 'staff-1');
+ rowContext.disconnect();
+});
+
test('collection secondary reads prefer bounded windows and expose semantic range state', async () => {
const rows = [row({id: 'staff-6', name: 'Dr Six'}), row({id: 'staff-7', name: 'Dr Seven'})];
const executor = createRichSchemaFixtureExecutor({
@@ -188,6 +217,30 @@ test('collection secondary reads prefer bounded windows and expose semantic rang
assert.equal(executor.windowCalls.length, 1, 'an identical window should use the secondary cache');
});
+test('abstract collection rows fail locally before a speculative metadata operation', async () => {
+ const types = createRichSchemaTypes();
+ const collectionType = types.get('rich__university_dept_Department__staffMembers__gqlv_collection');
+ collectionType.fields.find(candidate => candidate.name === 'get').type = {
+ kind: 'LIST', name: null, ofType: {kind: 'UNION', name: 'rich__university_staff_StaffUnion', ofType: null}
+ };
+ types.set('rich__university_staff_StaffUnion', {
+ kind: 'UNION', name: 'rich__university_staff_StaffUnion', description: null, fields: []
+ });
+ const executor = createRichSchemaFixtureExecutor({types, readResponses: [graphQLObjectResponse()]});
+ const context = new ObjectContextController({
+ client: new CausewayGraphQLClient({executor}),
+ logicalTypeName: DEPARTMENT_LOGICAL_TYPE,
+ objectId: '42'
+ });
+ context.registerRequirement({kind: 'collection', member: 'staffMembers'});
+ await waitFor(() => context.state.status === 'ready');
+
+ await assert.rejects(
+ context.loadCollection({member: 'staffMembers'}),
+ /abstract row type that requires concrete fragment projection/);
+ assert.equal(executor.readCalls.length, 1);
+});
+
test('collection secondary reads discard responses superseded for the same consumer', async () => {
const resolvers = new Map();
const executor = createRichSchemaFixtureExecutor({
diff --git a/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs b/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs
index 1ee98285ad7..da0232819d2 100644
--- a/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs
+++ b/viewers/webcomponents/foundation/test/fixtures/rich-schema-fixture.mjs
@@ -136,6 +136,14 @@ export function createRichSchemaTypes() {
]);
}
+export function createVersionlessRichSchemaTypes({windowed = false} = {}) {
+ const types = windowed ? createWindowedRichSchemaTypes() : createRichSchemaTypes();
+ const metadataType = types.get(STAFF_META_TYPE);
+ types.set(STAFF_META_TYPE, objectType(STAFF_META_TYPE, metadataType.description,
+ metadataType.fields.filter(candidate => candidate.name !== 'version')));
+ return types;
+}
+
export function createWindowedRichSchemaTypes() {
const types = createRichSchemaTypes();
const collectionType = types.get(COLLECTION_TYPE);
diff --git a/viewers/webcomponents/foundation/test/identity-selection.test.mjs b/viewers/webcomponents/foundation/test/identity-selection.test.mjs
new file mode 100644
index 00000000000..5d3220f78d6
--- /dev/null
+++ b/viewers/webcomponents/foundation/test/identity-selection.test.mjs
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ metadataSelectionForType,
+ resultSelectionForType
+} from '../src/interaction-operations.mjs';
+
+const scalar = name => ({kind: 'SCALAR', name, ofType: null});
+const named = (name, kind = 'OBJECT') => ({kind, name, ofType: null});
+const field = (name, type) => ({name, description: null, args: [], type});
+const type = (name, fields, kind = 'OBJECT') => ({name, kind, description: null, fields});
+
+function typesWithMetadata(metadataFields) {
+ return new Map([
+ ['Example', type('Example', [field('_meta', named('ExampleMeta'))])],
+ ['ExampleMeta', type('ExampleMeta', metadataFields.map(name => field(name, scalar('String'))))]
+ ]);
+}
+
+test('metadata selection preserves all advertised versioned identity fields', () => {
+ const types = typesWithMetadata(['id', 'logicalTypeName', 'title', 'version']);
+
+ assert.deepEqual(metadataSelectionForType(named('Example'), types), {
+ _meta: {id: true, logicalTypeName: true, title: true, version: true}
+ });
+ assert.deepEqual(resultSelectionForType(named('Example'), types), {
+ _meta: {id: true, logicalTypeName: true, title: true, version: true}
+ });
+});
+
+test('metadata selection omits absent version without weakening semantic identity', () => {
+ const types = typesWithMetadata(['id', 'logicalTypeName', 'title']);
+
+ assert.deepEqual(metadataSelectionForType(named('Example'), types), {
+ _meta: {id: true, logicalTypeName: true, title: true}
+ });
+ assert.equal(JSON.stringify(resultSelectionForType(named('Example'), types)).includes('version'), false);
+});
+
+test('partial metadata remains bounded without inventing identity minimums', () => {
+ const types = typesWithMetadata(['title']);
+
+ assert.deepEqual(metadataSelectionForType(named('Example'), types), {_meta: {title: true}});
+ assert.equal(JSON.stringify(resultSelectionForType(named('Example'), types)).includes('id'), false);
+ assert.equal(JSON.stringify(resultSelectionForType(named('Example'), types)).includes('logicalTypeName'), false);
+});
+
+test('missing descriptions and abstract types use typename-only projections', () => {
+ const missing = new Map();
+ const union = new Map([['ExampleUnion', type('ExampleUnion', [], 'UNION')]]);
+
+ assert.equal(metadataSelectionForType(named('Missing'), missing), null);
+ assert.deepEqual(resultSelectionForType(named('Missing'), missing), {__typename: true});
+ assert.equal(metadataSelectionForType(named('ExampleUnion', 'UNION'), union), null);
+ assert.deepEqual(resultSelectionForType(named('ExampleUnion', 'UNION'), union), {__typename: true});
+ assert.equal(resultSelectionForType(scalar('String'), missing), null);
+});
diff --git a/viewers/webcomponents/foundation/test/interaction-command.test.mjs b/viewers/webcomponents/foundation/test/interaction-command.test.mjs
index 55375d3e651..5916755c9d8 100644
--- a/viewers/webcomponents/foundation/test/interaction-command.test.mjs
+++ b/viewers/webcomponents/foundation/test/interaction-command.test.mjs
@@ -24,6 +24,7 @@ import {ObjectContextController} from '../src/object-context-controller.mjs';
const scalar = name => ({kind: 'SCALAR', name, ofType: null});
const named = name => ({kind: 'OBJECT', name, ofType: null});
+const list = ofType => ({kind: 'LIST', name: null, ofType});
const argument = (name, type) => ({name, description: null, defaultValue: null, type});
const field = (name, type, args = []) => ({name, description: null, args, type});
const graphType = (name, fields) => ({name, kind: 'OBJECT', description: null, fields, inputFields: [], enumValues: []});
@@ -61,6 +62,46 @@ function fixtureDescription() {
};
}
+function versionlessPreparationDescription() {
+ const description = fixtureDescription();
+ const choiceTypeName = 'rich__example_VersionlessChoice';
+ const metadataTypeName = `${choiceTypeName}__gqlv_meta`;
+ const paramsTypeName = `${description.generatedTypeName}__choose__gqlv_action_params`;
+ const parameterTypeName = `${description.generatedTypeName}__choose__choice__gqlv_action_parameter`;
+ const invokeTypeName = `${description.generatedTypeName}__choose__gqlv_action_invoke`;
+ const choiceInputType = named(`${choiceTypeName}__gqlv_input`);
+ const action = {
+ id: 'choose', kind: 'action', description: 'Choose', generatedTypeName: `${description.generatedTypeName}__choose__gqlv_action`,
+ fields: new Map([
+ ['params', field('params', named(paramsTypeName))],
+ ['validate', field('validate', scalar('String'), [argument('choice', choiceInputType)])],
+ ['invoke', field('invoke', named(invokeTypeName), [argument('choice', choiceInputType)])]
+ ]), value: null
+ };
+ return {
+ ...description,
+ members: new Map(description.members).set('choose', action),
+ types: new Map([
+ ...description.types,
+ [paramsTypeName, graphType(paramsTypeName, [field('choice', named(parameterTypeName))])],
+ [parameterTypeName, graphType(parameterTypeName, [
+ field('hidden', scalar('Boolean')),
+ field('default', named(choiceTypeName)),
+ field('choices', list(named(choiceTypeName))),
+ field('autoComplete', list(named(choiceTypeName)), [argument('search', scalar('String'))]),
+ field('datatype', scalar('String'))
+ ])],
+ [choiceTypeName, graphType(choiceTypeName, [field('_meta', named(metadataTypeName))])],
+ [metadataTypeName, graphType(metadataTypeName, [
+ field('id', scalar('ID')),
+ field('logicalTypeName', scalar('String')),
+ field('title', scalar('String'))
+ ])],
+ [invokeTypeName, graphType(invokeTypeName, [field('results', scalar('String'))])]
+ ])
+ };
+}
+
function fixtureMutation(description) {
return graphType('Mutation', [
field('example_Object__name', named(description.generatedTypeName), [
@@ -149,6 +190,38 @@ test('query-only and non-compliant variants report or execute discovered capabil
nonCompliant.disconnect();
});
+test('versionless preparation and autocomplete select only advertised identity metadata', async () => {
+ const description = versionlessPreparationDescription();
+ const calls = [];
+ const choice = {_meta: {id: 'choice-1', logicalTypeName: 'example.VersionlessChoice', title: 'Choice one'}};
+ const client = {
+ describeObject: async () => description,
+ describeMutation: async () => null,
+ executeObjectInteraction: async request => {
+ calls.push(request);
+ if (request.operationName === 'CausewayPrepareAction') {
+ return {data: {choose: {params: {choice: {hidden: false, default: choice, choices: [choice], datatype: 'example.VersionlessChoice'}}}}, errors: [], operation: {}};
+ }
+ return {data: {choose: {params: {choice: {autoComplete: [choice]}}}}, errors: [], operation: {}};
+ }
+ };
+ const context = new ObjectContextController({client, logicalTypeName: 'example.Object', objectId: '42'});
+
+ const prepared = await context.prepareAction('choose');
+ const completed = await context.autoCompleteActionParameter('choose', 'choice', 'Cho');
+
+ assert.equal(prepared.status, 'success');
+ assert.equal(prepared.data.parameters[0].state.default._meta.id, 'choice-1');
+ assert.equal(completed.status, 'success');
+ for (const call of calls) {
+ const serializedSelection = JSON.stringify(call.selection);
+ assert.match(serializedSelection, /logicalTypeName/);
+ assert.doesNotMatch(serializedSelection, /version/);
+ }
+ assert.deepEqual(normalizeInteractionInput(choice), {id: 'choice-1'});
+ context.disconnect();
+});
+
test('transient validation aborts obsolete generations', async () => {
const description = fixtureDescription();
let call = 0;
diff --git a/viewers/webcomponents/foundation/test/object-context.test.mjs b/viewers/webcomponents/foundation/test/object-context.test.mjs
index 24ff12eb47b..36b2f384bdc 100644
--- a/viewers/webcomponents/foundation/test/object-context.test.mjs
+++ b/viewers/webcomponents/foundation/test/object-context.test.mjs
@@ -23,7 +23,9 @@ import {CausewayGraphQLClient} from '../src/graphql-client.mjs';
import {ObjectContextController, StructuralResourceError} from '../src/object-context-controller.mjs';
import {
createRichSchemaFixtureExecutor,
+ createVersionlessRichSchemaTypes,
DEPARTMENT_LOGICAL_TYPE,
+ DEPARTMENT_OBJECT_FIELD,
graphQLObjectResponse,
partialPropertyErrorResponse,
waitFor
@@ -91,6 +93,29 @@ test('coordinates enum, object-reference, LOB and unsupported property projectio
assert.deepEqual(unsupportedState.data.get, {nested: {value: 'unknown'}});
});
+test('object-valued property projection omits an absent metadata version', async () => {
+ const response = graphQLObjectResponse();
+ delete response.data.rich[DEPARTMENT_OBJECT_FIELD].chair.get._meta.version;
+ const executor = createRichSchemaFixtureExecutor({
+ types: createVersionlessRichSchemaTypes(),
+ readResponses: [response]
+ });
+ const context = createContext(executor);
+ let chairState;
+ context.registerRequirement({kind: 'property', member: 'chair'}, state => { chairState = state; });
+ await waitFor(() => context.state.status === 'ready');
+
+ const document = executor.readCalls[0].document;
+ const chairSelection = document.slice(document.indexOf('chair {'), document.indexOf('prospectus {'));
+ assert.match(chairSelection, /_meta\s*\{[\s\S]*?id/);
+ assert.match(chairSelection, /logicalTypeName/);
+ assert.match(chairSelection, /title/);
+ assert.doesNotMatch(chairSelection, /version/);
+ assert.deepEqual(chairState.data.get._meta, {
+ id: 'staff-1', logicalTypeName: 'university.staff.StaffMember', title: 'Dr Ada'
+ });
+});
+
test('loads a later requirement as a delta and refreshes only active requirements', async () => {
const executor = createRichSchemaFixtureExecutor({
readResponses: [graphQLObjectResponse(), graphQLObjectResponse({version: '8'}), graphQLObjectResponse({version: '9'})]
(causeway) 01/15: plans web component action dispatch correction
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit 9b1994930d474acba4b12f14915b9946a50f1f77
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 06:34:26 2026 +0100
plans web component action dispatch correction
---
.../.openspec.yaml | 2 +
.../design.md | 117 +++++++++++++++++++++
.../proposal.md | 29 +++++
.../specs/domain-web-components/spec.md | 97 +++++++++++++++++
.../tasks.md | 74 +++++++++++++
.../planned-changes/web-component-viewer/README.md | 5 +-
.../web-component-viewer/vaadin-default-roadmap.md | 16 +--
7 files changed, 332 insertions(+), 8 deletions(-)
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/.openspec.yaml b/openspec/changes/fix-webcomponent-action-dispatch-correctness/.openspec.yaml
new file mode 100644
index 00000000000..4102db8a47b
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-08-24
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/design.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/design.md
new file mode 100644
index 00000000000..92e31029cd2
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/design.md
@@ -0,0 +1,117 @@
+## Context
+
+The public rich GraphQL schema exposes action invocation in more than one executable shape.
+Safe and idempotent actions are reached through nested object or service action-wrapper fields, while mutating actions normally use generated flat fields on the mutation root.
+Some supported API variants also expose a legacy nested `invokeNonIdempotent` field.
+
+The object and service contexts currently discover and execute these shapes independently.
+The object context treats any nested invocation field, including `invokeNonIdempotent`, as sufficient and therefore can skip an available top-level mutation.
+Both contexts assume that nested invocation returns an envelope with `results`, and otherwise request a `target` field even when the effective return type does not advertise one.
+Those assumptions can make operation rendering throw before execution, after which the standard controller can report only `Action invocation failed`.
+
+The pinned Reference Application preserves an executable parameterless service action that demonstrates the nested safe-dispatch defect.
+Its object actions also provide parameter, validation, mutation, outcome, cancellation, and stale-response fixtures for closing the operation-shape matrix.
+Public GraphQL remains authoritative, and this change must preserve Causeway elements, semantic events, typed value codecs, route policy, mutation serialization, strict CSP, and native or Vaadin editor independence.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- Use one introspection-driven dispatch plan for object and service actions.
+- Prefer the advertised top-level mutation for mutating actions and use a legacy nested mutating field only when no mutation exists.
+- Execute nested safe or idempotent fields without assuming a non-advertised result envelope or target field.
+- Map only declared arguments, add object target identity only through the declared target argument, and preserve exact codec values.
+- Normalize envelope and direct scalar, enum, object, collection, and void outcomes through the existing semantic result contract.
+- Return bounded capability, planning, GraphQL, transport, and invocation errors without exposing values or implementation exceptions.
+- Convert retained Reference Application known-gap assertions into successful action journeys and update the reviewed inventory only from focused evidence.
+
+**Non-Goals:**
+
+- Defining versionless identity or concurrency-token semantics.
+- Correcting general polymorphic union metadata projections or collection-row fragments.
+- Changing opaque bookmark route encoding or length handling.
+- Adding or renaming GraphQL operations, fields, arguments, or result types.
+- Adding paged autocomplete, Grid operations, Vaadin adapters, or a Vaadin-default policy.
+- Reviving invalid menu references from the copied upstream corpus.
+
+## Decisions
+
+### Build a shared immutable invocation plan
+
+A shared planner will consume the targeted object or service description, action descriptor, optional mutation root, generated field name, and target kind.
+It will return an immutable plan describing placement, mutability, selected field, declared arguments, target argument when applicable, result shape, extraction path, and outcome type.
+Both `ObjectContextController` and `ServiceActionContextController` will execute this plan through the existing GraphQL client methods.
+
+This is preferred to patching the two contexts separately because their current drift created different behavior for the same public action semantics.
+It also makes operation-shape fixtures reusable without moving GraphQL document construction into components.
+
+### Select placement by action semantics and advertised fields
+
+The planner will consider nested `invoke` and `invokeIdempotent` fields safe or idempotent query candidates.
+It will inspect the mutation root independently for the generated flat mutation field.
+An advertised top-level mutation wins for a mutating action even when `invokeNonIdempotent` also exists.
+The legacy nested `invokeNonIdempotent` field remains a compatibility fallback only when no top-level mutation is advertised.
+If no executable candidate exists, preparation and invocation return `UNSUPPORTED` without sending an invalid operation.
+
+This preserves compatibility with older API variants without using a mutating query when the compliant mutation is available.
+The alternative of removing the legacy path immediately would turn an established compatibility case into a breaking change.
+
+### Derive arguments and object target from the selected field
+
+Pending parameter values continue through the toolkit-neutral codecs and `normalizeInteractionInput`.
+Only arguments declared by the selected invocation field are emitted.
+For an object mutation, the planner identifies the target argument by its generated input type or advertised target name and supplies the current bookmark identity there.
+Service mutations never manufacture an object target.
+A missing required target or parameter mapping is a bounded planning failure before execution.
+
+This avoids maintaining a second parameter schema and prevents speculative `_target` or raw-string arguments.
+
+### Model nested result shape explicitly
+
+The planner will inspect the selected field's effective output type.
+When that type advertises a `results` field, the operation selects and extracts that field.
+When the selected field returns a scalar or enum directly, it requests no child selection and extracts the field value directly.
+When it returns a described object directly, it uses the existing safe result-selection rules and requests only advertised fields.
+When an advertised envelope provides another established result or target field, it is used only when introspection confirms the field and its type.
+Void output produces the existing void semantic result.
+
+The planner will never synthesize `{ target }` merely because `results` is absent.
+General union-fragment projection remains a later focused change; this change may select `__typename` where that is the only currently valid direct projection, but it will not claim navigable object identity unless metadata was actually returned.
+
+### Keep execution and presentation responsibilities separate
+
+The GraphQL contexts own planning, execution, extraction, error normalization, mutation serialization, and authoritative refresh notification.
+The standard interaction controller continues to own prompt state, focus, cancellation, semantic events, and result presentation.
+A context planning or execution failure returns an interaction result with a stable safe code and message, allowing the controller to avoid collapsing expected failures into its generic exception fallback.
+Unexpected exceptions remain caught at the controller boundary and are not exposed verbatim.
+
+### Qualify through a closed operation-shape matrix
+
+Foundation fixtures will cover object and service targets across nested safe, nested idempotent, top-level mutating, legacy nested mutating fallback, missing capability, parameterless, parameterized, envelope result, direct result, scalar, object, collection, and void cases.
+Integration tests will execute representative public GraphQL operations before browser tests prove the semantic controller path.
+The Reference Application service action currently asserted as `Action invocation failed` will instead assert successful typed outcome and host navigation or presentation as applicable.
+Object-action fixtures will prove valid dispatch while versionless failures remain explicitly classified for the next change.
+
+## Risks / Trade-offs
+
+- **[Risk] Existing API variants expose an unexpected envelope field.** → Record the discovered type and fail boundedly rather than guessing, then add a reviewed planner rule and fixture if it is a public supported shape.
+- **[Risk] Correct dispatch exposes the separate union-projection defect.** → Assert invocation success separately from navigable metadata and retain general union projection as the next focused contract change.
+- **[Risk] Mutation classification differs from field naming.** → Prefer actual mutation-root presence and descriptor fields over name heuristics, and test safe, idempotent, and mutating fixtures independently.
+- **[Risk] Shared planning changes previously working Petclinic behavior.** → Preserve current operation names and semantic results and run the full foundation, Petclinic, and Reference Application browser suites in both parameterless and parameterized paths.
+- **[Risk] Error details disclose submitted or protected values.** → Emit stable bounded codes and messages, retain codec redaction, and add negative assertions against operation variables, errors, events, and rendered markup.
+
+## Migration Plan
+
+1. Capture the effective nested safe and flat mutation shapes from targeted introspection in deterministic fixtures and evidence.
+2. Introduce the shared planner and unit-test it without changing public context methods.
+3. Route object and service invocation through the planner while retaining the legacy nested mutation fallback.
+4. Replace known-gap action assertions with successful integration and browser journeys.
+5. Run production module, Reference Application, CSP, accessibility, and isolation gates.
+
+The change is behavior-correcting and requires no application migration.
+Rollback consists of reverting the shared planner integration; no schema, persisted data, route, dependency, or packaged asset migration is involved.
+
+## Open Questions
+
+No architectural question blocks implementation.
+Implementation evidence must identify the exact direct or enveloped result shape used by each Reference Application target before its known-gap assertion is converted.
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/proposal.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/proposal.md
new file mode 100644
index 00000000000..ab1db8937b6
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/proposal.md
@@ -0,0 +1,29 @@
+## Why
+
+The Reference Application regression suite proves that executable parameterless service actions and valid parameterized object actions can still end in the generic visible error `Action invocation failed`.
+The semantic interaction contexts currently recognize the advertised capability but do not dispatch every nested safe-query and flat top-level mutation shape correctly, so this Priority 0 correctness defect must be removed before identity work, autocomplete paging, broader Vaadin adapters, or a default-policy flip.
+
+## What Changes
+
+- Make object and service action dispatch derive operation placement, argument placement, target identity, and result projection from targeted rich-schema introspection rather than assumptions about one generated shape.
+- Correctly execute advertised nested safe or idempotent invocation fields and flat top-level mutation fields for parameterless and parameterized actions.
+- Preserve action validation, typed codec values, mutation serialization, cancellation, stale-response protection, authoritative refresh, and typed object, collection, scalar, and void outcomes.
+- Replace successful-looking generic dispatch failures with bounded mapped GraphQL or capability errors at the action scope while keeping submitted protected values undisclosed.
+- Convert the pinned Reference Application action-choice and representative object-action known-gap journeys into successful semantic interaction assertions.
+- Add focused foundation, GraphQL integration, HTMX, Petclinic, and Reference Application regression coverage for nested query and flat mutation operation shapes.
+- Keep versionless identity and preparation, polymorphic union projection, opaque route handling, paged autocomplete, Vaadin family expansion, and the Vaadin-default policy outside this change.
+
+## Capabilities
+
+### New Capabilities
+
+None.
+
+### Modified Capabilities
+
+- `domain-web-components`: Strengthens semantic object and service action invocation so every advertised nested safe-query or flat mutation shape is dispatched, normalized, refreshed, and reported correctly.
+
+## Impact
+
+The change affects the framework-neutral object and service action contexts, GraphQL operation construction and result selection, the standard interaction controller's bounded error mapping, and representative sample and Reference Application tests.
+It does not rename public GraphQL fields or operations, add schema capabilities, change Causeway elements or semantic event names, alter canonical routes, add dependencies, or change Vaadin packaging, CSP, lazy loading, or default-selection policy.
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/specs/domain-web-components/spec.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/specs/domain-web-components/spec.md
new file mode 100644
index 00000000000..b9478be2a85
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/specs/domain-web-components/spec.md
@@ -0,0 +1,97 @@
+## MODIFIED Requirements
+
+### Requirement: Action argument validation and invocation
+The action interaction controller SHALL validate the pending argument set and invoke an object or service action through the semantically correct nested query or top-level mutation capability exposed by targeted introspection.
+The context MUST emit only arguments declared by the selected field, MUST supply object target identity only through an advertised target argument, and MUST NOT issue an invalid operation when no executable capability exists.
+
+#### Scenario: Invalid argument set
+- **WHEN** rich action validation rejects one or more pending arguments
+- **THEN** the prompt presents the mapped validation reasons
+- **AND** does not invoke the action
+
+#### Scenario: Parameterless nested service action
+- **WHEN** a parameterless service action advertises a nested safe or idempotent invocation field
+- **THEN** the service context executes that field beneath the advertised service query path without manufacturing variables or an object target
+- **AND** publishes the resulting semantic outcome instead of `Action invocation failed`
+
+#### Scenario: Parameterized nested object action
+- **WHEN** a valid object action advertises a nested safe or idempotent invocation field with declared parameters
+- **THEN** the object context sends the codec-produced pending values only through matching declared arguments
+- **AND** preserves the current object identity through the enclosing object lookup
+
+#### Scenario: Mutating object action has a top-level mutation
+- **WHEN** a valid mutating object action advertises a generated top-level mutation field
+- **THEN** the context executes that mutation and supplies the current bookmark through its declared target argument
+- **AND** does not select a legacy nested mutating query merely because `invokeNonIdempotent` is also advertised
+
+#### Scenario: Mutating service action has a top-level mutation
+- **WHEN** a valid mutating service action advertises a generated top-level mutation field
+- **THEN** the service context executes that mutation with only its declared action arguments
+- **AND** does not manufacture an object target
+
+#### Scenario: Only a legacy mutating invocation is available
+- **WHEN** a supported API variant exposes `invokeNonIdempotent` but no corresponding top-level mutation
+- **THEN** the context may use the legacy nested capability as an explicit compatibility fallback
+- **AND** reports the selected placement through its inspectable operation result
+
+#### Scenario: Advertised action has no executable placement
+- **WHEN** targeted introspection exposes action state or parameter fields but no supported invocation field or mutation
+- **THEN** preparation or invocation returns a bounded unsupported interaction result
+- **AND** no invalid GraphQL request is issued
+
+### Requirement: Semantic action outcomes
+The interaction layer SHALL derive action result selection and extraction from the advertised output type and SHALL normalize object, collection, scalar, and void outcomes through framework-neutral semantic events.
+It MUST NOT request a synthetic `results`, `target`, metadata, or child field that the effective result type does not advertise.
+
+#### Scenario: Invocation uses a results envelope
+- **WHEN** an advertised nested invocation output contains a `results` field
+- **THEN** the context selects and extracts that field using its described type
+- **AND** normalizes the extracted value through the semantic result contract
+
+#### Scenario: Invocation returns a direct value
+- **WHEN** an advertised invocation or mutation returns a scalar, enum, object, collection, or void value directly
+- **THEN** the context selects only children valid for that direct type and extracts the selected field value without assuming an envelope
+- **AND** preserves the documented scalar, object, collection, or void result kind
+
+#### Scenario: Action returns an object
+- **WHEN** an invocation returns an object bookmark and metadata
+- **THEN** the controller publishes a semantic object result containing that identity
+- **AND** host navigation policy decides whether to navigate
+
+#### Scenario: Action returns a scalar or collection
+- **WHEN** an invocation returns a scalar or collection
+- **THEN** the controller publishes a typed semantic result suitable for host or standard result presentation
+
+#### Scenario: Action returns void
+- **WHEN** an invocation succeeds without a value
+- **THEN** the controller publishes a successful void result
+- **AND** invalidates the owning object context when applicable
+
+#### Scenario: Result type lacks navigable metadata
+- **WHEN** a valid direct or polymorphic result can currently expose only a bounded non-navigable projection
+- **THEN** invocation success and the available typed result remain visible
+- **AND** the controller does not invent an object bookmark or claim navigable identity
+
+### Requirement: Local interaction error mapping
+Property and action interactions SHALL retain GraphQL validation, member, parameter, planning, invocation, and transport errors at the narrowest corresponding interaction scope.
+Expected action planning and execution failures MUST produce bounded safe interaction results rather than escaping solely to the controller's generic exception fallback.
+
+#### Scenario: Parameter-specific GraphQL error
+- **WHEN** an error path identifies one action parameter semantic field
+- **THEN** the prompt associates the error with that parameter
+- **AND** preserves successful state for other parameters
+
+#### Scenario: Invocation-level GraphQL error
+- **WHEN** an action invocation fails without a more specific member path
+- **THEN** the prompt presents a bounded mapped error at action level and remains available for correction or retry
+- **AND** preserves the GraphQL path and safe error code for diagnostics
+
+#### Scenario: Dispatch plan cannot satisfy the schema
+- **WHEN** the selected operation shape lacks a required declared argument or safe result projection
+- **THEN** the context returns a bounded action-planning error before execution
+- **AND** does not submit a partial or speculative operation
+
+#### Scenario: Protected parameter dispatch fails
+- **WHEN** planning, GraphQL execution, transport, cancellation, or result extraction fails after a protected parameter was entered
+- **THEN** rendered errors, semantic events, diagnostics, and operation summaries omit the submitted protected value
+- **AND** the prompt retains only the existing safe write-only pending representation
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/tasks.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/tasks.md
new file mode 100644
index 00000000000..3ff67b7ee67
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/tasks.md
@@ -0,0 +1,74 @@
+## 1. Capture the executable operation-shape baseline
+
+- [ ] 1.1 Record targeted introspection for the Reference Application parameterless `demo.ActionChoicesMenu.choices` service action, including its nested invocation and result shape.
+- [ ] 1.2 Record targeted introspection for representative safe, idempotent, and mutating object actions with and without parameters.
+- [ ] 1.3 Record the generated top-level mutation fields, declared target arguments, parameter arguments, and direct or enveloped result types for those actions.
+- [ ] 1.4 Add a focused failing foundation fixture for the nested executable shape that currently produces `Action invocation failed`.
+- [ ] 1.5 Add focused failing fixtures proving that an advertised flat mutation must be preferred over a legacy nested `invokeNonIdempotent` field.
+- [ ] 1.6 Publish the reviewed object and service operation-shape matrix as reproducible change evidence.
+
+## 2. Implement shared introspection-driven dispatch planning
+
+- [ ] 2.1 Add an immutable shared invocation-plan model for target kind, operation placement, mutability, selected field, arguments, result projection, extraction, and outcome type.
+- [ ] 2.2 Select nested `invoke` or `invokeIdempotent` only for advertised safe or idempotent query execution.
+- [ ] 2.3 Inspect the mutation root independently and prefer an advertised generated top-level mutation for mutating actions.
+- [ ] 2.4 Retain nested `invokeNonIdempotent` only as an explicit compatibility fallback when no corresponding mutation field exists.
+- [ ] 2.5 Map pending values only to arguments declared by the selected invocation field.
+- [ ] 2.6 Resolve an object mutation's target argument from its advertised generated input type or target name and reject an unsatisfied required target before execution.
+- [ ] 2.7 Ensure service mutations never receive a manufactured object target.
+- [ ] 2.8 Return a bounded unsupported plan without constructing an operation when no executable placement exists.
+
+## 3. Derive safe result projection and extraction
+
+- [ ] 3.1 Detect and select an advertised `results` envelope without assuming that every nested invocation uses one.
+- [ ] 3.2 Support direct scalar, enum, object, collection, and void result fields without requesting child fields for scalar or void values.
+- [ ] 3.3 Select only fields advertised by a described direct object or established result envelope and never synthesize an absent `target` field.
+- [ ] 3.4 Preserve valid `__typename`-only bounded output when general polymorphic metadata projection remains unavailable.
+- [ ] 3.5 Normalize direct and enveloped values through the existing object, collection, scalar, and void semantic result kinds.
+- [ ] 3.6 Reject an unsafe or undescribed required result projection with a bounded planning error before execution.
+
+## 4. Integrate object and service action contexts
+
+- [ ] 4.1 Route object action capability discovery and invocation through the shared dispatch planner.
+- [ ] 4.2 Route service action capability discovery and invocation through the same planner.
+- [ ] 4.3 Extend the GraphQL interaction operation builder only as needed for direct nested results and plan-defined extraction paths.
+- [ ] 4.4 Preserve current public context methods, GraphQL operation names, Causeway semantic events, and interaction result shapes.
+- [ ] 4.5 Preserve per-object and per-service mutation serialization and trigger authoritative refresh or change notification only after successful mutation.
+- [ ] 4.6 Preserve cancellation, disconnect, route replacement, and stale-generation checks so obsolete invocation results cannot update current state.
+- [ ] 4.7 Map expected capability, planning, GraphQL, invocation, and transport failures to bounded action-scoped interaction results before the controller's generic exception fallback.
+- [ ] 4.8 Verify protected action values remain absent from errors, diagnostics, semantic events, operation summaries, and rendered markup.
+
+## 5. Close the automated operation-shape matrix
+
+- [ ] 5.1 Add foundation tests for parameterless and parameterized nested safe and idempotent object actions.
+- [ ] 5.2 Add foundation tests for parameterless and parameterized nested safe and idempotent service actions.
+- [ ] 5.3 Add foundation tests for object and service top-level mutations, object target mapping, and mutation preference over a legacy nested field.
+- [ ] 5.4 Add foundation tests for the legacy nested mutating fallback and the no-executable-capability unsupported result.
+- [ ] 5.5 Add foundation tests for direct and enveloped scalar, object, collection, and void outcome normalization.
+- [ ] 5.6 Add negative tests for undeclared arguments, missing required target mapping, absent result fields, bounded errors, cancellation, stale completion, and protected-value redaction.
+- [ ] 5.7 Keep existing Petclinic object and service action interaction tests passing without changing their public selectors or event assertions.
+
+## 6. Qualify against GraphQL and the pinned Reference Application
+
+- [ ] 6.1 Add GraphQL integration assertions that the recorded nested safe and flat mutation operations execute successfully against authoritative fixtures.
+- [ ] 6.2 Replace the Reference Application `demo.ActionChoicesMenu.choices` visible-failure assertion with a successful parameterless service-action outcome and host navigation or presentation assertion.
+- [ ] 6.3 Add a successful parameterized object-action journey whose identity metadata is already complete, while retaining versionless-action failures for the next focused change.
+- [ ] 6.4 Cover valid, invalid, cancelled, stale, scalar, object, collection, and void action outcomes through representative Reference Application targets.
+- [ ] 6.5 Update the capability inventory and stable target catalogue only where focused executable evidence changes the reviewed classification.
+- [ ] 6.6 Prove clean and incremental inventory generation remain byte-identical after classification updates.
+
+## 7. Document compatibility and production isolation
+
+- [ ] 7.1 Document nested safe-query, top-level mutation, and legacy nested-mutation fallback behavior for semantic action contexts.
+- [ ] 7.2 Publish reproduction steps, operation-shape evidence, before-and-after results, and any intentionally retained identity or union gaps.
+- [ ] 7.3 Verify no Maven or npm dependency, public GraphQL field or operation name, Causeway element, semantic event name, canonical route, or browser asset URL changes.
+- [ ] 7.4 Verify Vaadin bundle inputs, CSP hashes, route-lazy loading, native fallback, and default-selection policy remain unchanged.
+
+## 8. Run final qualification gates
+
+- [ ] 8.1 Run the complete foundation Node suite and web-component foundation and HTMX Maven tests.
+- [ ] 8.2 Run GraphQL model and relevant integration tests for nested query and flat mutation action execution.
+- [ ] 8.3 Run the full Petclinic integration and Playwright suites.
+- [ ] 8.4 Run the Reference Application clean package, integration, capability inventory, and Playwright suites.
+- [ ] 8.5 Run strict CSP, accessibility, keyboard, light, dark, narrow, reduced-motion, forced-colors, external-request, console-error, page-error, and overflow gates.
+- [ ] 8.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
diff --git a/openspec/planned-changes/web-component-viewer/README.md b/openspec/planned-changes/web-component-viewer/README.md
index 83aef5fdad1..4d6c23f1bde 100644
--- a/openspec/planned-changes/web-component-viewer/README.md
+++ b/openspec/planned-changes/web-component-viewer/README.md
@@ -3,8 +3,9 @@
This directory contains complete follow-on changes and evidence-gated proposal-only drafts for the Causeway web-component viewer programme.
They are held outside `openspec/changes/` because the repository permits only one active OpenSpec change at a time.
The foundation, domain-component, rich GraphQL correctness, value-semantics, collection-windowing, application-entry, composite-object, menubar, generic HTMX, theming, Vaadin evaluation, and Vaadin reference-widget pilot changes are archived.
-The current active change is `add-referenceapp-webcomponent-regression-suite`.
-Its broad capability inventory precedes the proposal-only Vaadin-default sequence in `vaadin-default-roadmap.md`.
+The Reference Application regression suite and input-value hardening changes are archived.
+The current active change is `fix-webcomponent-action-dispatch-correctness`, the remaining Priority 0 correction identified by that broad capability inventory.
+Focused versionless-identity, union-projection, and opaque-route corrections precede the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
The older Vue, Svelte, metadata, diagnostics, performance-analysis, catalogue, and designer drafts remain queued behind that higher-priority qualification and default-adoption work.
Complete child directories contain `.openspec.yaml`, `proposal.md`, `design.md`, `tasks.md`, and delta specifications and can be promoted verbatim after review.
diff --git a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
index 1b52854f172..6314ea3b62d 100644
--- a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
+++ b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
@@ -5,15 +5,19 @@ Causeway elements, events, GraphQL contexts, canonical routes, and application-o
Native semantic editors remain rollback and fail-safe implementations, and default selection does not imply eager asset delivery.
The repository permits one active OpenSpec change at a time.
-The following proposal-only drafts are deliberately sequenced behind `add-referenceapp-webcomponent-regression-suite` and must be refined against its checked-in capability inventory before promotion.
+The Reference Application suite and input-value hardening are archived.
+The active `fix-webcomponent-action-dispatch-correctness` change is the remaining Priority 0 correctness tranche identified by the pinned regression corpus.
+Proposal-only drafts must be refined against checked-in capability evidence before promotion.
| Order | Proposal | Purpose | Promotion gate |
|---:|---|---|---|
-| 1 | `add-referenceapp-webcomponent-regression-suite` | Copy the pinned broad corpus, establish deterministic inventory, and expose real gaps. | Active change completes with reviewed classifications. |
-| 2 | `harden-webcomponent-input-value-semantics` | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Reference Application identifies concrete affected shapes and stable fixtures. |
-| 3 | `add-paged-graphql-reference-autocomplete` | Add honest server-side reference windows for large datasets. | Public GraphQL operation and ordering contract are accepted. |
-| 4 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
-| 5 | `make-vaadin-default-for-webcomponent-viewer` | Flip the supported selection policy to Vaadin-first and remove pilot status. | All prerequisite suites pass in default and explicit native modes. |
+| 1 | `add-referenceapp-webcomponent-regression-suite` *(archived)* | Copy the pinned broad corpus, establish deterministic inventory, and expose real gaps. | Completed with reviewed classifications. |
+| 2 | `harden-webcomponent-input-value-semantics` *(archived)* | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Completed against stable Reference Application fixtures. |
+| 3 | `fix-webcomponent-action-dispatch-correctness` *(active)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Reference Application action failures become successful typed interactions without changing public operations. |
+| 4 | Focused identity, union-projection, and opaque-route changes | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling. | Each retained gap has an executable focused contract and passing regression target. |
+| 5 | `add-paged-graphql-reference-autocomplete` | Add honest server-side reference windows for large datasets. | Public GraphQL operation, identity, preparation, and ordering contracts are accepted. |
+| 6 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
+| 7 | `make-vaadin-default-for-webcomponent-viewer` | Flip the supported selection policy to Vaadin-first and remove pilot status. | All prerequisite suites pass in default and explicit native modes. |
The final default change is intentionally small and policy-focused.
Correctness, GraphQL capability, and component-family expansion remain separate so failures do not become entangled with the default flip.
(causeway) 03/15: archives web component action dispatch correction
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit 745c42364fdb43cc846755cf245055d58d7c03ba
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 10:51:32 2026 +0100
archives web component action dispatch correction
---
.../.openspec.yaml | 0
.../design.md | 0
.../evidence/REPRODUCING.md | 0
.../evidence/final-gate-results.md | 0
.../evidence/implementation-report.md | 0
.../evidence/operation-shape-matrix.md | 0
.../evidence/production-isolation.md | 0
.../proposal.md | 0
.../specs/domain-web-components/spec.md | 0
.../tasks.md | 0
.../planned-changes/web-component-viewer/README.md | 4 +-
.../web-component-viewer/vaadin-default-roadmap.md | 5 +-
openspec/specs/domain-web-components/spec.md | 75 ++++++++++++++++++----
13 files changed, 68 insertions(+), 16 deletions(-)
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/.openspec.yaml b/openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/.openspec.yaml
similarity index 100%
rename from openspec/changes/fix-webcomponent-action-dispatch-correctness/.openspec.yaml
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/.openspec.yaml
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/design.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/design.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-action-dispatch-correctness/design.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/design.md
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/REPRODUCING.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/REPRODUCING.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/REPRODUCING.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/REPRODUCING.md
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/final-gate-results.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/final-gate-results.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/final-gate-results.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/final-gate-results.md
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/implementation-report.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/implementation-report.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/implementation-report.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/implementation-report.md
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/operation-shape-matrix.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/operation-shape-matrix.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/operation-shape-matrix.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/operation-shape-matrix.md
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/production-isolation.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/production-isolation.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/production-isolation.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/evidence/production-isolation.md
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/proposal.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/proposal.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-action-dispatch-correctness/proposal.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/proposal.md
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/specs/domain-web-components/spec.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/specs/domain-web-components/spec.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-action-dispatch-correctness/specs/domain-web-components/spec.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/specs/domain-web-components/spec.md
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/tasks.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/tasks.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-action-dispatch-correctness/tasks.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-action-dispatch-correctness/tasks.md
diff --git a/openspec/planned-changes/web-component-viewer/README.md b/openspec/planned-changes/web-component-viewer/README.md
index 4d6c23f1bde..ce85134be4a 100644
--- a/openspec/planned-changes/web-component-viewer/README.md
+++ b/openspec/planned-changes/web-component-viewer/README.md
@@ -4,8 +4,8 @@ This directory contains complete follow-on changes and evidence-gated proposal-o
They are held outside `openspec/changes/` because the repository permits only one active OpenSpec change at a time.
The foundation, domain-component, rich GraphQL correctness, value-semantics, collection-windowing, application-entry, composite-object, menubar, generic HTMX, theming, Vaadin evaluation, and Vaadin reference-widget pilot changes are archived.
The Reference Application regression suite and input-value hardening changes are archived.
-The current active change is `fix-webcomponent-action-dispatch-correctness`, the remaining Priority 0 correction identified by that broad capability inventory.
-Focused versionless-identity, union-projection, and opaque-route corrections precede the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
+The action-dispatch correctness change is archived, completing the remaining Priority 0 correction identified by that broad capability inventory.
+The next change should be a focused versionless-identity and preparation correction, followed by separate union-projection and opaque-route corrections before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
The older Vue, Svelte, metadata, diagnostics, performance-analysis, catalogue, and designer drafts remain queued behind that higher-priority qualification and default-adoption work.
Complete child directories contain `.openspec.yaml`, `proposal.md`, `design.md`, `tasks.md`, and delta specifications and can be promoted verbatim after review.
diff --git a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
index 6314ea3b62d..2bab7ff6c08 100644
--- a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
+++ b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
@@ -6,14 +6,15 @@ Native semantic editors remain rollback and fail-safe implementations, and defau
The repository permits one active OpenSpec change at a time.
The Reference Application suite and input-value hardening are archived.
-The active `fix-webcomponent-action-dispatch-correctness` change is the remaining Priority 0 correctness tranche identified by the pinned regression corpus.
+The archived `fix-webcomponent-action-dispatch-correctness` change completed the remaining Priority 0 correctness tranche identified by the pinned regression corpus.
+The next change should isolate versionless identity and preparation before separate union-projection and opaque-route corrections.
Proposal-only drafts must be refined against checked-in capability evidence before promotion.
| Order | Proposal | Purpose | Promotion gate |
|---:|---|---|---|
| 1 | `add-referenceapp-webcomponent-regression-suite` *(archived)* | Copy the pinned broad corpus, establish deterministic inventory, and expose real gaps. | Completed with reviewed classifications. |
| 2 | `harden-webcomponent-input-value-semantics` *(archived)* | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Completed against stable Reference Application fixtures. |
-| 3 | `fix-webcomponent-action-dispatch-correctness` *(active)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Reference Application action failures become successful typed interactions without changing public operations. |
+| 3 | `fix-webcomponent-action-dispatch-correctness` *(archived)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Completed with successful typed Reference Application interactions and unchanged public operations. |
| 4 | Focused identity, union-projection, and opaque-route changes | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling. | Each retained gap has an executable focused contract and passing regression target. |
| 5 | `add-paged-graphql-reference-autocomplete` | Add honest server-side reference windows for large datasets. | Public GraphQL operation, identity, preparation, and ordering contracts are accepted. |
| 6 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
diff --git a/openspec/specs/domain-web-components/spec.md b/openspec/specs/domain-web-components/spec.md
index df5f66d970e..161bd5eef06 100644
--- a/openspec/specs/domain-web-components/spec.md
+++ b/openspec/specs/domain-web-components/spec.md
@@ -340,23 +340,57 @@ The standard action prompt SHALL support parameter hidden state, disabled state,
- **THEN** the prompt discards that response without replacing newer suggestions
### Requirement: Action argument validation and invocation
-The action interaction controller SHALL validate the pending argument set and invoke the action through the semantically correct query or mutation capability exposed by the configured schema.
+The action interaction controller SHALL validate the pending argument set and invoke an object or service action through the semantically correct nested query or top-level mutation capability exposed by targeted introspection.
+The context MUST emit only arguments declared by the selected field, MUST supply object target identity only through an advertised target argument, and MUST NOT issue an invalid operation when no executable capability exists.
#### Scenario: Invalid argument set
- **WHEN** rich action validation rejects one or more pending arguments
- **THEN** the prompt presents the mapped validation reasons
- **AND** does not invoke the action
-#### Scenario: Safe action invocation
-- **WHEN** a valid safe action is submitted
-- **THEN** the context executes the action through its advertised safe invocation capability
+#### Scenario: Parameterless nested service action
+- **WHEN** a parameterless service action advertises a nested safe or idempotent invocation field
+- **THEN** the service context executes that field beneath the advertised service query path without manufacturing variables or an object target
+- **AND** publishes the resulting semantic outcome instead of `Action invocation failed`
-#### Scenario: Mutating action invocation
-- **WHEN** a valid mutating action is submitted and a top-level mutation is available
-- **THEN** the context executes that mutation rather than relying on a non-spec-compliant mutating query
+#### Scenario: Parameterized nested object action
+- **WHEN** a valid object action advertises a nested safe or idempotent invocation field with declared parameters
+- **THEN** the object context sends the codec-produced pending values only through matching declared arguments
+- **AND** preserves the current object identity through the enclosing object lookup
+
+#### Scenario: Mutating object action has a top-level mutation
+- **WHEN** a valid mutating object action advertises a generated top-level mutation field
+- **THEN** the context executes that mutation and supplies the current bookmark through its declared target argument
+- **AND** does not select a legacy nested mutating query merely because `invokeNonIdempotent` is also advertised
+
+#### Scenario: Mutating service action has a top-level mutation
+- **WHEN** a valid mutating service action advertises a generated top-level mutation field
+- **THEN** the service context executes that mutation with only its declared action arguments
+- **AND** does not manufacture an object target
+
+#### Scenario: Only a legacy mutating invocation is available
+- **WHEN** a supported API variant exposes `invokeNonIdempotent` but no corresponding top-level mutation
+- **THEN** the context may use the legacy nested capability as an explicit compatibility fallback
+- **AND** reports the selected placement through its inspectable operation result
+
+#### Scenario: Advertised action has no executable placement
+- **WHEN** targeted introspection exposes action state or parameter fields but no supported invocation field or mutation
+- **THEN** preparation or invocation returns a bounded unsupported interaction result
+- **AND** no invalid GraphQL request is issued
### Requirement: Semantic action outcomes
-The interaction layer SHALL normalize object, collection, scalar, and void action outcomes and publish them through framework-neutral semantic events.
+The interaction layer SHALL derive action result selection and extraction from the advertised output type and SHALL normalize object, collection, scalar, and void outcomes through framework-neutral semantic events.
+It MUST NOT request a synthetic `results`, `target`, metadata, or child field that the effective result type does not advertise.
+
+#### Scenario: Invocation uses a results envelope
+- **WHEN** an advertised nested invocation output contains a `results` field
+- **THEN** the context selects and extracts that field using its described type
+- **AND** normalizes the extracted value through the semantic result contract
+
+#### Scenario: Invocation returns a direct value
+- **WHEN** an advertised invocation or mutation returns a scalar, enum, object, collection, or void value directly
+- **THEN** the context selects only children valid for that direct type and extracts the selected field value without assuming an envelope
+- **AND** preserves the documented scalar, object, collection, or void result kind
#### Scenario: Action returns an object
- **WHEN** an invocation returns an object bookmark and metadata
@@ -370,7 +404,12 @@ The interaction layer SHALL normalize object, collection, scalar, and void actio
#### Scenario: Action returns void
- **WHEN** an invocation succeeds without a value
- **THEN** the controller publishes a successful void result
-- **AND** invalidates the owning object context
+- **AND** invalidates the owning object context when applicable
+
+#### Scenario: Result type lacks navigable metadata
+- **WHEN** a valid direct or polymorphic result can currently expose only a bounded non-navigable projection
+- **THEN** invocation success and the available typed result remain visible
+- **AND** the controller does not invent an object bookmark or claim navigable identity
### Requirement: Interaction concurrency and cancellation
The object context SHALL serialize mutating commands for one object and SHALL prevent obsolete transient semantic responses from replacing newer interaction state.
@@ -384,16 +423,28 @@ The object context SHALL serialize mutating commands for one object and SHALL pr
- **THEN** the obsolete response is discarded
### Requirement: Local interaction error mapping
-Property and action interactions SHALL retain GraphQL validation, member, parameter, invocation, and transport errors at the narrowest corresponding interaction scope.
+Property and action interactions SHALL retain GraphQL validation, member, parameter, planning, invocation, and transport errors at the narrowest corresponding interaction scope.
+Expected action planning and execution failures MUST produce bounded safe interaction results rather than escaping solely to the controller's generic exception fallback.
#### Scenario: Parameter-specific GraphQL error
- **WHEN** an error path identifies one action parameter semantic field
- **THEN** the prompt associates the error with that parameter
- **AND** preserves successful state for other parameters
-#### Scenario: Invocation-level error
+#### Scenario: Invocation-level GraphQL error
- **WHEN** an action invocation fails without a more specific member path
-- **THEN** the prompt presents the error at action level and remains available for correction or retry
+- **THEN** the prompt presents a bounded mapped error at action level and remains available for correction or retry
+- **AND** preserves the GraphQL path and safe error code for diagnostics
+
+#### Scenario: Dispatch plan cannot satisfy the schema
+- **WHEN** the selected operation shape lacks a required declared argument or safe result projection
+- **THEN** the context returns a bounded action-planning error before execution
+- **AND** does not submit a partial or speculative operation
+
+#### Scenario: Protected parameter dispatch fails
+- **WHEN** planning, GraphQL execution, transport, cancellation, or result extraction fails after a protected parameter was entered
+- **THEN** rendered errors, semantic events, diagnostics, and operation summaries omit the submitted protected value
+- **AND** the prompt retains only the existing safe write-only pending representation
### Requirement: Explicit interaction enablement
The interaction layer SHALL preserve existing read-only rendering unless an application explicitly enables property editing or installs a standard interaction controller.
(causeway) 12/15: archives opaque bookmark route correction
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit e208807dd55a86dea7a2c54c8b35ba69597793dc
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 14:45:00 2026 +0100
archives opaque bookmark route correction
---
.../.openspec.yaml | 0
.../design.md | 0
.../evidence/REPRODUCING.md | 0
.../evidence/final-gate-results.md | 0
.../evidence/implementation-report.md | 0
.../evidence/production-isolation.md | 0
.../evidence/route-bound-matrix.md | 0
.../proposal.md | 0
.../generic-htmx-web-component-viewer/spec.md | 0
.../spec.md | 0
.../tasks.md | 0
.../planned-changes/web-component-viewer/README.md | 3 ++-
.../web-component-viewer/vaadin-default-roadmap.md | 4 ++--
.../generic-htmx-web-component-viewer/spec.md | 14 +++++++++----
.../spec.md | 24 ++++++++++++++++++++++
15 files changed, 38 insertions(+), 7 deletions(-)
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/.openspec.yaml b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/.openspec.yaml
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/.openspec.yaml
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/.openspec.yaml
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/design.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/design.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/design.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/design.md
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/REPRODUCING.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/REPRODUCING.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/REPRODUCING.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/REPRODUCING.md
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/final-gate-results.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/final-gate-results.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/final-gate-results.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/final-gate-results.md
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/implementation-report.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/implementation-report.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/implementation-report.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/implementation-report.md
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/production-isolation.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/production-isolation.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/production-isolation.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/production-isolation.md
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/route-bound-matrix.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/route-bound-matrix.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/evidence/route-bound-matrix.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/evidence/route-bound-matrix.md
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/proposal.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/proposal.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/proposal.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/proposal.md
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/specs/generic-htmx-web-component-viewer/spec.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/specs/generic-htmx-web-component-viewer/spec.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/specs/generic-htmx-web-component-viewer/spec.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/specs/generic-htmx-web-component-viewer/spec.md
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/specs/reference-application-viewer-regression-suite/spec.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/specs/reference-application-viewer-regression-suite/spec.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/specs/reference-application-viewer-regression-suite/spec.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/specs/reference-application-viewer-regression-suite/spec.md
diff --git a/openspec/changes/fix-webcomponent-opaque-route-correctness/tasks.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/tasks.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-opaque-route-correctness/tasks.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-opaque-route-correctness/tasks.md
diff --git a/openspec/planned-changes/web-component-viewer/README.md b/openspec/planned-changes/web-component-viewer/README.md
index 85c16e6c8e2..d6b17ec15ed 100644
--- a/openspec/planned-changes/web-component-viewer/README.md
+++ b/openspec/planned-changes/web-component-viewer/README.md
@@ -7,7 +7,8 @@ The Reference Application regression suite and input-value hardening changes are
The action-dispatch correctness change is archived, completing the remaining Priority 0 correction identified by that broad capability inventory.
The versionless-identity and preparation correction is archived.
The union-projection correction is archived.
-The active `fix-webcomponent-opaque-route-correctness` change addresses long authoritative bookmarks before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
+The opaque-route correction is archived.
+The next change should add paged GraphQL reference autocomplete before the Vaadin expansion and default sequence in `vaadin-default-roadmap.md`.
The older Vue, Svelte, metadata, diagnostics, performance-analysis, catalogue, and designer drafts remain queued behind that higher-priority qualification and default-adoption work.
Complete child directories contain `.openspec.yaml`, `proposal.md`, `design.md`, `tasks.md`, and delta specifications and can be promoted verbatim after review.
diff --git a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
index 0b5aff3d9c6..43da121f83c 100644
--- a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
+++ b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
@@ -8,7 +8,7 @@ The repository permits one active OpenSpec change at a time.
The Reference Application suite and input-value hardening are archived.
The archived `fix-webcomponent-action-dispatch-correctness` change completed the remaining Priority 0 correctness tranche identified by the pinned regression corpus.
The archived `fix-webcomponent-versionless-identity-preparation` change isolates concrete versionless identity.
-The archived `fix-webcomponent-union-projection-correctness` change precedes the active `fix-webcomponent-opaque-route-correctness` correction.
+The versionless identity, union projection, and opaque-route correctness prerequisites are archived.
Proposal-only drafts must be refined against checked-in capability evidence before promotion.
| Order | Proposal | Purpose | Promotion gate |
@@ -16,7 +16,7 @@ Proposal-only drafts must be refined against checked-in capability evidence befo
| 1 | `add-referenceapp-webcomponent-regression-suite` *(archived)* | Copy the pinned broad corpus, establish deterministic inventory, and expose real gaps. | Completed with reviewed classifications. |
| 2 | `harden-webcomponent-input-value-semantics` *(archived)* | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Completed against stable Reference Application fixtures. |
| 3 | `fix-webcomponent-action-dispatch-correctness` *(archived)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Completed with successful typed Reference Application interactions and unchanged public operations. |
-| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, `fix-webcomponent-union-projection-correctness` *(archived)*, `fix-webcomponent-opaque-route-correctness` *(active)* | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
+| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, `fix-webcomponent-union-projection-correctness` *(archived)*, `fix-webcomponent-opaque-route-correctness` *(archived)* | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
| 5 | `add-paged-graphql-reference-autocomplete` | Add honest server-side reference windows for large datasets. | Public GraphQL operation, identity, preparation, and ordering contracts are accepted. |
| 6 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
| 7 | `make-vaadin-default-for-webcomponent-viewer` | Flip the supported selection policy to Vaadin-first and remove pilot status. | All prerequisite suites pass in default and explicit native modes. |
diff --git a/openspec/specs/generic-htmx-web-component-viewer/spec.md b/openspec/specs/generic-htmx-web-component-viewer/spec.md
index ca5bf03f843..68885341c4c 100644
--- a/openspec/specs/generic-htmx-web-component-viewer/spec.md
+++ b/openspec/specs/generic-htmx-web-component-viewer/spec.md
@@ -18,21 +18,27 @@ The project SHALL provide an explicitly enabled generic HTMX viewer whose primar
### Requirement: Canonical bookmark routing
The viewer SHALL map a public logical type and opaque object identifier to one documented round-trippable route grammar beneath a configurable base path.
+Each browser-generated and server-parsed segment MUST use the same canonical UTF-8 percent encoding and MUST remain within the documented encoded-segment bound without interpreting or altering identifier content.
#### Scenario: Direct object route is requested
- **WHEN** `<base-path>/object/<logical-type>/<identifier>` contains independently canonical percent-encoded route segments
-- **THEN** the router renders the object page for that logical route identity
+- **THEN** the router renders the object page for that exact logical route identity
- **AND** browser history represents the same canonical route
#### Scenario: Semantic navigation is requested
- **WHEN** a component publishes an object navigation or object-result event
-- **THEN** default route policy constructs the same canonical route
+- **THEN** default route policy constructs the same canonical route from the exact advertised identity
- **AND** HTMX replaces only the route region while pushing that route into browser history
+#### Scenario: Long authoritative identifier remains within the route bound
+- **WHEN** GraphQL returns a valid opaque identifier longer than the former decoded-character limit whose canonical encoded segment remains within the documented bound
+- **THEN** browser and server codecs preserve and round-trip the identifier exactly
+- **AND** direct load, HTMX replacement, history restoration, back, and forward reconstruct the same object context
+
#### Scenario: Route encoding is invalid
-- **WHEN** a route contains malformed escapes, empty values, encoded separators, control characters, dot segments, overlong values, or a non-canonical encoding
+- **WHEN** a route contains malformed escapes, empty values, encoded separators, control characters, dot segments, malformed Unicode, overlong encoded segments, or a non-canonical encoding
- **THEN** the viewer presents a bounded invalid-route state
-- **AND** does not disclose object state, authorization rules, or raw decoder exceptions
+- **AND** does not disclose object state, authorization rules, submitted route content, or raw decoder exceptions
#### Scenario: Viewer is mounted elsewhere
- **WHEN** an application configures a valid non-root base path
diff --git a/openspec/specs/reference-application-viewer-regression-suite/spec.md b/openspec/specs/reference-application-viewer-regression-suite/spec.md
index cd68fb014b9..83d75cfb3ed 100644
--- a/openspec/specs/reference-application-viewer-regression-suite/spec.md
+++ b/openspec/specs/reference-application-viewer-regression-suite/spec.md
@@ -174,3 +174,27 @@ It MUST preserve deterministic concrete-row evidence, bounded schema mismatch be
- **WHEN** a projected concrete result carries the long opaque identifier retained by the corpus
- **THEN** the suite continues to assert the focused `invalid-route` gap
- **AND** does not attribute route rejection to union projection
+
+### Requirement: Opaque bookmark route regression coverage
+The pinned Reference Application suite SHALL exercise the authoritative long memento identifier returned for `demo.CompositeValuesPage` through the generic HTMX canonical route.
+It MUST preserve the exact identifier, distinguish corrected routing from object-read failures, and retain unrelated bounded invalid-route behavior.
+
+#### Scenario: Composite-values result is routed
+- **WHEN** `demo.CompositeValueTypeMenu.compositeValueTypes` returns the `demo.CompositeValuesPage` identity
+- **THEN** its exact opaque identifier produces a canonical HTMX object route within the supported encoded bound
+- **AND** the route reaches ready or documented partial object state instead of `invalid-route`
+
+#### Scenario: Composite-values route reconstructs identity
+- **WHEN** the server renders the canonical composite-values route
+- **THEN** the route object context contains the same logical type and byte-for-byte identifier returned by GraphQL
+- **AND** representative composite value content remains visible through the authoritative object read
+
+#### Scenario: Composite-values history is traversed
+- **WHEN** navigation replaces the active object route with the composite-values route and the browser traverses back and forward
+- **THEN** each history entry restores its exact canonical logical identity and route state
+- **AND** stale work from the replaced route cannot overwrite the restored context
+
+#### Scenario: Malformed route remains bounded
+- **WHEN** the same qualification run requests malformed escapes, separators, controls, non-canonical encoding, or a segment beyond the supported encoded bound
+- **THEN** the viewer retains its non-disclosing `invalid-route` presentation
+- **AND** successful long opaque routing does not weaken route validation
(causeway) 06/15: archives versionless web component identity correction
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit 7237730fb43f4702f4d075ebdb524dc81c6839c7
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 12:24:36 2026 +0100
archives versionless web component identity correction
---
.../.openspec.yaml | 0
.../design.md | 0
.../evidence/REPRODUCING.md | 0
.../evidence/final-gate-results.md | 0
.../evidence/implementation-report.md | 0
.../evidence/metadata-shape-matrix.md | 0
.../evidence/production-isolation.md | 0
.../proposal.md | 0
.../specs/domain-web-components/spec.md | 0
.../spec.md | 0
.../tasks.md | 0
.../planned-changes/web-component-viewer/README.md | 3 +-
.../web-component-viewer/vaadin-default-roadmap.md | 5 ++--
openspec/specs/domain-web-components/spec.md | 34 ++++++++++++++++++++++
.../spec.md | 24 +++++++++++++++
15 files changed, 63 insertions(+), 3 deletions(-)
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/.openspec.yaml b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/.openspec.yaml
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/.openspec.yaml
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/.openspec.yaml
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/design.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/design.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/design.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/design.md
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/REPRODUCING.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/REPRODUCING.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/REPRODUCING.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/REPRODUCING.md
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/final-gate-results.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/final-gate-results.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/final-gate-results.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/final-gate-results.md
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/implementation-report.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/implementation-report.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/implementation-report.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/implementation-report.md
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/metadata-shape-matrix.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/metadata-shape-matrix.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/metadata-shape-matrix.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/metadata-shape-matrix.md
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/production-isolation.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/production-isolation.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/evidence/production-isolation.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/evidence/production-isolation.md
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/proposal.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/proposal.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/proposal.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/proposal.md
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/specs/domain-web-components/spec.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/specs/domain-web-components/spec.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/specs/domain-web-components/spec.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/specs/domain-web-components/spec.md
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/specs/reference-application-viewer-regression-suite/spec.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/specs/reference-application-viewer-regression-suite/spec.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/specs/reference-application-viewer-regression-suite/spec.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/specs/reference-application-viewer-regression-suite/spec.md
diff --git a/openspec/changes/fix-webcomponent-versionless-identity-preparation/tasks.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/tasks.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-versionless-identity-preparation/tasks.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-versionless-identity-preparation/tasks.md
diff --git a/openspec/planned-changes/web-component-viewer/README.md b/openspec/planned-changes/web-component-viewer/README.md
index b111d394730..c5bdce7d7db 100644
--- a/openspec/planned-changes/web-component-viewer/README.md
+++ b/openspec/planned-changes/web-component-viewer/README.md
@@ -5,7 +5,8 @@ They are held outside `openspec/changes/` because the repository permits only on
The foundation, domain-component, rich GraphQL correctness, value-semantics, collection-windowing, application-entry, composite-object, menubar, generic HTMX, theming, Vaadin evaluation, and Vaadin reference-widget pilot changes are archived.
The Reference Application regression suite and input-value hardening changes are archived.
The action-dispatch correctness change is archived, completing the remaining Priority 0 correction identified by that broad capability inventory.
-The current active change is `fix-webcomponent-versionless-identity-preparation`, followed by separate union-projection and opaque-route corrections before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
+The versionless-identity and preparation correction is archived.
+The next change should be a focused union-projection correction, followed by opaque-route handling before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
The older Vue, Svelte, metadata, diagnostics, performance-analysis, catalogue, and designer drafts remain queued behind that higher-priority qualification and default-adoption work.
Complete child directories contain `.openspec.yaml`, `proposal.md`, `design.md`, `tasks.md`, and delta specifications and can be promoted verbatim after review.
diff --git a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
index 2421b0b409e..14a79b20fc0 100644
--- a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
+++ b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
@@ -7,7 +7,8 @@ Native semantic editors remain rollback and fail-safe implementations, and defau
The repository permits one active OpenSpec change at a time.
The Reference Application suite and input-value hardening are archived.
The archived `fix-webcomponent-action-dispatch-correctness` change completed the remaining Priority 0 correctness tranche identified by the pinned regression corpus.
-The active `fix-webcomponent-versionless-identity-preparation` change isolates concrete versionless identity before separate union-projection and opaque-route corrections.
+The archived `fix-webcomponent-versionless-identity-preparation` change isolates concrete versionless identity.
+The next change should correct union projection before the separate opaque-route correction.
Proposal-only drafts must be refined against checked-in capability evidence before promotion.
| Order | Proposal | Purpose | Promotion gate |
@@ -15,7 +16,7 @@ Proposal-only drafts must be refined against checked-in capability evidence befo
| 1 | `add-referenceapp-webcomponent-regression-suite` *(archived)* | Copy the pinned broad corpus, establish deterministic inventory, and expose real gaps. | Completed with reviewed classifications. |
| 2 | `harden-webcomponent-input-value-semantics` *(archived)* | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Completed against stable Reference Application fixtures. |
| 3 | `fix-webcomponent-action-dispatch-correctness` *(archived)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Completed with successful typed Reference Application interactions and unchanged public operations. |
-| 4 | `fix-webcomponent-versionless-identity-preparation` *(active)*, then focused union-projection and opaque-route changes | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
+| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, then focused union-projection and opaque-route changes | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
| 5 | `add-paged-graphql-reference-autocomplete` | Add honest server-side reference windows for large datasets. | Public GraphQL operation, identity, preparation, and ordering contracts are accepted. |
| 6 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
| 7 | `make-vaadin-default-for-webcomponent-viewer` | Flip the supported selection policy to Vaadin-first and remove pilot status. | All prerequisite suites pass in default and explicit native modes. |
diff --git a/openspec/specs/domain-web-components/spec.md b/openspec/specs/domain-web-components/spec.md
index 161bd5eef06..57e7486a6b4 100644
--- a/openspec/specs/domain-web-components/spec.md
+++ b/openspec/specs/domain-web-components/spec.md
@@ -931,3 +931,37 @@ Only successful server results may replace authoritative state, and obsolete, ca
- **WHEN** a newer edit, cancellation, disconnect, or route replacement supersedes validation or mutation work
- **THEN** the obsolete result is ignored or aborted
- **AND** no stale value or protected input leaks into the current component state
+
+### Requirement: Advertised semantic identity projection
+The component library SHALL derive metadata selection for concrete object values and rows from the effective metadata type advertised by targeted introspection.
+It MUST preserve advertised identity and presentation fields, MUST treat `version` as optional, and MUST NOT request, synthesize, or infer absent metadata fields.
+
+#### Scenario: Versioned object value is read
+- **WHEN** a concrete property, choice, autocomplete result, preparation value, action result, or collection row advertises `id`, `logicalTypeName`, `title`, and `version`
+- **THEN** the operation selects those advertised fields
+- **AND** the semantic value preserves the returned version
+
+#### Scenario: Versionless object value is read
+- **WHEN** a concrete property, choice, autocomplete result, preparation value, action result, or collection row advertises `id`, `logicalTypeName`, and `title` but not `version`
+- **THEN** the operation omits `version`
+- **AND** the value remains available for supported rendering, pending-value conversion, validation, hydration, refresh, and navigation
+
+#### Scenario: Metadata lacks semantic identity minimums
+- **WHEN** an effective metadata type does not advertise both `id` and `logicalTypeName`
+- **THEN** the component does not claim a navigable bookmark or hydratable object identity
+- **AND** it exposes only a valid bounded projection or the existing local unsupported state
+
+#### Scenario: Versionless value participates in preparation
+- **WHEN** a property or action parameter preparation field returns a concrete versionless object through default, choices, autocomplete, validity, or datatype semantics
+- **THEN** the context selects only metadata fields advertised for that object
+- **AND** cancellation and stale-response protection remain unchanged
+
+#### Scenario: Versionless collection rows are loaded
+- **WHEN** a concrete collection element type advertises semantic identity without `version`
+- **THEN** row selection merges the advertised identity fields with requested semantic columns
+- **AND** the rows remain hydratable without manufacturing a concurrency token
+
+#### Scenario: Abstract row type requires fragments
+- **WHEN** an interface or union row cannot expose semantic metadata without concrete fragments
+- **THEN** the component retains a bounded non-navigable or partial-error result
+- **AND** does not treat versionless concrete-object support as general union-projection support
diff --git a/openspec/specs/reference-application-viewer-regression-suite/spec.md b/openspec/specs/reference-application-viewer-regression-suite/spec.md
index d00324d1865..75021813932 100644
--- a/openspec/specs/reference-application-viewer-regression-suite/spec.md
+++ b/openspec/specs/reference-application-viewer-regression-suite/spec.md
@@ -116,3 +116,27 @@ The report MUST distinguish discovery from remediation and MUST identify focused
- **WHEN** a framework, GraphQL, viewer, dependency, or corpus update changes a previously accepted outcome
- **THEN** the suite identifies the semantic category and representative target that regressed
- **AND** a maintainer can reproduce it without the external Reference Application repository
+
+### Requirement: Versionless identity regression coverage
+The pinned Reference Application suite SHALL exercise representative concrete view models and collection rows whose rich metadata omits `version` while preserving stable semantic identity.
+It MUST distinguish corrected versionless projection behavior from retained polymorphic-union and opaque-route gaps.
+
+#### Scenario: Versionless preparation target is exercised
+- **WHEN** the browser prepares representative action or property interaction semantics that return concrete versionless values
+- **THEN** defaults, choices, autocomplete, validation, and successful submission remain usable without a missing-version GraphQL error
+- **AND** invalid, cancelled, and stale interactions retain their established behavior
+
+#### Scenario: Versionless property or action result is rendered
+- **WHEN** a representative concrete view model is returned as a property value or typed action outcome
+- **THEN** its advertised identity and title remain renderable and navigable through existing semantic contracts
+- **AND** no `_meta.version` selection is submitted for its versionless metadata type
+
+#### Scenario: Versionless collection row is rendered
+- **WHEN** a representative concrete view-model collection is activated
+- **THEN** its row window reaches the supported ready or documented partial state with stable identities and requested columns
+- **AND** a missing version field is not the cause of any row error
+
+#### Scenario: Unrelated retained gaps remain classified
+- **WHEN** the same qualification run reaches a polymorphic union target or a long opaque composite bookmark
+- **THEN** the suite retains the corresponding bounded known-gap assertion until its focused change is implemented
+- **AND** does not count it as evidence that concrete versionless identity failed
(causeway) 02/15: fixes web component action dispatch correctness
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit bb612cda335ddc5419630590eb40c6f5c87e8e4d
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 10:49:51 2026 +0100
fixes web component action dispatch correctness
---
.../design.md | 8 +-
.../evidence/REPRODUCING.md | 42 ++++
.../evidence/final-gate-results.md | 25 +++
.../evidence/implementation-report.md | 37 ++++
.../evidence/operation-shape-matrix.md | 44 +++++
.../evidence/production-isolation.md | 15 ++
.../tasks.md | 102 +++++-----
.../htmx/ReferenceAppHtmxPlaywrightTest.java | 37 ++--
.../ReferenceAppHtmxApplication_IntegTest.java | 53 +++++
viewers/webcomponents/foundation/USAGE.adoc | 7 +-
.../foundation/src/action-dispatch.mjs | 217 ++++++++++++++++++++
.../foundation/src/interaction-operations.mjs | 13 +-
.../foundation/src/object-context-controller.mjs | 159 ++++++++-------
.../foundation/src/service-action-context.mjs | 144 ++++++++------
.../foundation/test/action-dispatch.test.mjs | 218 +++++++++++++++++++++
.../test/application-menu-client.test.mjs | 18 ++
.../test/fixtures/menu-graphql-fixture.mjs | 26 ++-
17 files changed, 956 insertions(+), 209 deletions(-)
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/design.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/design.md
index 92e31029cd2..8570659da90 100644
--- a/openspec/changes/fix-webcomponent-action-dispatch-correctness/design.md
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/design.md
@@ -9,8 +9,9 @@ The object context treats any nested invocation field, including `invokeNonIdemp
Both contexts assume that nested invocation returns an envelope with `results`, and otherwise request a `target` field even when the effective return type does not advertise one.
Those assumptions can make operation rendering throw before execution, after which the standard controller can report only `Action invocation failed`.
-The pinned Reference Application preserves an executable parameterless service action that demonstrates the nested safe-dispatch defect.
-Its object actions also provide parameter, validation, mutation, outcome, cancellation, and stale-response fixtures for closing the operation-shape matrix.
+The pinned Reference Application preserves an executable parameterless service action whose wrapper has no nested invocation field and whose generated mutation returns a versionless view model directly.
+The current direct-result projection requests the absent `_meta.version` field and collapses the operation-rendering failure into `Action invocation failed`.
+Its object actions also provide nested safe envelopes, direct mutations, parameters, validation, outcomes, cancellation, and stale-response fixtures for closing the operation-shape matrix.
Public GraphQL remains authoritative, and this change must preserve Causeway elements, semantic events, typed value codecs, route policy, mutation serialization, strict CSP, and native or Vaadin editor independence.
## Goals / Non-Goals
@@ -114,4 +115,5 @@ Rollback consists of reverting the shared planner integration; no schema, persis
## Open Questions
No architectural question blocks implementation.
-Implementation evidence must identify the exact direct or enveloped result shape used by each Reference Application target before its known-gap assertion is converted.
+Implementation evidence confirms that `demo.ActionChoicesMenu.choices` uses the parameterless mutation `demo_ActionChoicesMenu__choices` and returns `rich__demo_ActionChoices` directly with versionless metadata.
+The remaining implementation evidence must record each selected object-action shape before its known-gap assertion is converted.
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/REPRODUCING.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/REPRODUCING.md
new file mode 100644
index 00000000000..43992633203
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/REPRODUCING.md
@@ -0,0 +1,42 @@
+# Reproducing action dispatch qualification
+
+Use JDK 25 and the repository Maven wrapper or Maven installation configured for this checkout.
+The Reference Application modules intentionally skip installation by default, so local standalone launch preparation must explicitly override that policy.
+
+```shell
+mvn -f regressiontests/pom.xml -N -Dmaven.install.skip=false install
+mvn -f regressiontests/referenceapp/pom.xml -N -Dmaven.install.skip=false install
+mvn -f regressiontests/referenceapp/pom.xml -DskipTests -Dmaven.install.skip=false install
+```
+
+Run the foundation operation-shape matrix:
+
+```shell
+node --test viewers/webcomponents/foundation/test/action-dispatch.test.mjs
+node --test viewers/webcomponents/foundation/test/application-menu-client.test.mjs
+```
+
+Run the complete foundation suite:
+
+```shell
+cd viewers/webcomponents/foundation
+node --test
+```
+
+Run the focused Reference Application browser journey:
+
+```shell
+mvn -f viewers/webcomponents/pom.xml -pl foundation,htmx -am -DskipTests install
+mvn -f regressiontests/referenceapp/pom.xml \
+ -Preferenceapp-playwright \
+ -Dtest=ReferenceAppHtmxPlaywrightTest#menusChoicesAutocompleteCancellationAndRouteDisposal \
+ -Dsurefire.failIfNoSpecifiedTests=false \
+ test
+```
+
+The first service action must navigate to `demo.ActionChoices` without opening an error prompt.
+The parameterized `selectTvCharacter` mutation must accept one advertised choice, close its prompt, and retain the authoritative route.
+The shell and unrelated routes must continue to make zero Vaadin candidate-bundle requests.
+
+For targeted introspection, start the application with `run-referenceapp-htmx`, wait until a small `__type` query succeeds, and inspect only the named service, object, action-wrapper, result, and mutation types listed in `operation-shape-matrix.md`.
+Broad schema introspection is neither required nor used by the viewer.
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/final-gate-results.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/final-gate-results.md
new file mode 100644
index 00000000000..a2affbc6d92
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/final-gate-results.md
@@ -0,0 +1,25 @@
+# Final gate results
+
+## Passed
+
+- Foundation Node suite: 129 tests passed with zero failures.
+- Web-component foundation and HTMX Maven tests: `BUILD SUCCESS`.
+- GraphQL model reactor and tests: `BUILD SUCCESS`.
+- Pinned Reference Application direct service and parameterized object mutation integration: `BUILD SUCCESS`.
+- Petclinic integration and Playwright reactor: `BUILD SUCCESS`.
+- Petclinic Playwright: 4 tests passed with zero failures, errors, or skips.
+- Reference Application ordinary clean package, integration tests, inventory tests, and deterministic fixtures: `BUILD SUCCESS`.
+- Reference Application Playwright: 9 tests passed with zero failures, errors, or skips.
+- Vaadin production-like pilot: 5 scenarios with zero axe, CSP, console, page, external-request, or overflow failures.
+- GraphQL model and Reference Application RAT checks: `BUILD SUCCESS`.
+- New foundation source and test modules are approved as Apache License 2.0 by RAT.
+- Strict OpenSpec validation and `git diff --check`: passed.
+
+## Compatibility results
+
+No dependency manifest changed.
+No public GraphQL name, Causeway element, context method, semantic event name, canonical route, history policy, or browser asset URL changed.
+No Vaadin bundle input, generated bundle, checksum, CSP hash, qualification policy, lazy-loading trigger, native fallback, or default-selection policy changed.
+
+The standalone foundation RAT goal still reports the same pre-existing `vaadin-reference/README.adoc` and generated `vaadin-reference.js` files as unknown-license resources.
+Neither file is introduced or modified by this change, and RAT explicitly approves both newly added action-dispatch files.
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/implementation-report.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/implementation-report.md
new file mode 100644
index 00000000000..0d9723d937d
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/implementation-report.md
@@ -0,0 +1,37 @@
+# Action dispatch implementation report
+
+## Implemented boundary
+
+Object and service action contexts now share an immutable introspection-driven invocation plan.
+The plan records target kind, placement, mutability, selected field, mutation field, object target argument, declared arguments, result selection, extraction path, and effective outcome type.
+
+Nested `invoke` and `invokeIdempotent` fields remain query placements.
+An advertised generated top-level mutation is preferred over `invokeNonIdempotent`.
+The legacy nested mutating field remains available only when no corresponding mutation exists.
+Object targets are supplied only through a declared compatible target argument, and service actions never receive an object target.
+
+Direct scalar, enum, object, collection, and void results no longer require a fabricated envelope.
+An advertised `results` envelope remains supported and is extracted explicitly.
+Object metadata projection is derived from the effective metadata type, so versionless view models omit `_meta.version` rather than failing operation rendering.
+General union-fragment metadata projection remains deferred.
+
+Expected planning and execution failures return bounded action-scoped results.
+Protected action failures redact errors and operation variables while retaining the executable document shape for safe diagnostics.
+Cancellation and stale controller generations retain their existing behavior, and only successful mutating plans trigger authoritative refresh or service change notification.
+
+## Closed Reference Application failures
+
+`demo.ActionChoicesMenu.choices` now executes its parameterless flat mutation and navigates to the returned `demo.ActionChoices` object without opening an error prompt.
+`demo.ActionChoices.selectTvCharacter` now prepares its reference choices, submits the selected typed identity through the generated mutation, closes the prompt, and keeps the authoritative logical route.
+`demo.ActionSemanticsVm.reportPropertyForSafe` now executes without a version-selection failure and completes through the host result policy.
+`demo.ActionSemanticsVm.updatePropertyForIdempotent` retains invalid-value validation and now accepts a valid value without a version-selection failure.
+
+The remaining known gaps concern general polymorphic union projections, opaque composite routes, and identity/preparation cases not resolved by selecting only advertised result metadata.
+They remain outside this Priority 0 change.
+
+## Automated coverage
+
+The foundation operation matrix covers nested safe and idempotent fields, direct object and service mutations, mutation preference, legacy fallback, declared arguments, object targets, missing targets, unsupported plans, direct results, envelopes, versionless metadata, and protected-value redaction.
+Real GraphQL integration covers the parameterless service mutation and parameterized object mutation against the pinned Reference Application.
+The Reference Application browser suite converts prior visible-failure assertions into successful semantic journeys while retaining invalid, cancellation, route-disposal, accessibility, responsive, CSP, and external-isolation coverage.
+Petclinic continues to cover complete-identity object actions and established public selectors and events.
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/operation-shape-matrix.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/operation-shape-matrix.md
new file mode 100644
index 00000000000..41ceab9575c
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/operation-shape-matrix.md
@@ -0,0 +1,44 @@
+# Reviewed action operation-shape matrix
+
+## Authoritative Reference Application shapes
+
+Targeted introspection was recorded against the pinned Reference Application with secured user `sven`.
+The public schema was not modified to obtain these shapes.
+
+| Target | Action wrapper | Executable placement | Arguments | Result |
+|---|---|---|---|---|
+| `demo.ActionChoicesMenu.choices` | `rich__demo_ActionChoicesMenu__choices__gqlv_action` advertises `hidden`, `disabled`, and `validate`, but no nested invocation field | Mutation `demo_ActionChoicesMenu__choices` | None | Direct `rich__demo_ActionChoices` |
+| `demo.ActionChoices.selectTvCharacter` | Wrapper advertises parameter state and validation, but no nested invocation field | Mutation `demo_ActionChoices__selectTvCharacter` | `_target: rich__demo_ActionChoices__gqlv_input`, `tvCharacter: rich__demo_DependentArgsDemoItem__gqlv_input` | Direct `rich__demo_ActionChoices` |
+| `demo.ActionChoices.selectTvCharacterByShow` | Wrapper advertises parameter state and validation, but no nested invocation field | Mutation `demo_ActionChoices__selectTvCharacterByShow` | `_target`, `tvShow`, `tvCharacter` | Direct `rich__demo_ActionChoices` |
+| `demo.ActionChoices.selectTvCharacters` | Wrapper advertises parameter state and validation, but no nested invocation field | Mutation `demo_ActionChoices__selectTvCharacters` | `_target`, `tvCharacters` | Direct `rich__demo_ActionChoices` |
+| `demo.ActionChoices.selectTvCharactersByShow` | Wrapper advertises nested `invoke` | Nested safe query | `tvShow`, `tvCharacters` through the nested field; object identity through the enclosing lookup | Envelope with `target`, `args`, and `results`; `results` is `rich__demo_ActionChoices` |
+| `demo.ActionChoices.selectTvCharactersByShows` | Wrapper advertises nested `invoke` | Nested safe query | `tvShows`, `tvCharacters` through the nested field; object identity through the enclosing lookup | Envelope with `target`, `args`, and `results`; `results` is `rich__demo_ActionChoices` |
+
+## Root cause confirmed
+
+`demo.ActionChoicesMenu.choices` is not a nested safe invocation.
+It is a parameterless flat mutation returning a view model directly.
+The returned `rich__demo_ActionChoices` metadata type advertises identity, logical type, and title but not every entity concurrency field.
+The previous generic result selector requested `_meta.version` unconditionally, so operation rendering failed before GraphQL execution and the interaction controller displayed only `Action invocation failed`.
+
+The corrected selector derives metadata children from the effective metadata type.
+The corrected dispatch planner also prevents an advertised legacy nested `invokeNonIdempotent` field from hiding an available top-level mutation.
+
+## Closed foundation matrix
+
+Foundation fixtures cover:
+
+- nested `invoke` and `invokeIdempotent` placement;
+- direct top-level object and service mutation placement;
+- top-level mutation preference over `invokeNonIdempotent`;
+- legacy nested mutation fallback when no root mutation exists;
+- object target argument discovery by generated input type;
+- absence of manufactured service targets;
+- direct scalar and direct versionless object results;
+- `results` envelopes;
+- required-argument and missing-target planning errors;
+- unsupported action plans;
+- omission of unadvertised metadata fields.
+
+General polymorphic union fragments remain outside this change.
+Versionless action preparation cases not solved by effective result selection remain candidates for the next identity-focused change.
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/production-isolation.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/production-isolation.md
new file mode 100644
index 00000000000..f40e5da578c
--- /dev/null
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/evidence/production-isolation.md
@@ -0,0 +1,15 @@
+# Production isolation verification
+
+No Maven POM, npm package manifest, lock file, dependency version, or third-party package changes are part of this implementation.
+No public GraphQL query, mutation, field, argument, scalar, input, output, or generated-name contract changes.
+The implementation consumes existing targeted introspection and existing executable fields.
+
+The public `<causeway-*>` vocabulary, context methods, semantic event names, event target details, typed result kinds, canonical routes, HTMX history policy, and browser asset URLs remain unchanged.
+The new action dispatch module is an internal same-origin foundation module packaged through the established source-module mechanism.
+
+No Vaadin package, generated bundle, checksum, CSP hash, qualification policy, route-lazy trigger, native fallback, or default-selection property changes.
+Routes that do not instantiate an eligible reference editor continue to request no Vaadin candidate bundle.
+Action parameters that do instantiate the qualified reference adapter continue to use the same Causeway-owned codec, identity, pending-value, validation, cancellation, and semantic event contracts.
+
+The corrected behavior is rollback-safe because it changes only client operation planning and safe result projection.
+Reverting the implementation requires no schema, persisted data, application configuration, route, or asset migration.
diff --git a/openspec/changes/fix-webcomponent-action-dispatch-correctness/tasks.md b/openspec/changes/fix-webcomponent-action-dispatch-correctness/tasks.md
index 3ff67b7ee67..0744ee4c52e 100644
--- a/openspec/changes/fix-webcomponent-action-dispatch-correctness/tasks.md
+++ b/openspec/changes/fix-webcomponent-action-dispatch-correctness/tasks.md
@@ -1,74 +1,74 @@
## 1. Capture the executable operation-shape baseline
-- [ ] 1.1 Record targeted introspection for the Reference Application parameterless `demo.ActionChoicesMenu.choices` service action, including its nested invocation and result shape.
-- [ ] 1.2 Record targeted introspection for representative safe, idempotent, and mutating object actions with and without parameters.
-- [ ] 1.3 Record the generated top-level mutation fields, declared target arguments, parameter arguments, and direct or enveloped result types for those actions.
-- [ ] 1.4 Add a focused failing foundation fixture for the nested executable shape that currently produces `Action invocation failed`.
-- [ ] 1.5 Add focused failing fixtures proving that an advertised flat mutation must be preferred over a legacy nested `invokeNonIdempotent` field.
-- [ ] 1.6 Publish the reviewed object and service operation-shape matrix as reproducible change evidence.
+- [x] 1.1 Record targeted introspection for the Reference Application parameterless `demo.ActionChoicesMenu.choices` service action, including its nested invocation and result shape.
+- [x] 1.2 Record targeted introspection for representative safe, idempotent, and mutating object actions with and without parameters.
+- [x] 1.3 Record the generated top-level mutation fields, declared target arguments, parameter arguments, and direct or enveloped result types for those actions.
+- [x] 1.4 Add a focused foundation fixture for the direct versionless mutation result shape that previously produced `Action invocation failed`.
+- [x] 1.5 Add focused failing fixtures proving that an advertised flat mutation must be preferred over a legacy nested `invokeNonIdempotent` field.
+- [x] 1.6 Publish the reviewed object and service operation-shape matrix as reproducible change evidence.
## 2. Implement shared introspection-driven dispatch planning
-- [ ] 2.1 Add an immutable shared invocation-plan model for target kind, operation placement, mutability, selected field, arguments, result projection, extraction, and outcome type.
-- [ ] 2.2 Select nested `invoke` or `invokeIdempotent` only for advertised safe or idempotent query execution.
-- [ ] 2.3 Inspect the mutation root independently and prefer an advertised generated top-level mutation for mutating actions.
-- [ ] 2.4 Retain nested `invokeNonIdempotent` only as an explicit compatibility fallback when no corresponding mutation field exists.
-- [ ] 2.5 Map pending values only to arguments declared by the selected invocation field.
-- [ ] 2.6 Resolve an object mutation's target argument from its advertised generated input type or target name and reject an unsatisfied required target before execution.
-- [ ] 2.7 Ensure service mutations never receive a manufactured object target.
-- [ ] 2.8 Return a bounded unsupported plan without constructing an operation when no executable placement exists.
+- [x] 2.1 Add an immutable shared invocation-plan model for target kind, operation placement, mutability, selected field, arguments, result projection, extraction, and outcome type.
+- [x] 2.2 Select nested `invoke` or `invokeIdempotent` only for advertised safe or idempotent query execution.
+- [x] 2.3 Inspect the mutation root independently and prefer an advertised generated top-level mutation for mutating actions.
+- [x] 2.4 Retain nested `invokeNonIdempotent` only as an explicit compatibility fallback when no corresponding mutation field exists.
+- [x] 2.5 Map pending values only to arguments declared by the selected invocation field.
+- [x] 2.6 Resolve an object mutation's target argument from its advertised generated input type or target name and reject an unsatisfied required target before execution.
+- [x] 2.7 Ensure service mutations never receive a manufactured object target.
+- [x] 2.8 Return a bounded unsupported plan without constructing an operation when no executable placement exists.
## 3. Derive safe result projection and extraction
-- [ ] 3.1 Detect and select an advertised `results` envelope without assuming that every nested invocation uses one.
-- [ ] 3.2 Support direct scalar, enum, object, collection, and void result fields without requesting child fields for scalar or void values.
-- [ ] 3.3 Select only fields advertised by a described direct object or established result envelope and never synthesize an absent `target` field.
-- [ ] 3.4 Preserve valid `__typename`-only bounded output when general polymorphic metadata projection remains unavailable.
-- [ ] 3.5 Normalize direct and enveloped values through the existing object, collection, scalar, and void semantic result kinds.
-- [ ] 3.6 Reject an unsafe or undescribed required result projection with a bounded planning error before execution.
+- [x] 3.1 Detect and select an advertised `results` envelope without assuming that every nested invocation uses one.
+- [x] 3.2 Support direct scalar, enum, object, collection, and void result fields without requesting child fields for scalar or void values.
+- [x] 3.3 Select only fields advertised by a described direct object or established result envelope and never synthesize an absent `target` field.
+- [x] 3.4 Preserve valid `__typename`-only bounded output when general polymorphic metadata projection remains unavailable.
+- [x] 3.5 Normalize direct and enveloped values through the existing object, collection, scalar, and void semantic result kinds.
+- [x] 3.6 Reject an unsafe or undescribed required result projection with a bounded planning error before execution.
## 4. Integrate object and service action contexts
-- [ ] 4.1 Route object action capability discovery and invocation through the shared dispatch planner.
-- [ ] 4.2 Route service action capability discovery and invocation through the same planner.
-- [ ] 4.3 Extend the GraphQL interaction operation builder only as needed for direct nested results and plan-defined extraction paths.
-- [ ] 4.4 Preserve current public context methods, GraphQL operation names, Causeway semantic events, and interaction result shapes.
-- [ ] 4.5 Preserve per-object and per-service mutation serialization and trigger authoritative refresh or change notification only after successful mutation.
-- [ ] 4.6 Preserve cancellation, disconnect, route replacement, and stale-generation checks so obsolete invocation results cannot update current state.
-- [ ] 4.7 Map expected capability, planning, GraphQL, invocation, and transport failures to bounded action-scoped interaction results before the controller's generic exception fallback.
-- [ ] 4.8 Verify protected action values remain absent from errors, diagnostics, semantic events, operation summaries, and rendered markup.
+- [x] 4.1 Route object action capability discovery and invocation through the shared dispatch planner.
+- [x] 4.2 Route service action capability discovery and invocation through the same planner.
+- [x] 4.3 Extend the GraphQL interaction operation builder only as needed for direct nested results and plan-defined extraction paths.
+- [x] 4.4 Preserve current public context methods, GraphQL operation names, Causeway semantic events, and interaction result shapes.
+- [x] 4.5 Preserve per-object and per-service mutation serialization and trigger authoritative refresh or change notification only after successful mutation.
+- [x] 4.6 Preserve cancellation, disconnect, route replacement, and stale-generation checks so obsolete invocation results cannot update current state.
+- [x] 4.7 Map expected capability, planning, GraphQL, invocation, and transport failures to bounded action-scoped interaction results before the controller's generic exception fallback.
+- [x] 4.8 Verify protected action values remain absent from errors, diagnostics, semantic events, operation summaries, and rendered markup.
## 5. Close the automated operation-shape matrix
-- [ ] 5.1 Add foundation tests for parameterless and parameterized nested safe and idempotent object actions.
-- [ ] 5.2 Add foundation tests for parameterless and parameterized nested safe and idempotent service actions.
-- [ ] 5.3 Add foundation tests for object and service top-level mutations, object target mapping, and mutation preference over a legacy nested field.
-- [ ] 5.4 Add foundation tests for the legacy nested mutating fallback and the no-executable-capability unsupported result.
-- [ ] 5.5 Add foundation tests for direct and enveloped scalar, object, collection, and void outcome normalization.
-- [ ] 5.6 Add negative tests for undeclared arguments, missing required target mapping, absent result fields, bounded errors, cancellation, stale completion, and protected-value redaction.
-- [ ] 5.7 Keep existing Petclinic object and service action interaction tests passing without changing their public selectors or event assertions.
+- [x] 5.1 Add foundation tests for parameterless and parameterized nested safe and idempotent object actions.
+- [x] 5.2 Add foundation tests for parameterless and parameterized nested safe and idempotent service actions.
+- [x] 5.3 Add foundation tests for object and service top-level mutations, object target mapping, and mutation preference over a legacy nested field.
+- [x] 5.4 Add foundation tests for the legacy nested mutating fallback and the no-executable-capability unsupported result.
+- [x] 5.5 Add foundation tests for direct and enveloped scalar, object, collection, and void outcome normalization.
+- [x] 5.6 Add negative tests for undeclared arguments, missing required target mapping, absent result fields, bounded errors, cancellation, stale completion, and protected-value redaction.
+- [x] 5.7 Keep existing Petclinic object and service action interaction tests passing without changing their public selectors or event assertions.
## 6. Qualify against GraphQL and the pinned Reference Application
-- [ ] 6.1 Add GraphQL integration assertions that the recorded nested safe and flat mutation operations execute successfully against authoritative fixtures.
-- [ ] 6.2 Replace the Reference Application `demo.ActionChoicesMenu.choices` visible-failure assertion with a successful parameterless service-action outcome and host navigation or presentation assertion.
-- [ ] 6.3 Add a successful parameterized object-action journey whose identity metadata is already complete, while retaining versionless-action failures for the next focused change.
-- [ ] 6.4 Cover valid, invalid, cancelled, stale, scalar, object, collection, and void action outcomes through representative Reference Application targets.
-- [ ] 6.5 Update the capability inventory and stable target catalogue only where focused executable evidence changes the reviewed classification.
-- [ ] 6.6 Prove clean and incremental inventory generation remain byte-identical after classification updates.
+- [x] 6.1 Add GraphQL integration assertions that the recorded nested safe and flat mutation operations execute successfully against authoritative fixtures.
+- [x] 6.2 Replace the Reference Application `demo.ActionChoicesMenu.choices` visible-failure assertion with a successful parameterless service-action outcome and host navigation or presentation assertion.
+- [x] 6.3 Add a successful parameterized object-action journey whose identity metadata is already complete, while retaining versionless-action failures for the next focused change.
+- [x] 6.4 Cover valid, invalid, cancelled, stale, scalar, object, collection, and void action outcomes through representative Reference Application targets.
+- [x] 6.5 Update the capability inventory and stable target catalogue only where focused executable evidence changes the reviewed classification.
+- [x] 6.6 Prove clean and incremental inventory generation remain byte-identical after classification updates.
## 7. Document compatibility and production isolation
-- [ ] 7.1 Document nested safe-query, top-level mutation, and legacy nested-mutation fallback behavior for semantic action contexts.
-- [ ] 7.2 Publish reproduction steps, operation-shape evidence, before-and-after results, and any intentionally retained identity or union gaps.
-- [ ] 7.3 Verify no Maven or npm dependency, public GraphQL field or operation name, Causeway element, semantic event name, canonical route, or browser asset URL changes.
-- [ ] 7.4 Verify Vaadin bundle inputs, CSP hashes, route-lazy loading, native fallback, and default-selection policy remain unchanged.
+- [x] 7.1 Document nested safe-query, top-level mutation, and legacy nested-mutation fallback behavior for semantic action contexts.
+- [x] 7.2 Publish reproduction steps, operation-shape evidence, before-and-after results, and any intentionally retained identity or union gaps.
+- [x] 7.3 Verify no Maven or npm dependency, public GraphQL field or operation name, Causeway element, semantic event name, canonical route, or browser asset URL changes.
+- [x] 7.4 Verify Vaadin bundle inputs, CSP hashes, route-lazy loading, native fallback, and default-selection policy remain unchanged.
## 8. Run final qualification gates
-- [ ] 8.1 Run the complete foundation Node suite and web-component foundation and HTMX Maven tests.
-- [ ] 8.2 Run GraphQL model and relevant integration tests for nested query and flat mutation action execution.
-- [ ] 8.3 Run the full Petclinic integration and Playwright suites.
-- [ ] 8.4 Run the Reference Application clean package, integration, capability inventory, and Playwright suites.
-- [ ] 8.5 Run strict CSP, accessibility, keyboard, light, dark, narrow, reduced-motion, forced-colors, external-request, console-error, page-error, and overflow gates.
-- [ ] 8.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
+- [x] 8.1 Run the complete foundation Node suite and web-component foundation and HTMX Maven tests.
+- [x] 8.2 Run GraphQL model and relevant integration tests for nested query and flat mutation action execution.
+- [x] 8.3 Run the full Petclinic integration and Playwright suites.
+- [x] 8.4 Run the Reference Application clean package, integration, capability inventory, and Playwright suites.
+- [x] 8.5 Run strict CSP, accessibility, keyboard, light, dark, narrow, reduced-motion, forced-colors, external-request, console-error, page-error, and overflow gates.
+- [x] 8.6 Run applicable RAT checks, strict OpenSpec validation, `git diff --check`, and production-isolation verification.
diff --git a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
index 65e6f38c47f..b09623cda59 100644
--- a/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
+++ b/regressiontests/referenceapp/htmx/src/playwright/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxPlaywrightTest.java
@@ -113,25 +113,19 @@ void menusChoicesAutocompleteCancellationAndRouteDisposal() {
openMenu("Prog Model");
serviceAction("demo.ActionChoicesMenu", "choices").click();
- page.locator(PROMPT).waitFor();
- assertThat(page.locator(PROMPT + " .causeway-action-prompt-error").textContent())
- .contains("Action invocation failed");
- page.locator("[data-testid='action-prompt-cancel']").click();
- page.locator(PROMPT).waitFor(new Locator.WaitForOptions()
- .setState(com.microsoft.playwright.options.WaitForSelectorState.DETACHED));
-
- openObject("demo.ActionChoices", invokeViewModel("demo_ActionChoicesMenu", "choices", "rich__demo_ActionChoices"));
+ waitForLogicalType("demo.ActionChoices");
+ page.waitForFunction("() => ['ready', 'fallback', 'partial-error'].includes(document.querySelector('#causeway-route causeway-object')?.dataset.layoutState)");
+ assertThat(page.locator(PROMPT).count()).isZero();
final Locator invokingControl = objectAction("selectTvCharacter");
invokingControl.click();
waitForPrompt("selectTvCharacter");
- assertThat(page.locator(PROMPT + " .causeway-action-prompt-error").textContent())
- .contains("Field 'version' is unavailable");
- assertThat(candidateRequests()).isZero();
- page.locator("[data-testid='action-prompt-cancel']").click();
+ selectFirstAvailableChoice("tvCharacter");
+ submitPrompt();
page.locator(PROMPT).waitFor(new Locator.WaitForOptions()
.setState(com.microsoft.playwright.options.WaitForSelectorState.DETACHED));
- assertThat((Boolean) invokingControl.evaluate("element => element === document.activeElement")).isTrue();
+ waitForLogicalType("demo.ActionChoices");
+ assertThat(candidateRequests()).isZero();
openObject("demo.ActionAutoCompletePage", invokeViewModel(
"demo_ActionAutoCompleteMenu", "autoComplete", "rich__demo_ActionAutoCompletePage"));
@@ -304,16 +298,14 @@ void textMultilineNullableDisabledInvalidCancelledAndStalePropertyStatesRemainVi
}
@Test
- void parameterlessParameterizedDefaultValidationOutcomeAndVersionGapActionStatesRemainVisible() {
+ void parameterlessParameterizedDefaultValidationAndSuccessfulActionStatesRemainVisible() {
openObject("demo.ActionSemanticsVm", invokeViewModel(
"demo_ActionMenu", "semantics", "rich__demo_ActionSemanticsVm"));
+ page.evaluate("() => globalThis.__referenceAppActionContextBeforeInvoke = document.querySelector('#causeway-route causeway-object-context')");
objectAction("reportPropertyForSafe").click();
- page.locator(PROMPT).waitFor();
- assertThat(page.locator(PROMPT + " .causeway-action-prompt-error").textContent())
- .contains("Field 'version' is unavailable");
- page.locator("[data-testid='action-prompt-cancel']").click();
- page.locator(PROMPT).waitFor(new Locator.WaitForOptions()
- .setState(com.microsoft.playwright.options.WaitForSelectorState.DETACHED));
+ page.waitForFunction("() => document.querySelector('#causeway-route causeway-object-context') !== globalThis.__referenceAppActionContextBeforeInvoke");
+ waitForLogicalType("demo.ActionSemanticsVm");
+ assertThat(page.locator(PROMPT).count()).isZero();
final Locator update = objectAction("updatePropertyForIdempotent");
update.click();
@@ -333,12 +325,9 @@ void parameterlessParameterizedDefaultValidationOutcomeAndVersionGapActionStates
waitForPrompt("updatePropertyForIdempotent");
page.locator(parameter("value")).fill("37");
submitPrompt();
- page.waitForFunction("() => document.querySelector(\"dialog[data-testid='action-prompt'] .causeway-action-prompt-error\")?.textContent?.trim().length > 0");
- assertThat(page.locator(PROMPT + " .causeway-action-prompt-error").textContent())
- .contains("Field 'version' is unavailable");
- page.locator("[data-testid='action-prompt-cancel']").click();
page.locator(PROMPT).waitFor(new Locator.WaitForOptions()
.setState(com.microsoft.playwright.options.WaitForSelectorState.DETACHED));
+ waitForLogicalType("demo.ActionSemanticsVm");
}
@Test
diff --git a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
index 5683089c06b..767ada113b1 100644
--- a/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
+++ b/regressiontests/referenceapp/htmx/src/test/java/org/apache/causeway/regressiontests/referenceapp/htmx/ReferenceAppHtmxApplication_IntegTest.java
@@ -162,6 +162,59 @@ void exposesRepresentativeFixtureIdentityAndEffectiveGrid() throws Exception {
.doesNotContain("<bs:metadataError>");
}
+ @Test
+ void directServiceAndParameterizedObjectActionMutationsUseAdvertisedShapes() throws Exception {
+ final JsonNode opened = graphQL("""
+ mutation {
+ demo_ActionChoicesMenu__choices {
+ _meta { id logicalTypeName title }
+ }
+ }
+ """);
+ assertNoGraphQLErrors(opened);
+ final JsonNode metadata = opened.at("/data/demo_ActionChoicesMenu__choices/_meta");
+ assertThat(metadata.path("logicalTypeName").asText()).isEqualTo("demo.ActionChoices");
+ final String targetId = metadata.path("id").asText();
+ assertThat(targetId).isNotBlank();
+
+ final JsonNode prepared = graphQL("""
+ query {
+ rich {
+ demo_ActionChoices(object: {id: %s}) {
+ selectTvCharacter {
+ params {
+ tvCharacter {
+ choices { _meta { id logicalTypeName title } }
+ }
+ }
+ }
+ }
+ }
+ }
+ """.formatted(OBJECT_MAPPER.writeValueAsString(targetId)));
+ assertNoGraphQLErrors(prepared);
+ final String choiceId = prepared.at(
+ "/data/rich/demo_ActionChoices/selectTvCharacter/params/tvCharacter/choices/0/_meta/id").asText();
+ assertThat(choiceId).isNotBlank();
+
+ final JsonNode invoked = graphQL("""
+ mutation {
+ demo_ActionChoices__selectTvCharacter(
+ _target: {id: %s},
+ tvCharacter: {id: %s}) {
+ _meta { id logicalTypeName title }
+ }
+ }
+ """.formatted(
+ OBJECT_MAPPER.writeValueAsString(targetId),
+ OBJECT_MAPPER.writeValueAsString(choiceId)));
+ assertNoGraphQLErrors(invoked);
+ assertThat(invoked.at("/data/demo_ActionChoices__selectTvCharacter/_meta/id").asText())
+ .isNotBlank();
+ assertThat(invoked.at("/data/demo_ActionChoices__selectTvCharacter/_meta/logicalTypeName").asText())
+ .isEqualTo("demo.ActionChoices");
+ }
+
@Test
void exactDecimalPropertyMutationUsesAdvertisedStringAndRestoresFixture() throws Exception {
final JsonNode open = graphQL("""
diff --git a/viewers/webcomponents/foundation/USAGE.adoc b/viewers/webcomponents/foundation/USAGE.adoc
index 073ca9b47e3..10c39f938bd 100644
--- a/viewers/webcomponents/foundation/USAGE.adoc
+++ b/viewers/webcomponents/foundation/USAGE.adoc
@@ -408,8 +408,11 @@ Custom prompts must preserve labels, validation associations, pending announceme
Call `release()` and `releaseMoneyCodec()` when the overrides are no longer required.
The object context exposes `prepareAction`, `autoCompleteActionParameter`, `validateAction`, and `invokeAction` for those integrations.
-Safe actions use the advertised rich query invocation field.
-Mutating actions use the discovered top-level mutation when available, while a non-compliant query mutation is used only when that is the capability exposed by the configured API variant.
+Safe and idempotent actions use an advertised nested `invoke` or `invokeIdempotent` query field.
+Mutating object and service actions use the discovered top-level mutation when available, while nested `invokeNonIdempotent` remains an explicit compatibility fallback only when no corresponding mutation is advertised.
+The shared dispatch planner emits only declared arguments, resolves an object target through its advertised generated input argument, and never manufactures a service target.
+Nested result envelopes are selected through an advertised `results` field, while direct mutation and invocation results are projected from their effective scalar, enum, object, collection, or void type.
+Object metadata selection includes only fields advertised by the effective metadata type, so a versionless view model does not receive a speculative `_meta.version` selection.
Object, collection, scalar, and void outcomes are normalized and published through `causeway-action-result` without automatic navigation.
The standard controller may render a local result summary; host routing remains responsible for object-result navigation.
diff --git a/viewers/webcomponents/foundation/src/action-dispatch.mjs b/viewers/webcomponents/foundation/src/action-dispatch.mjs
new file mode 100644
index 00000000000..a00c31af4d9
--- /dev/null
+++ b/viewers/webcomponents/foundation/src/action-dispatch.mjs
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import {fieldsByName, namedType} from './introspection.mjs';
+import {argumentsFromValues, resultSelectionForType} from './interaction-operations.mjs';
+
+export const ActionInvocationPlacement = Object.freeze({
+ NESTED_QUERY: 'nested-query',
+ ROOT_MUTATION: 'root-mutation',
+ LEGACY_NESTED_MUTATION: 'legacy-nested-mutation'
+});
+
+export class ActionDispatchPlanError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.name = 'ActionDispatchPlanError';
+ this.code = code;
+ }
+}
+
+export function createActionInvocationPlan({
+ targetKind,
+ description,
+ descriptor,
+ mutationType = null,
+ mutationFieldName = null
+} = {}) {
+ const safeField = ['invoke', 'invokeIdempotent']
+ .map(name => descriptor?.fields?.get(name))
+ .find(Boolean) ?? null;
+ const legacyMutationField = descriptor?.fields?.get('invokeNonIdempotent') ?? null;
+ const rootMutationField = mutationType && mutationFieldName
+ ? fieldsByName(mutationType).get(mutationFieldName) ?? null
+ : null;
+
+ let placement;
+ let field;
+ if (safeField) {
+ placement = ActionInvocationPlacement.NESTED_QUERY;
+ field = safeField;
+ } else if (rootMutationField) {
+ placement = ActionInvocationPlacement.ROOT_MUTATION;
+ field = rootMutationField;
+ } else if (legacyMutationField) {
+ placement = ActionInvocationPlacement.LEGACY_NESTED_MUTATION;
+ field = legacyMutationField;
+ } else {
+ return Object.freeze({
+ supported: false,
+ targetKind,
+ placement: null,
+ mutating: false,
+ field: null,
+ fieldName: null,
+ mutationFieldName: null,
+ targetArgumentName: null
+ });
+ }
+
+ const mutating = placement !== ActionInvocationPlacement.NESTED_QUERY;
+ const targetArgumentName = placement === ActionInvocationPlacement.ROOT_MUTATION && targetKind === 'object'
+ ? findTargetArgument(field, description?.generatedInputTypeName)
+ : null;
+ if (placement === ActionInvocationPlacement.ROOT_MUTATION && targetKind === 'object' && !targetArgumentName) {
+ throw new ActionDispatchPlanError(
+ 'ACTION_TARGET_ARGUMENT_UNAVAILABLE',
+ 'The advertised object action mutation has no compatible target argument.');
+ }
+
+ return Object.freeze({
+ supported: true,
+ targetKind,
+ placement,
+ mutating,
+ field,
+ fieldName: field.name,
+ mutationFieldName: placement === ActionInvocationPlacement.ROOT_MUTATION ? mutationFieldName : null,
+ targetArgumentName
+ });
+}
+
+export function actionInvocationArguments(plan, values = {}, identity = null) {
+ if (!plan?.supported || !plan.field) {
+ throw new ActionDispatchPlanError('ACTION_INVOCATION_UNAVAILABLE', 'No executable action invocation is advertised.');
+ }
+ const args = argumentsFromValues(plan.field, values);
+ if (plan.targetArgumentName) {
+ if (!identity?.id) {
+ throw new ActionDispatchPlanError('ACTION_TARGET_IDENTITY_UNAVAILABLE', 'The object action target identity is unavailable.');
+ }
+ args[plan.targetArgumentName] = {id: identity.id};
+ }
+ for (const argument of plan.field.args ?? []) {
+ if (argument.type?.kind !== 'NON_NULL' || Object.prototype.hasOwnProperty.call(args, argument.name)) {
+ continue;
+ }
+ throw new ActionDispatchPlanError(
+ 'ACTION_REQUIRED_ARGUMENT_UNAVAILABLE',
+ `Required action argument '${argument.name}' is unavailable.`);
+ }
+ return args;
+}
+
+export async function ensureActionInvocationResultTypes(client, description, plan, signal) {
+ await ensureType(client, description, plan?.field?.type, signal);
+ const describedType = description.types.get(namedType(plan?.field?.type)) ?? null;
+ const resultsField = describedType ? fieldsByName(describedType).get('results') ?? null : null;
+ if (resultsField) {
+ await ensureType(client, description, resultsField.type, signal);
+ }
+}
+
+export function actionInvocationResultPlan(plan, types) {
+ if (!plan?.supported || !plan.field) {
+ throw new ActionDispatchPlanError('ACTION_INVOCATION_UNAVAILABLE', 'No executable action invocation is advertised.');
+ }
+ const directType = plan.field.type;
+ const describedType = types.get(namedType(directType)) ?? null;
+ const resultsField = describedType ? fieldsByName(describedType).get('results') ?? null : null;
+ if (resultsField) {
+ return Object.freeze({
+ selection: Object.freeze({results: resultSelectionForType(resultsField.type, types) ?? true}),
+ resultType: resultsField.type,
+ extractionPath: Object.freeze(['results'])
+ });
+ }
+ return Object.freeze({
+ selection: resultSelectionForType(directType, types) ?? true,
+ resultType: directType,
+ extractionPath: Object.freeze([])
+ });
+}
+
+export function extractActionInvocationResult(value, resultPlan) {
+ let current = value;
+ for (const segment of resultPlan?.extractionPath ?? []) {
+ current = current?.[segment] ?? null;
+ }
+ return current;
+}
+
+export function secureActionInvocationResult(result, parameters = []) {
+ if (!parameters.some(parameter => isProtectedType(parameter.inputType))) {
+ return result;
+ }
+ const operation = result?.operation
+ ? Object.freeze({
+ ...result.operation,
+ variables: Object.freeze(Object.fromEntries(
+ Object.keys(result.operation.variables ?? {}).map(name => [name, '<redacted>'])))
+ })
+ : null;
+ const errors = Object.freeze((result?.errors ?? []).map(error => Object.freeze({
+ message: 'Protected action input was not accepted.',
+ path: Object.freeze([...(error?.path ?? [])]),
+ extensions: Object.freeze({...error?.extensions, code: error?.extensions?.code ?? 'PROTECTED_ACTION_INPUT_FAILED'})
+ })));
+ return Object.freeze({...result, data: null, operation, errors});
+}
+
+async function ensureType(client, description, typeRef, signal) {
+ const typeName = namedType(typeRef);
+ if (!typeName || ['SCALAR', 'ENUM'].includes(innermostKind(typeRef))) {
+ return;
+ }
+ if (!description.types.has(typeName)) {
+ const described = await client.describeTypes([typeName], {signal});
+ const type = described.get(typeName);
+ if (type) {
+ description.types.set(typeName, type);
+ }
+ }
+ const type = description.types.get(typeName);
+ const metadataTypeName = namedType(fieldsByName(type).get('_meta')?.type);
+ if (metadataTypeName && !description.types.has(metadataTypeName)) {
+ const described = await client.describeTypes([metadataTypeName], {signal});
+ const metadataType = described.get(metadataTypeName);
+ if (metadataType) {
+ description.types.set(metadataTypeName, metadataType);
+ }
+ }
+}
+
+function innermostKind(typeRef) {
+ let current = typeRef;
+ while (current?.ofType) {
+ current = current.ofType;
+ }
+ return current?.kind ?? null;
+}
+
+function isProtectedType(typeRef) {
+ const typeName = namedType(typeRef)?.toLocaleLowerCase() ?? '';
+ return typeName.includes('password') || typeName.includes('protected');
+}
+
+function findTargetArgument(field, generatedInputTypeName) {
+ return field.args?.find(argument => namedType(argument.type) === generatedInputTypeName)?.name
+ ?? field.args?.find(argument => argument.name === '_target')?.name
+ ?? null;
+}
diff --git a/viewers/webcomponents/foundation/src/interaction-operations.mjs b/viewers/webcomponents/foundation/src/interaction-operations.mjs
index 1b814c2da68..c69c94a0189 100644
--- a/viewers/webcomponents/foundation/src/interaction-operations.mjs
+++ b/viewers/webcomponents/foundation/src/interaction-operations.mjs
@@ -194,8 +194,17 @@ export function resultSelectionForType(typeRef, types) {
return {__typename: true};
}
const fields = fieldsByName(typeDescription);
- if (fields.has('_meta')) {
- return {_meta: {id: true, logicalTypeName: true, title: true, version: true}};
+ const metadataField = fields.get('_meta');
+ const metadataType = metadataField ? types.get(namedType(metadataField.type)) ?? null : null;
+ if (metadataType) {
+ const metadataFields = fieldsByName(metadataType);
+ const metadataSelection = Object.fromEntries(
+ ['id', 'logicalTypeName', 'title', 'version']
+ .filter(fieldName => metadataFields.has(fieldName))
+ .map(fieldName => [fieldName, true]));
+ if (Object.keys(metadataSelection).length > 0) {
+ return {_meta: metadataSelection};
+ }
}
const scalarFields = typeDescription.fields
.filter(field => ['SCALAR', 'ENUM'].includes(innermostType(field.type)?.kind))
diff --git a/viewers/webcomponents/foundation/src/object-context-controller.mjs b/viewers/webcomponents/foundation/src/object-context-controller.mjs
index 2b146526187..541b46f5021 100644
--- a/viewers/webcomponents/foundation/src/object-context-controller.mjs
+++ b/viewers/webcomponents/foundation/src/object-context-controller.mjs
@@ -17,6 +17,14 @@
* under the License.
*/
+import {
+ actionInvocationArguments,
+ actionInvocationResultPlan,
+ createActionInvocationPlan,
+ ensureActionInvocationResultTypes,
+ extractActionInvocationResult,
+ secureActionInvocationResult
+} from './action-dispatch.mjs';
import {createSemanticEvent, OBJECT_CONTEXT_STATE_EVENT} from './context-events.mjs';
import {fieldsByName, namedType} from './introspection.mjs';
import {argumentsFromValues, commandSelection, resultSelectionForType} from './interaction-operations.mjs';
@@ -290,24 +298,45 @@ export class ObjectContextController extends EventTarget {
enumValues: Object.freeze(enumType?.enumValues?.map(value => value.name) ?? [])
});
});
- const invocationField = actionInvocationField(descriptor);
- const mutationType = invocationField ? null : await this.client.describeMutation();
+ const mutationType = await this.client.describeMutation();
const mutationFieldName = mutationFieldNameFor(description, member);
- const mutationField = mutationType ? fieldsByName(mutationType).get(mutationFieldName) ?? null : null;
+ let invocationPlan;
+ let planningError = null;
+ try {
+ invocationPlan = createActionInvocationPlan({
+ targetKind: 'object',
+ description,
+ descriptor,
+ mutationType,
+ mutationFieldName
+ });
+ } catch (error) {
+ invocationPlan = Object.freeze({supported: false});
+ planningError = commandError({
+ message: 'The advertised object action cannot be dispatched safely.',
+ extensions: {code: error?.code ?? 'ACTION_DISPATCH_PLAN_FAILED'}
+ });
+ }
return Object.freeze({
descriptor,
parameters: Object.freeze(parameters),
validate: Boolean(validateField),
- invocationField: invocationField?.name ?? null,
- mutationFieldName: mutationField ? mutationFieldName : null,
- invokable: Boolean(invocationField || mutationField)
+ invocationPlan,
+ invocationField: invocationPlan.placement === 'root-mutation' ? null : invocationPlan.fieldName ?? null,
+ mutationFieldName: invocationPlan.mutationFieldName ?? null,
+ mutating: invocationPlan.mutating ?? false,
+ planningError,
+ invokable: invocationPlan.supported === true
});
}
async prepareAction(member, values = {}, {signal} = {}) {
const capabilities = await this.describeActionInteraction(member);
if (!capabilities.invokable) {
- return interactionResult(InteractionStatus.UNSUPPORTED, {capabilities}, [commandError(`Action '${member}' does not expose an invocation capability.`)]);
+ return interactionResult(
+ capabilities.planningError ? InteractionStatus.FAILED : InteractionStatus.UNSUPPORTED,
+ {capabilities},
+ [capabilities.planningError ?? commandError(`Action '${member}' does not expose an invocation capability.`)]);
}
if (capabilities.parameters.length === 0) {
return interactionResult(InteractionStatus.SUCCESS, {capabilities, parameters: []});
@@ -410,63 +439,65 @@ export class ObjectContextController extends EventTarget {
});
}
- invokeAction(member, values = {}, {signal} = {}) {
- return this.#serializeMutation(async () => {
- const {description, descriptor} = await this.#memberDescriptor(member, 'action');
- const invocationField = actionInvocationField(descriptor);
- let result;
- let resultType;
- if (invocationField) {
- const invokeType = description.types.get(namedType(invocationField.type));
- const resultsField = invokeType ? fieldsByName(invokeType).get('results') : null;
- if (resultsField) {
- await ensureResultTypes(this.client, description, resultsField.type, signal);
+ async invokeAction(member, values = {}, {signal} = {}) {
+ const capabilities = await this.describeActionInteraction(member);
+ if (!capabilities.invokable) {
+ return interactionResult(
+ capabilities.planningError ? InteractionStatus.FAILED : InteractionStatus.UNSUPPORTED,
+ null,
+ [capabilities.planningError ?? commandError(`Action '${member}' does not expose an invocation capability.`)]);
+ }
+ const execute = async () => {
+ try {
+ const {description} = await this.#memberDescriptor(member, 'action');
+ const plan = capabilities.invocationPlan;
+ await ensureActionInvocationResultTypes(this.client, description, plan, signal);
+ const resultPlan = actionInvocationResultPlan(plan, description.types);
+ const args = actionInvocationArguments(plan, values, this.identity);
+ let result;
+ if (plan.placement === 'root-mutation') {
+ const mutationType = await this.client.describeMutation({signal});
+ result = await this.client.executeMutationInteraction({
+ description,
+ mutationType,
+ fieldName: plan.mutationFieldName,
+ args,
+ resultSelection: resultPlan.selection === true ? null : resultPlan.selection,
+ operationName: 'CausewayInvokeAction',
+ signal
+ });
+ } else {
+ result = await this.client.executeObjectInteraction({
+ description,
+ identity: this.identity,
+ selection: {
+ [member]: {
+ [plan.fieldName]: commandSelection(args, resultPlan.selection)
+ }
+ },
+ operationName: 'CausewayInvokeAction',
+ signal
+ });
+ const invocationValue = result.data?.[member]?.[plan.fieldName] ?? null;
+ result = {...result, data: extractActionInvocationResult(invocationValue, resultPlan)};
}
- const resultsSelection = resultsField ? resultSelectionForType(resultsField.type, description.types) : null;
- result = await this.client.executeObjectInteraction({
- description,
- identity: this.identity,
- selection: {
- [member]: {
- [invocationField.name]: commandSelection(
- argumentsFromValues(invocationField, values),
- resultsField ? {results: resultsSelection ?? true} : {target: true}
- )
- }
- },
- operationName: 'CausewayInvokeAction',
- signal
- });
- resultType = resultsField?.type ?? null;
- result = {...result, data: result.data?.[member]?.[invocationField.name]?.results ?? null};
- } else {
- const mutationType = await this.client.describeMutation({signal});
- const fieldName = mutationFieldNameFor(description, member);
- const mutationField = mutationType ? fieldsByName(mutationType).get(fieldName) : null;
- if (!mutationField) {
- return interactionResult(InteractionStatus.UNSUPPORTED, null, [commandError(`Action '${member}' does not expose an invocation mutation.`)]);
+ result = secureActionInvocationResult(result, capabilities.parameters);
+ const response = commandResponse(result, normalizeActionResult(result.data, resultPlan.resultType));
+ if (response.status === InteractionStatus.SUCCESS && plan.mutating) {
+ this.refresh();
}
- const targetArgument = targetArgumentName(mutationField, description.generatedInputTypeName);
- const args = argumentsFromValues(mutationField, values);
- args[targetArgument] = {id: this.identity.id};
- resultType = mutationField.type;
- await ensureResultTypes(this.client, description, resultType, signal);
- result = await this.client.executeMutationInteraction({
- description,
- mutationType,
- fieldName,
- args,
- resultSelection: resultSelectionForType(resultType, description.types),
- operationName: 'CausewayInvokeAction',
- signal
- });
- }
- const response = commandResponse(result, normalizeActionResult(result.data, resultType));
- if (response.status === InteractionStatus.SUCCESS) {
- this.refresh();
+ return response;
+ } catch (error) {
+ if (signal?.aborted) {
+ return interactionResult(InteractionStatus.OBSOLETE);
+ }
+ return interactionResult(InteractionStatus.FAILED, null, [commandError({
+ message: 'The object action could not be dispatched safely.',
+ extensions: {code: error?.code ?? 'ACTION_DISPATCH_FAILED'}
+ })]);
}
- return response;
- });
+ };
+ return capabilities.mutating ? this.#serializeMutation(execute) : execute();
}
async loadCollection({
@@ -942,12 +973,6 @@ function parameterInputType(wrapper) {
return null;
}
-function actionInvocationField(descriptor) {
- return ['invoke', 'invokeIdempotent', 'invokeNonIdempotent']
- .map(name => descriptor.fields.get(name))
- .find(Boolean) ?? null;
-}
-
function commandResponse(result, data) {
if (result.errors?.length) {
return interactionResult(InteractionStatus.FAILED, data, result.errors, result.operation);
diff --git a/viewers/webcomponents/foundation/src/service-action-context.mjs b/viewers/webcomponents/foundation/src/service-action-context.mjs
index 4e0cfe14dfe..f6c3fa929f0 100644
--- a/viewers/webcomponents/foundation/src/service-action-context.mjs
+++ b/viewers/webcomponents/foundation/src/service-action-context.mjs
@@ -17,6 +17,14 @@
* under the License.
*/
+import {
+ actionInvocationArguments,
+ actionInvocationResultPlan,
+ createActionInvocationPlan,
+ ensureActionInvocationResultTypes,
+ extractActionInvocationResult,
+ secureActionInvocationResult
+} from './action-dispatch.mjs';
import {fieldsByName, namedType} from './introspection.mjs';
import {argumentsFromValues, commandSelection, resultSelectionForType} from './interaction-operations.mjs';
import {InteractionResultKind, InteractionStatus} from './types.mjs';
@@ -112,7 +120,10 @@ export class ServiceActionContextController {
async prepareAction(actionId, values = {}, {signal} = {}) {
const capabilities = await this.describeActionInteraction(actionId);
if (!capabilities.invokable) {
- return interactionResult(InteractionStatus.UNSUPPORTED, {capabilities}, [commandError(`Service action '${actionId}' does not expose an invocation capability.`)]);
+ return interactionResult(
+ capabilities.planningError ? InteractionStatus.FAILED : InteractionStatus.UNSUPPORTED,
+ {capabilities},
+ [capabilities.planningError ?? commandError(`Service action '${actionId}' does not expose an invocation capability.`)]);
}
if (capabilities.parameters.length === 0) {
return interactionResult(InteractionStatus.SUCCESS, {capabilities, parameters: []});
@@ -215,56 +226,60 @@ export class ServiceActionContextController {
async invokeAction(actionId, values = {}, {signal} = {}) {
const capabilities = await this.describeActionInteraction(actionId);
+ if (!capabilities.invokable) {
+ return interactionResult(
+ capabilities.planningError ? InteractionStatus.FAILED : InteractionStatus.UNSUPPORTED,
+ null,
+ [capabilities.planningError ?? commandError(`Service action '${actionId}' does not expose an invocation capability.`)]);
+ }
const execute = async () => {
- const description = await this.describeService();
- let result;
- let resultType;
- if (capabilities.invocationField) {
- const invocationField = capabilities.invocationField;
- const invokeType = description.types.get(namedType(invocationField.type));
- const resultsField = invokeType ? fieldsByName(invokeType).get('results') : null;
- if (resultsField) {
- await ensureResultTypes(this.client, description, resultsField.type, signal);
+ try {
+ const description = await this.describeService();
+ const plan = capabilities.invocationPlan;
+ await ensureActionInvocationResultTypes(this.client, description, plan, signal);
+ const resultPlan = actionInvocationResultPlan(plan, description.types);
+ const args = actionInvocationArguments(plan, values);
+ let result;
+ if (plan.placement === 'root-mutation') {
+ const mutationType = await this.client.describeMutation({signal});
+ result = await this.client.executeMutationInteraction({
+ description,
+ mutationType,
+ fieldName: plan.mutationFieldName,
+ args,
+ resultSelection: resultPlan.selection === true ? null : resultPlan.selection,
+ operationName: 'CausewayInvokeServiceAction',
+ signal
+ });
+ } else {
+ result = await this.client.executeServiceInteraction({
+ description,
+ selection: {
+ [actionId]: {
+ [plan.fieldName]: commandSelection(args, resultPlan.selection)
+ }
+ },
+ operationName: 'CausewayInvokeServiceAction',
+ signal
+ });
+ const invocationValue = result.data?.[actionId]?.[plan.fieldName] ?? null;
+ result = {...result, data: extractActionInvocationResult(invocationValue, resultPlan)};
}
- const resultsSelection = resultsField ? resultSelectionForType(resultsField.type, description.types) : null;
- result = await this.client.executeServiceInteraction({
- description,
- selection: {
- [actionId]: {
- [invocationField.name]: commandSelection(
- argumentsFromValues(invocationField, values),
- resultsField ? {results: resultsSelection ?? true} : {target: true}
- )
- }
- },
- operationName: 'CausewayInvokeServiceAction',
- signal
- });
- resultType = resultsField?.type ?? null;
- result = {...result, data: result.data?.[actionId]?.[invocationField.name]?.results ?? null};
- } else {
- const mutationType = await this.client.describeMutation({signal});
- const mutationField = mutationType ? fieldsByName(mutationType).get(capabilities.mutationFieldName) : null;
- if (!mutationField) {
- return interactionResult(InteractionStatus.UNSUPPORTED, null, [commandError(`Service action '${actionId}' does not expose an invocation mutation.`)]);
+ result = secureActionInvocationResult(result, capabilities.parameters);
+ const response = commandResponse(result, normalizeActionResult(result.data, resultPlan.resultType));
+ if (response.status === InteractionStatus.SUCCESS && plan.mutating) {
+ this.onChanged();
}
- resultType = mutationField.type;
- await ensureResultTypes(this.client, description, resultType, signal);
- result = await this.client.executeMutationInteraction({
- description,
- mutationType,
- fieldName: capabilities.mutationFieldName,
- args: argumentsFromValues(mutationField, values),
- resultSelection: resultSelectionForType(resultType, description.types),
- operationName: 'CausewayInvokeServiceAction',
- signal
- });
- }
- const response = commandResponse(result, normalizeActionResult(result.data, resultType));
- if (response.status === InteractionStatus.SUCCESS && capabilities.mutating) {
- this.onChanged();
+ return response;
+ } catch (error) {
+ if (signal?.aborted) {
+ return interactionResult(InteractionStatus.OBSOLETE);
+ }
+ return interactionResult(InteractionStatus.FAILED, null, [commandError({
+ message: 'The service action could not be dispatched safely.',
+ extensions: {code: error?.code ?? 'ACTION_DISPATCH_FAILED'}
+ })]);
}
- return response;
};
return capabilities.mutating ? this.serializeMutation(execute) : execute();
}
@@ -300,22 +315,35 @@ export class ServiceActionContextController {
enumValues: Object.freeze(enumType?.enumValues?.map(value => value.name) ?? [])
});
});
- const invocationField = ['invoke', 'invokeIdempotent']
- .map(name => descriptor.fields.get(name))
- .find(Boolean) ?? null;
- const legacyMutatingField = descriptor.fields.get('invokeNonIdempotent') ?? null;
- const mutationType = invocationField ? null : await this.client.describeMutation();
+ const mutationType = await this.client.describeMutation();
const mutationFieldName = `${description.generatedFieldName}__${actionId}`;
- const mutationField = mutationType ? fieldsByName(mutationType).get(mutationFieldName) ?? null : null;
- const effectiveInvocationField = invocationField ?? (!mutationField ? legacyMutatingField : null);
+ let invocationPlan;
+ let planningError = null;
+ try {
+ invocationPlan = createActionInvocationPlan({
+ targetKind: 'service',
+ description,
+ descriptor,
+ mutationType,
+ mutationFieldName
+ });
+ } catch (error) {
+ invocationPlan = Object.freeze({supported: false});
+ planningError = commandError({
+ message: 'The advertised service action cannot be dispatched safely.',
+ extensions: {code: error?.code ?? 'ACTION_DISPATCH_PLAN_FAILED'}
+ });
+ }
return Object.freeze({
descriptor,
parameters: Object.freeze(parameters),
validate: Boolean(validateField),
- invocationField: effectiveInvocationField,
- mutationFieldName: mutationField ? mutationFieldName : null,
- mutating: Boolean(mutationField || legacyMutatingField && !invocationField),
- invokable: Boolean(effectiveInvocationField || mutationField)
+ invocationPlan,
+ invocationField: invocationPlan.placement === 'root-mutation' ? null : invocationPlan.field ?? null,
+ mutationFieldName: invocationPlan.mutationFieldName ?? null,
+ mutating: invocationPlan.mutating ?? false,
+ planningError,
+ invokable: invocationPlan.supported === true
});
}
diff --git a/viewers/webcomponents/foundation/test/action-dispatch.test.mjs b/viewers/webcomponents/foundation/test/action-dispatch.test.mjs
new file mode 100644
index 00000000000..04fc0dd0499
--- /dev/null
+++ b/viewers/webcomponents/foundation/test/action-dispatch.test.mjs
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ ActionDispatchPlanError,
+ ActionInvocationPlacement,
+ actionInvocationArguments,
+ actionInvocationResultPlan,
+ createActionInvocationPlan,
+ extractActionInvocationResult,
+ secureActionInvocationResult
+} from '../src/action-dispatch.mjs';
+import {resultSelectionForType} from '../src/interaction-operations.mjs';
+
+const scalar = name => ({kind: 'SCALAR', name, ofType: null});
+const object = name => ({kind: 'OBJECT', name, ofType: null});
+const nonNull = type => ({kind: 'NON_NULL', name: null, ofType: type});
+const argument = (name, type) => ({name, type});
+const field = (name, type, args = []) => ({name, type, args});
+const type = (name, fields, kind = 'OBJECT') => ({name, kind, fields, enumValues: [], possibleTypes: []});
+const descriptor = fields => ({fields: new Map(fields.map(candidate => [candidate.name, candidate]))});
+const description = (types = new Map()) => ({generatedInputTypeName: 'rich__sample_Target__gqlv_input', types});
+
+function mutationType(...fields) {
+ return type('Mutation', fields);
+}
+
+test('safe nested invocation takes its advertised query placement', () => {
+ const invoke = field('invokeIdempotent', object('SafeEnvelope'), [argument('name', scalar('String'))]);
+ const mutation = field('sample_Target__greet', scalar('String'), [argument('_target', object('rich__sample_Target__gqlv_input'))]);
+ const plan = createActionInvocationPlan({
+ targetKind: 'object',
+ description: description(),
+ descriptor: descriptor([invoke]),
+ mutationType: mutationType(mutation),
+ mutationFieldName: mutation.name
+ });
+
+ assert.equal(plan.placement, ActionInvocationPlacement.NESTED_QUERY);
+ assert.equal(plan.fieldName, 'invokeIdempotent');
+ assert.equal(plan.mutating, false);
+ assert.equal(plan.targetArgumentName, null);
+ assert.deepEqual(actionInvocationArguments(plan, {name: 'Ada', ignored: 'not-advertised'}, {id: 'target-1'}), {name: 'Ada'});
+});
+
+test('top-level mutation is preferred over legacy nested mutation', () => {
+ const legacy = field('invokeNonIdempotent', object('LegacyEnvelope'));
+ const mutation = field('sample_Target__update', object('rich__sample_Target'), [
+ argument('_target', nonNull(object('rich__sample_Target__gqlv_input'))),
+ argument('value', nonNull(scalar('String')))
+ ]);
+ const plan = createActionInvocationPlan({
+ targetKind: 'object',
+ description: description(),
+ descriptor: descriptor([legacy]),
+ mutationType: mutationType(mutation),
+ mutationFieldName: mutation.name
+ });
+
+ assert.equal(plan.placement, ActionInvocationPlacement.ROOT_MUTATION);
+ assert.equal(plan.fieldName, mutation.name);
+ assert.equal(plan.targetArgumentName, '_target');
+ assert.deepEqual(actionInvocationArguments(plan, {value: 'updated', ignored: 'not-advertised'}, {id: 'target-1'}), {
+ _target: {id: 'target-1'},
+ value: 'updated'
+ });
+});
+
+test('service mutation never manufactures an object target', () => {
+ const mutation = field('sample_Service__clear', scalar('String'));
+ const plan = createActionInvocationPlan({
+ targetKind: 'service',
+ description: description(),
+ descriptor: descriptor([]),
+ mutationType: mutationType(mutation),
+ mutationFieldName: mutation.name
+ });
+
+ assert.equal(plan.placement, ActionInvocationPlacement.ROOT_MUTATION);
+ assert.deepEqual(actionInvocationArguments(plan, {}, {id: 'must-not-be-used'}), {});
+});
+
+test('legacy nested mutation remains the bounded fallback without a root mutation', () => {
+ const legacy = field('invokeNonIdempotent', object('LegacyEnvelope'));
+ const plan = createActionInvocationPlan({
+ targetKind: 'service',
+ description: description(),
+ descriptor: descriptor([legacy]),
+ mutationType: mutationType(),
+ mutationFieldName: 'sample_Service__clear'
+ });
+
+ assert.equal(plan.placement, ActionInvocationPlacement.LEGACY_NESTED_MUTATION);
+ assert.equal(plan.mutating, true);
+});
+
+test('missing executable capability produces an unsupported immutable plan', () => {
+ const plan = createActionInvocationPlan({
+ targetKind: 'service',
+ description: description(),
+ descriptor: descriptor([]),
+ mutationType: mutationType(),
+ mutationFieldName: 'sample_Service__missing'
+ });
+
+ assert.equal(plan.supported, false);
+ assert.equal(Object.isFrozen(plan), true);
+ assert.throws(() => actionInvocationArguments(plan), ActionDispatchPlanError);
+});
+
+test('required arguments and object targets fail before operation rendering', () => {
+ const mutation = field('sample_Target__update', object('rich__sample_Target'), [
+ argument('_target', nonNull(object('rich__sample_Target__gqlv_input'))),
+ argument('secret', nonNull(scalar('Password')))
+ ]);
+ const plan = createActionInvocationPlan({
+ targetKind: 'object',
+ description: description(),
+ descriptor: descriptor([]),
+ mutationType: mutationType(mutation),
+ mutationFieldName: mutation.name
+ });
+
+ assert.throws(
+ () => actionInvocationArguments(plan, {}, {id: 'target-1'}),
+ error => error.code === 'ACTION_REQUIRED_ARGUMENT_UNAVAILABLE' && !error.message.includes('submitted-secret'));
+ assert.throws(
+ () => actionInvocationArguments(plan, {secret: 'submitted-secret'}),
+ error => error.code === 'ACTION_TARGET_IDENTITY_UNAVAILABLE' && !error.message.includes('submitted-secret'));
+});
+
+test('enveloped and direct action results use their described shapes', () => {
+ const targetRef = object('rich__sample_Target');
+ const envelopeRef = object('SafeEnvelope');
+ const types = new Map([
+ ['SafeEnvelope', type('SafeEnvelope', [field('target', targetRef), field('results', targetRef)])],
+ ['rich__sample_Target', type('rich__sample_Target', [field('_meta', object('rich__sample_Target__gqlv_meta'))])],
+ ['rich__sample_Target__gqlv_meta', type('rich__sample_Target__gqlv_meta', [
+ field('id', scalar('ID')),
+ field('logicalTypeName', scalar('String')),
+ field('title', scalar('String'))
+ ])]
+ ]);
+ const envelopePlan = createActionInvocationPlan({
+ targetKind: 'service',
+ description: description(types),
+ descriptor: descriptor([field('invoke', envelopeRef)]),
+ mutationType: mutationType(),
+ mutationFieldName: 'sample_Service__open'
+ });
+ const envelopeResult = actionInvocationResultPlan(envelopePlan, types);
+
+ assert.deepEqual(envelopeResult.selection, {results: {_meta: {id: true, logicalTypeName: true, title: true}}});
+ assert.deepEqual(extractActionInvocationResult({target: {ignored: true}, results: {_meta: {id: '1'}}}, envelopeResult), {_meta: {id: '1'}});
+
+ const directPlan = createActionInvocationPlan({
+ targetKind: 'service',
+ description: description(types),
+ descriptor: descriptor([]),
+ mutationType: mutationType(field('sample_Service__open', targetRef)),
+ mutationFieldName: 'sample_Service__open'
+ });
+ const directResult = actionInvocationResultPlan(directPlan, types);
+ assert.deepEqual(directResult.selection, {_meta: {id: true, logicalTypeName: true, title: true}});
+ assert.deepEqual(directResult.extractionPath, []);
+});
+
+test('protected action results redact errors and operation variables', () => {
+ const result = {
+ data: 'submitted-secret',
+ errors: [{message: 'Rejected submitted-secret', path: ['changePassword'], extensions: {classification: 'BAD_REQUEST'}}],
+ operation: {document: 'mutation Change($input0: Password!) { change(password: $input0) }', variables: {input0: 'submitted-secret'}}
+ };
+
+ const secured = secureActionInvocationResult(result, [{inputType: scalar('Password')}]);
+
+ assert.equal(secured.errors[0].message, 'Protected action input was not accepted.');
+ assert.equal(secured.operation.variables.input0, '<redacted>');
+ assert.equal(JSON.stringify(secured).includes('submitted-secret'), false);
+ assert.equal(secured.operation.document.includes('Password'), true);
+});
+
+test('metadata selection requests only fields advertised by the effective type', () => {
+ const targetRef = object('rich__sample_VersionlessViewModel');
+ const types = new Map([
+ ['rich__sample_VersionlessViewModel', type('rich__sample_VersionlessViewModel', [
+ field('_meta', object('rich__sample_VersionlessViewModel__gqlv_meta'))
+ ])],
+ ['rich__sample_VersionlessViewModel__gqlv_meta', type('rich__sample_VersionlessViewModel__gqlv_meta', [
+ field('id', scalar('ID')),
+ field('logicalTypeName', scalar('String')),
+ field('title', scalar('String'))
+ ])]
+ ]);
+
+ const selection = resultSelectionForType(targetRef, types);
+ assert.deepEqual(selection, {_meta: {id: true, logicalTypeName: true, title: true}});
+ assert.equal(JSON.stringify(selection).includes('version'), false);
+});
diff --git a/viewers/webcomponents/foundation/test/application-menu-client.test.mjs b/viewers/webcomponents/foundation/test/application-menu-client.test.mjs
index 1cc03bf4de9..83d5dc896c5 100644
--- a/viewers/webcomponents/foundation/test/application-menu-client.test.mjs
+++ b/viewers/webcomponents/foundation/test/application-menu-client.test.mjs
@@ -170,6 +170,24 @@ test('mutating service actions use the existing top-level mutation without a man
assert.equal(changed, 1);
});
+test('parameterless service mutation returns versionless object metadata without requesting version or target', async () => {
+ const executor = createMenuGraphQLExecutor();
+ const client = new CausewayGraphQLClient({executor});
+ const context = new ServiceActionContextController({client, logicalTypeName: SAMPLE_SERVICE_LOGICAL_TYPE});
+
+ const invoked = await context.invokeAction('openView', {});
+
+ assert.equal(invoked.status, InteractionStatus.SUCCESS);
+ assert.deepEqual(invoked.data, {kind: 'object', value: {_meta: {
+ id: 'view-1', logicalTypeName: 'sample.VersionlessViewModel', title: 'View one'
+ }}});
+ const operation = executor.mutationCalls.at(-1);
+ assert.match(operation.document, /^mutation CausewayInvokeServiceAction \{/);
+ assert.match(operation.document, /_meta \{\s+id\s+logicalTypeName\s+title\s+\}/);
+ assert.doesNotMatch(operation.document, /version|target|_target|\$object/);
+ assert.deepEqual(operation.variables, {});
+});
+
test('mutating service actions delegate to application-scope serialization', async () => {
const executor = createMenuGraphQLExecutor();
let tail = Promise.resolve();
diff --git a/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs b/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs
index 2c389467269..3c0b63f4a59 100644
--- a/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs
+++ b/viewers/webcomponents/foundation/test/fixtures/menu-graphql-fixture.mjs
@@ -58,7 +58,8 @@ export function createMenuGraphQLTypes({menuBarsAvailable = true} = {}) {
field('greet', named(`${SAMPLE_SERVICE_TYPE}__greet__gqlv_action`)),
field('disabledAction', named(`${SAMPLE_SERVICE_TYPE}__disabledAction__gqlv_action`)),
field('hiddenAction', named(`${SAMPLE_SERVICE_TYPE}__hiddenAction__gqlv_action`)),
- field('clearNotes', named(`${SAMPLE_SERVICE_TYPE}__clearNotes__gqlv_action`))
+ field('clearNotes', named(`${SAMPLE_SERVICE_TYPE}__clearNotes__gqlv_action`)),
+ field('openView', named(`${SAMPLE_SERVICE_TYPE}__openView__gqlv_action`))
])],
[`${SAMPLE_SERVICE_TYPE}__welcomeMessage__gqlv_action`, actionType(
`${SAMPLE_SERVICE_TYPE}__welcomeMessage__gqlv_action`,
@@ -109,8 +110,24 @@ export function createMenuGraphQLTypes({menuBarsAvailable = true} = {}) {
[`${SAMPLE_SERVICE_TYPE}__clearNotes__gqlv_action_invoke`, invokeType(
`${SAMPLE_SERVICE_TYPE}__clearNotes__gqlv_action_invoke`, scalar('String')
)],
+ [`${SAMPLE_SERVICE_TYPE}__openView__gqlv_action`, objectType(
+ `${SAMPLE_SERVICE_TYPE}__openView__gqlv_action`, [
+ field('hidden', scalar('Boolean')),
+ field('disabled', scalar('String')),
+ field('validate', scalar('String'))
+ ]
+ )],
+ ['rich__sample_VersionlessViewModel', objectType('rich__sample_VersionlessViewModel', [
+ field('_meta', named('rich__sample_VersionlessViewModel__gqlv_meta'))
+ ])],
+ ['rich__sample_VersionlessViewModel__gqlv_meta', objectType('rich__sample_VersionlessViewModel__gqlv_meta', [
+ field('id', scalar('ID')),
+ field('logicalTypeName', scalar('String')),
+ field('title', scalar('String'))
+ ])],
['Mutation', objectType('Mutation', [
- field(`${SAMPLE_SERVICE_FIELD}__clearNotes`, scalar('String'))
+ field(`${SAMPLE_SERVICE_FIELD}__clearNotes`, scalar('String')),
+ field(`${SAMPLE_SERVICE_FIELD}__openView`, named('rich__sample_VersionlessViewModel'))
])]
]);
}
@@ -180,6 +197,11 @@ export function createMenuGraphQLExecutor({
if (request.operationName === 'CausewayInvokeServiceAction') {
if (request.document.startsWith('mutation')) {
mutationCalls.push(request);
+ if (request.document.includes(`${SAMPLE_SERVICE_FIELD}__openView`)) {
+ return {data: {[`${SAMPLE_SERVICE_FIELD}__openView`]: {_meta: {
+ id: 'view-1', logicalTypeName: 'sample.VersionlessViewModel', title: 'View one'
+ }}}};
+ }
return {data: {[`${SAMPLE_SERVICE_FIELD}__clearNotes`]: 'Cleared'}};
}
serviceCalls.push(request);
(causeway) 15/15: archives paged reference autocomplete change
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit 8743abdacd1ea5dc204e9a215b96aa080d01fd04
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 21:59:00 2026 +0100
archives paged reference autocomplete change
---
.../.openspec.yaml | 0
.../design.md | 0
.../evidence/REPRODUCING.md | 0
.../evidence/final-gate-results.md | 0
.../evidence/implementation-report.md | 0
.../evidence/production-isolation.md | 0
.../evidence/window-shape-matrix.md | 0
.../proposal.md | 0
.../specs/domain-web-components/spec.md | 0
.../spec.md | 0
.../spec.md | 0
.../specs/vaadin-reference-widget-pilot/spec.md | 0
.../tasks.md | 0
.../planned-changes/web-component-viewer/README.md | 2 +-
.../web-component-viewer/vaadin-default-roadmap.md | 2 +-
openspec/specs/domain-web-components/spec.md | 34 +++++++++++++++++++++
.../spec.md | 29 ++++++++++++++++++
.../spec.md | 8 ++++-
.../specs/vaadin-reference-widget-pilot/spec.md | 35 +++++++++++++++-------
19 files changed, 97 insertions(+), 13 deletions(-)
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/.openspec.yaml b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/.openspec.yaml
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/.openspec.yaml
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/.openspec.yaml
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/design.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/design.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/design.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/design.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/REPRODUCING.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/final-gate-results.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/implementation-report.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/implementation-report.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/evidence/implementation-report.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/implementation-report.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/production-isolation.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/production-isolation.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/evidence/production-isolation.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/production-isolation.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/evidence/window-shape-matrix.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/proposal.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/proposal.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/proposal.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/proposal.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/specs/domain-web-components/spec.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/domain-web-components/spec.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/specs/domain-web-components/spec.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/domain-web-components/spec.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/specs/reference-application-viewer-regression-suite/spec.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/reference-application-viewer-regression-suite/spec.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/specs/reference-application-viewer-regression-suite/spec.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/reference-application-viewer-regression-suite/spec.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md
similarity index 100%
copy from openspec/changes/add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md
copy to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/specs/vaadin-reference-widget-pilot/spec.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/vaadin-reference-widget-pilot/spec.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/specs/vaadin-reference-widget-pilot/spec.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/specs/vaadin-reference-widget-pilot/spec.md
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md b/openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/tasks.md
similarity index 100%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/tasks.md
rename to openspec/changes/archive/2026-08-24-add-paged-graphql-reference-autocomplete/tasks.md
diff --git a/openspec/planned-changes/web-component-viewer/README.md b/openspec/planned-changes/web-component-viewer/README.md
index ad2efceecf8..6ce102e8183 100644
--- a/openspec/planned-changes/web-component-viewer/README.md
+++ b/openspec/planned-changes/web-component-viewer/README.md
@@ -8,7 +8,7 @@ The action-dispatch correctness change is archived, completing the remaining Pri
The versionless-identity and preparation correction is archived.
The union-projection correction is archived.
The opaque-route correction is archived.
-The active `add-paged-graphql-reference-autocomplete` change adds honest bounded server response windows before the Vaadin expansion and default sequence in `vaadin-default-roadmap.md`.
+The archived `add-paged-graphql-reference-autocomplete` change adds honest bounded server response windows before the planned Vaadin expansion and default sequence in `vaadin-default-roadmap.md`.
The older Vue, Svelte, metadata, diagnostics, performance-analysis, catalogue, and designer drafts remain queued behind that higher-priority qualification and default-adoption work.
Complete child directories contain `.openspec.yaml`, `proposal.md`, `design.md`, `tasks.md`, and delta specifications and can be promoted verbatim after review.
diff --git a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
index c743032c67e..bbe13123ebe 100644
--- a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
+++ b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
@@ -17,7 +17,7 @@ Proposal-only drafts must be refined against checked-in capability evidence befo
| 2 | `harden-webcomponent-input-value-semantics` *(archived)* | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Completed against stable Reference Application fixtures. |
| 3 | `fix-webcomponent-action-dispatch-correctness` *(archived)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Completed with successful typed Reference Application interactions and unchanged public operations. |
| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, `fix-webcomponent-union-projection-correctness` *(archived)*, `fix-webcomponent-opaque-route-correctness` *(archived)* | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
-| 5 | `add-paged-graphql-reference-autocomplete` *(active)* | Add honest bounded server response windows for reference autocomplete without claiming persistence query pushdown. | Public GraphQL operation, identity, preparation, ordering, continuation, and consistency contracts are accepted. |
+| 5 | `add-paged-graphql-reference-autocomplete` *(archived 2026-08-24)* | Add honest bounded server response windows for reference autocomplete without claiming persistence query pushdown. | Public GraphQL operation, identity, preparation, ordering, continuation, and consistency contracts are accepted. |
| 6 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
| 7 | `make-vaadin-default-for-webcomponent-viewer` | Flip the supported selection policy to Vaadin-first and remove pilot status. | All prerequisite suites pass in default and explicit native modes. |
diff --git a/openspec/specs/domain-web-components/spec.md b/openspec/specs/domain-web-components/spec.md
index 9a288e52734..346c925180b 100644
--- a/openspec/specs/domain-web-components/spec.md
+++ b/openspec/specs/domain-web-components/spec.md
@@ -1009,3 +1009,37 @@ It MUST validate fragment membership and nested fields through targeted introspe
- **WHEN** a probe or fragment replay belongs to a disconnected, cancelled, or superseded collection generation
- **THEN** its remaining work is aborted or discarded
- **AND** it cannot replace the current row state
+
+### Requirement: Semantic autocomplete window consumption
+Semantic property and action-parameter editors SHALL prefer an advertised rich GraphQL autocomplete window while preserving Causeway-owned pending values, validation, semantic events, cancellation, and toolkit neutrality.
+They MUST retain a bounded honest fallback when the server exposes only legacy autocomplete.
+
+#### Scenario: Windowed property search begins
+- **WHEN** an editable reference property advertises `autoCompleteWindow` and the search reaches its minimum length
+- **THEN** the property context requests offset zero with a bounded page size
+- **AND** publishes the returned items and continuation metadata only for the current filter generation
+
+#### Scenario: Windowed action parameter depends on earlier values
+- **WHEN** an object or service action parameter requests a page using current preceding arguments
+- **THEN** the semantic context sends only arguments declared by the advertised window field
+- **AND** changing an earlier value invalidates outstanding pages and restarts the affected search at offset zero
+
+#### Scenario: Later page is requested
+- **WHEN** the active semantic editor requests an offset not yet loaded for the current filter
+- **THEN** the context obtains that authoritative server window without downloading or locally slicing the complete result
+- **AND** semantic identities deduplicate items at their requested positions
+
+#### Scenario: Window request becomes obsolete
+- **WHEN** filter text, dependent arguments, prompt state, route generation, connection, or component lifetime supersedes an outstanding page
+- **THEN** the request is aborted or ignored
+- **AND** stale items, totals, validation, selection, focus, and errors cannot replace current state
+
+#### Scenario: Native editor receives a partial first window
+- **WHEN** native fallback presentation has items with `hasNext` true
+- **THEN** it exposes the bounded current choices and an accessible additional-results or refine-search indication
+- **AND** does not claim the first window is the complete result
+
+#### Scenario: Server has only legacy autocomplete
+- **WHEN** targeted introspection finds `autoComplete` but no `autoCompleteWindow`
+- **THEN** the context uses the existing single-response operation within its configured bound
+- **AND** an over-bound response retains the established visible limitation state without silent truncation
diff --git a/openspec/specs/reference-application-viewer-regression-suite/spec.md b/openspec/specs/reference-application-viewer-regression-suite/spec.md
index 83d75cfb3ed..e56904b1061 100644
--- a/openspec/specs/reference-application-viewer-regression-suite/spec.md
+++ b/openspec/specs/reference-application-viewer-regression-suite/spec.md
@@ -198,3 +198,32 @@ It MUST preserve the exact identifier, distinguish corrected routing from object
- **WHEN** the same qualification run requests malformed escapes, separators, controls, non-canonical encoding, or a segment beyond the supported encoded bound
- **THEN** the viewer retains its non-disclosing `invalid-route` presentation
- **AND** successful long opaque routing does not weaken route validation
+
+### Requirement: Multi-window reference autocomplete regression coverage
+The pinned Reference Application suite SHALL exercise deterministic rich autocomplete results larger than its configured qualification page for property or action-parameter reference selection.
+It MUST cover GraphQL metadata, later-window selection, argument dependencies, cancellation, legacy compatibility, and toolkit-neutral outcomes.
+
+#### Scenario: GraphQL autocomplete spans several windows
+- **WHEN** a deterministic search returns more references than the configured page size
+- **THEN** adjacent windows report accurate items, offsets, counts, totals, maximum, ordering, and continuation state
+- **AND** their combined authoritative encounter order contains no omitted or duplicated position
+
+#### Scenario: Invalid window is requested
+- **WHEN** qualification requests a negative offset, non-positive size, or size above the configured maximum
+- **THEN** GraphQL returns a bounded non-disclosing error
+- **AND** existing legacy autocomplete remains executable
+
+#### Scenario: Browser selects a later-window reference
+- **WHEN** the reference editor searches and requests an item absent from the first window
+- **THEN** the internal adapter obtains the later server window and selection preserves the item's semantic identity
+- **AND** validation or submission uses the existing Causeway interaction contract
+
+#### Scenario: Search generation is superseded
+- **WHEN** the browser changes filter or dependent parameter values while a page is in flight or replaces the route
+- **THEN** obsolete pages cannot alter suggestions, total count, selection, error, focus, or current route state
+- **AND** no unexpected GraphQL, console, page, CSP, external-request, accessibility, or overflow failure occurs
+
+#### Scenario: Native and candidate modes are qualified
+- **WHEN** the same semantic autocomplete target runs with native fallback and explicitly enabled Vaadin reference widgets
+- **THEN** both modes preserve authoritative values and honest continuation or refinement behavior
+- **AND** unaffected routes retain zero Vaadin asset requests
diff --git a/openspec/changes/add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md b/openspec/specs/rich-graphql-reference-autocomplete-windowing/spec.md
similarity index 94%
rename from openspec/changes/add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md
rename to openspec/specs/rich-graphql-reference-autocomplete-windowing/spec.md
index d10da5bcd32..a6f067d28c0 100644
--- a/openspec/changes/add-paged-graphql-reference-autocomplete/specs/rich-graphql-reference-autocomplete-windowing/spec.md
+++ b/openspec/specs/rich-graphql-reference-autocomplete-windowing/spec.md
@@ -1,4 +1,10 @@
-## ADDED Requirements
+# Rich GraphQL Reference Autocomplete Windowing Specification
+
+## Purpose
+
+Define additive, bounded rich GraphQL autocomplete windows for properties and action parameters while retaining the existing autocomplete operation and Causeway semantics.
+
+## Requirements
### Requirement: Additive rich autocomplete windows
Rich GraphQL SHALL expose `autoCompleteWindow` beside every advertised rich property or action-parameter `autoComplete` field.
diff --git a/openspec/specs/vaadin-reference-widget-pilot/spec.md b/openspec/specs/vaadin-reference-widget-pilot/spec.md
index 28afcd48ecd..8ec866c4344 100644
--- a/openspec/specs/vaadin-reference-widget-pilot/spec.md
+++ b/openspec/specs/vaadin-reference-widget-pilot/spec.md
@@ -68,16 +68,31 @@ Causeway MUST remain authoritative for pending values, stable domain identity, r
- **AND** does not establish a second authoritative widget state machine
### Requirement: Honest bounded autocomplete behavior
-The pilot SHALL define and enforce an explicit maximum accepted result count and search policy for the current non-paged GraphQL autocomplete operation.
-Local slicing for candidate callbacks MUST NOT be represented as server paging, and responses that exceed the accepted bound MUST fail visibly or use the existing fallback rather than appear silently complete.
-
-#### Scenario: Bounded autocomplete response is returned
-- **WHEN** GraphQL returns a stable choice set within the configured bound
-- **THEN** the adapter may serve candidate callback windows from that result while retaining cancellation and generation checks
-- **AND** records that paging is local presentation over one server response
-
-#### Scenario: Autocomplete bound is exceeded
-- **WHEN** the server response exceeds the configured maximum or cannot provide stable identities
+The pilot SHALL prefer advertised public GraphQL autocomplete windows and SHALL connect its internal lazy data-provider callback to bounded server response pages.
+It MUST retain an explicit maximum search policy for legacy non-paged autocomplete, and local slicing MUST NOT be represented as server paging.
+
+#### Scenario: Window capability is advertised
+- **WHEN** an eligible reference editor advertises `autoCompleteWindow`
+- **THEN** the internal Vaadin data provider requests bounded offset pages using current filter text and Causeway argument context
+- **AND** supplies returned items and authoritative total count to the control without exposing a Vaadin API to the application
+
+#### Scenario: User scrolls beyond the first page
+- **WHEN** Vaadin requests a later page for the current filter generation
+- **THEN** the adapter obtains that page from the semantic Causeway context
+- **AND** does not locally slice a previously downloaded complete result
+
+#### Scenario: Filter changes while pages are in flight
+- **WHEN** newer filter text, dependent arguments, route navigation, fragment replacement, prompt closure, or disconnection supersedes page requests
+- **THEN** the adapter cancels or ignores stale callbacks and items
+- **AND** retains Causeway-owned selection, focus, validation, and pending-value state
+
+#### Scenario: Only bounded legacy autocomplete is available
+- **WHEN** the server does not advertise a window field and GraphQL returns a stable choice set within the configured bound
+- **THEN** the adapter may use the complete finite result while retaining cancellation and generation checks
+- **AND** records that the response is legacy and not server paging
+
+#### Scenario: Legacy autocomplete bound is exceeded
+- **WHEN** a legacy server response exceeds the configured maximum or cannot provide stable identities
- **THEN** the editor presents a Causeway-owned limitation state or activates the documented fallback
- **AND** does not truncate the choices while claiming a complete match set
(causeway) 09/15: archives union projection correctness change
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git
commit e7e2c9a5052e1ae4f57950b1e69a7e30bb2d074f
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Mon Aug 24 13:38:45 2026 +0100
archives union projection correctness change
---
.../.openspec.yaml | 0
.../design.md | 0
.../evidence/REPRODUCING.md | 0
.../evidence/final-gate-results.md | 0
.../evidence/implementation-report.md | 0
.../evidence/production-isolation.md | 0
.../evidence/union-shape-matrix.md | 0
.../proposal.md | 0
.../specs/domain-web-components/spec.md | 0
.../spec.md | 0
.../spec.md | 0
.../tasks.md | 0
.../planned-changes/web-component-viewer/README.md | 3 +-
.../web-component-viewer/vaadin-default-roadmap.md | 4 +-
openspec/specs/domain-web-components/spec.md | 50 ++++++++++++++++++++--
.../spec.md | 36 +++++++++++++++-
.../spec.md | 19 ++++++++
17 files changed, 105 insertions(+), 7 deletions(-)
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/.openspec.yaml b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/.openspec.yaml
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/.openspec.yaml
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/.openspec.yaml
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/design.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/design.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/design.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/design.md
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/REPRODUCING.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/REPRODUCING.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/evidence/REPRODUCING.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/REPRODUCING.md
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/final-gate-results.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/final-gate-results.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/evidence/final-gate-results.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/final-gate-results.md
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/implementation-report.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/implementation-report.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/evidence/implementation-report.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/implementation-report.md
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/production-isolation.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/production-isolation.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/evidence/production-isolation.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/production-isolation.md
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/evidence/union-shape-matrix.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/union-shape-matrix.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/evidence/union-shape-matrix.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/evidence/union-shape-matrix.md
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/proposal.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/proposal.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/proposal.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/proposal.md
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/specs/domain-web-components/spec.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/specs/domain-web-components/spec.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/specs/domain-web-components/spec.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/specs/domain-web-components/spec.md
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/specs/reference-application-viewer-regression-suite/spec.md
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/specs/rich-graphql-object-interaction-correctness/spec.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/specs/rich-graphql-object-interaction-correctness/spec.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/specs/rich-graphql-object-interaction-correctness/spec.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/specs/rich-graphql-object-interaction-correctness/spec.md
diff --git a/openspec/changes/fix-webcomponent-union-projection-correctness/tasks.md b/openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/tasks.md
similarity index 100%
rename from openspec/changes/fix-webcomponent-union-projection-correctness/tasks.md
rename to openspec/changes/archive/2026-08-24-fix-webcomponent-union-projection-correctness/tasks.md
diff --git a/openspec/planned-changes/web-component-viewer/README.md b/openspec/planned-changes/web-component-viewer/README.md
index 9bb43beab38..d9b6f8635a4 100644
--- a/openspec/planned-changes/web-component-viewer/README.md
+++ b/openspec/planned-changes/web-component-viewer/README.md
@@ -6,7 +6,8 @@ The foundation, domain-component, rich GraphQL correctness, value-semantics, col
The Reference Application regression suite and input-value hardening changes are archived.
The action-dispatch correctness change is archived, completing the remaining Priority 0 correction identified by that broad capability inventory.
The versionless-identity and preparation correction is archived.
-The current active change is `fix-webcomponent-union-projection-correctness`, followed by opaque-route handling before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
+The union-projection correction is archived.
+The next change should address opaque-route handling before the proposal-only paged-autocomplete and Vaadin-default sequence in `vaadin-default-roadmap.md`.
The older Vue, Svelte, metadata, diagnostics, performance-analysis, catalogue, and designer drafts remain queued behind that higher-priority qualification and default-adoption work.
Complete child directories contain `.openspec.yaml`, `proposal.md`, `design.md`, `tasks.md`, and delta specifications and can be promoted verbatim after review.
diff --git a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
index 828d5dd7918..d640788c5a1 100644
--- a/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
+++ b/openspec/planned-changes/web-component-viewer/vaadin-default-roadmap.md
@@ -8,7 +8,7 @@ The repository permits one active OpenSpec change at a time.
The Reference Application suite and input-value hardening are archived.
The archived `fix-webcomponent-action-dispatch-correctness` change completed the remaining Priority 0 correctness tranche identified by the pinned regression corpus.
The archived `fix-webcomponent-versionless-identity-preparation` change isolates concrete versionless identity.
-The active `fix-webcomponent-union-projection-correctness` change precedes the separate opaque-route correction.
+The archived `fix-webcomponent-union-projection-correctness` change precedes the separate opaque-route correction.
Proposal-only drafts must be refined against checked-in capability evidence before promotion.
| Order | Proposal | Purpose | Promotion gate |
@@ -16,7 +16,7 @@ Proposal-only drafts must be refined against checked-in capability evidence befo
| 1 | `add-referenceapp-webcomponent-regression-suite` *(archived)* | Copy the pinned broad corpus, establish deterministic inventory, and expose real gaps. | Completed with reviewed classifications. |
| 2 | `harden-webcomponent-input-value-semantics` *(archived)* | Correct precision, temporal, nullable, protected, resource, and custom-value behavior independently of toolkit choice. | Completed against stable Reference Application fixtures. |
| 3 | `fix-webcomponent-action-dispatch-correctness` *(archived)* | Correct nested safe-query and flat mutation dispatch for object and service actions. | Completed with successful typed Reference Application interactions and unchanged public operations. |
-| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, `fix-webcomponent-union-projection-correctness` *(active)*, then focused opaque-route handling | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
+| 4 | `fix-webcomponent-versionless-identity-preparation` *(archived)*, `fix-webcomponent-union-projection-correctness` *(archived)*, then focused opaque-route handling | Correct versionless preparation, valid polymorphic metadata selection, and long composite bookmark handling in separate changes. | Each retained gap has an executable focused contract and passing regression target. |
| 5 | `add-paged-graphql-reference-autocomplete` | Add honest server-side reference windows for large datasets. | Public GraphQL operation, identity, preparation, and ordering contracts are accepted. |
| 6 | `expand-vaadin-semantic-editor-families` | Qualify free-core adapters beyond reference controls with independent lazy closures and CSP gates. | Corrected codecs and Reference Application family journeys pass. |
| 7 | `make-vaadin-default-for-webcomponent-viewer` | Flip the supported selection policy to Vaadin-first and remove pilot status. | All prerequisite suites pass in default and explicit native modes. |
diff --git a/openspec/specs/domain-web-components/spec.md b/openspec/specs/domain-web-components/spec.md
index 57e7486a6b4..9a288e52734 100644
--- a/openspec/specs/domain-web-components/spec.md
+++ b/openspec/specs/domain-web-components/spec.md
@@ -961,7 +961,51 @@ It MUST preserve advertised identity and presentation fields, MUST treat `versio
- **THEN** row selection merges the advertised identity fields with requested semantic columns
- **AND** the rows remain hydratable without manufacturing a concurrency token
-#### Scenario: Abstract row type requires fragments
-- **WHEN** an interface or union row cannot expose semantic metadata without concrete fragments
+#### Scenario: Abstract row projection remains unsupported
+- **WHEN** an interface or union row exceeds the bounded projection policy or cannot be resolved through advertised concrete fragments
- **THEN** the component retains a bounded non-navigable or partial-error result
-- **AND** does not treat versionless concrete-object support as general union-projection support
+- **AND** does not manufacture a concrete identity
+
+### Requirement: Bounded polymorphic value projection
+The component library SHALL derive valid inline-fragment selections for advertised GraphQL interface and union values without selecting concrete fields directly on the abstract type.
+It MUST validate fragment membership and nested fields through targeted introspection, MUST bound fragment and introspection cost, and MUST NOT repeat a mutating interaction to discover its result type.
+
+#### Scenario: Small abstract result has described possible types
+- **WHEN** an interface or union advertises a bounded set of described concrete object types
+- **THEN** the operation selects `__typename` and valid inline fragments for those advertised types
+- **AND** each fragment requests only metadata and children valid for its concrete type
+
+#### Scenario: Broad collection union is activated
+- **WHEN** an activated side-effect-free collection exposes an abstract row type whose complete possible-type set exceeds the direct expansion limit
+- **THEN** the context issues one bounded typename-only probe and describes only distinct observed advertised concrete types
+- **AND** reissues the same list or window read once with valid fragments for those types
+
+#### Scenario: Polymorphic rows expose common identity
+- **WHEN** concrete fragment results contain `id` and `logicalTypeName`
+- **THEN** each row retains its exact typename, metadata, semantic object link, and hydrated row context
+- **AND** optional title and version behavior follows the concrete metadata type
+
+#### Scenario: Requested column differs by concrete type
+- **WHEN** a declared semantic column is present on some observed concrete types and absent on another
+- **THEN** each fragment includes the column only where its wrapper and child selection are advertised
+- **AND** the missing cell remains local without invalidating successfully projected rows
+
+#### Scenario: Replay returns an unobserved concrete type
+- **WHEN** a collection changes between typename probe and fragment replay and returns an advertised type not included in the replay fragments
+- **THEN** that row remains bounded to its available typename projection and is reported locally
+- **AND** the context does not enter an unbounded probe loop
+
+#### Scenario: Returned typename is not advertised
+- **WHEN** a response typename is not an advertised possible type of the abstract field
+- **THEN** the context rejects it as a bounded schema mismatch
+- **AND** does not construct or submit a fragment from that value
+
+#### Scenario: Broad mutating action result
+- **WHEN** a mutating action returns an abstract type that cannot be projected within the direct fragment bound
+- **THEN** the action executes exactly once and retains its successful bounded typename-only outcome
+- **AND** the controller does not invent navigable identity or repeat the mutation
+
+#### Scenario: Polymorphic request becomes obsolete
+- **WHEN** a probe or fragment replay belongs to a disconnected, cancelled, or superseded collection generation
+- **THEN** its remaining work is aborted or discarded
+- **AND** it cannot replace the current row state
diff --git a/openspec/specs/reference-application-viewer-regression-suite/spec.md b/openspec/specs/reference-application-viewer-regression-suite/spec.md
index 75021813932..cd68fb014b9 100644
--- a/openspec/specs/reference-application-viewer-regression-suite/spec.md
+++ b/openspec/specs/reference-application-viewer-regression-suite/spec.md
@@ -137,6 +137,40 @@ It MUST distinguish corrected versionless projection behavior from retained poly
- **AND** a missing version field is not the cause of any row error
#### Scenario: Unrelated retained gaps remain classified
-- **WHEN** the same qualification run reaches a polymorphic union target or a long opaque composite bookmark
+- **WHEN** the same qualification run reaches an incompatible raw union row or a long opaque composite bookmark
- **THEN** the suite retains the corresponding bounded known-gap assertion until its focused change is implemented
- **AND** does not count it as evidence that concrete versionless identity failed
+
+### Requirement: Polymorphic projection regression coverage
+The pinned Reference Application suite SHALL distinguish valid concrete and union projection from a runtime object that is not a member of its advertised union.
+It MUST preserve deterministic concrete-row evidence, bounded schema mismatch behavior, and the separate opaque-route gap.
+
+#### Scenario: Declared type-of collection is activated
+- **WHEN** the browser activates `demo.CollectionTypeOfPage.children`, whose `typeOf` metadata supplies the concrete row type
+- **THEN** concrete `demo.CollectionTypeOfChildVm` rows render their semantic identities through the ordinary concrete projection
+- **AND** union probing is not used for that collection
+
+#### Scenario: Raw collection exposes incompatible runtime rows
+- **WHEN** the companion raw collection is advertised as `rich__demo_ValueHolder__gqlv_union` but returns `demo.CollectionTypeOfChildVm`, which does not implement `demo.ValueHolder`
+- **THEN** GraphQL and the viewer retain a bounded local schema/runtime mismatch
+- **AND** the viewer does not manufacture union membership or an application-specific fragment
+
+#### Scenario: Generated union membership is completed incrementally
+- **WHEN** the Reference Application schema repeatedly discovers concrete `demo.ValueHolder` implementations
+- **THEN** introspection advertises the deterministic merged set rather than only the first registration
+- **AND** every advertised fragment name is a valid member of the completed union
+
+#### Scenario: Invalid direct union metadata is rejected
+- **WHEN** a reproduction selects `_meta` directly from `rich__demo_ValueHolder__gqlv_union`
+- **THEN** GraphQL rejects that operation as invalid
+- **AND** valid viewer planning uses typename and concrete fragments only
+
+#### Scenario: Existing collection behavior remains stable
+- **WHEN** the full collection journey also reaches concrete versionless rows, configured collections, lazy tabs, stale windows, partial errors, and route replacement
+- **THEN** those established behaviors retain their passing assertions
+- **AND** polymorphic planning does not make inactive collections eager
+
+#### Scenario: Opaque composite route remains separate
+- **WHEN** a projected concrete result carries the long opaque identifier retained by the corpus
+- **THEN** the suite continues to assert the focused `invalid-route` gap
+- **AND** does not attribute route rejection to union projection
diff --git a/openspec/specs/rich-graphql-object-interaction-correctness/spec.md b/openspec/specs/rich-graphql-object-interaction-correctness/spec.md
index 8561f20a93d..56809fe6566 100644
--- a/openspec/specs/rich-graphql-object-interaction-correctness/spec.md
+++ b/openspec/specs/rich-graphql-object-interaction-correctness/spec.md
@@ -60,3 +60,22 @@ The correctness changes SHALL preserve established successful concrete-object an
- **WHEN** an existing concrete object query or scalar action document is executed after the change
- **THEN** its generated names and semantic result remain compatible
- **AND** any new type exposure is limited to public logical types required by the corrected contract
+
+### Requirement: Complete incremental union registration
+Rich GraphQL SHALL preserve the union of concrete possible types discovered by every registration of the same generated interface or union name during metamodel construction.
+It MUST deduplicate possible types by GraphQL name and MUST retain one deterministic generated abstract type and resolver registration.
+
+#### Scenario: Later registration discovers another concrete type
+- **WHEN** a generated union name is registered after an existing registration with one or more additional concrete object types
+- **THEN** the schema registry replaces the stored union with merged possible-type membership
+- **AND** introspection advertises both the earlier and later concrete types
+
+#### Scenario: Registration repeats an existing concrete type
+- **WHEN** another registration contributes a concrete type name already present on the generated union
+- **THEN** the stored union contains that type exactly once
+- **AND** schema construction remains deterministic
+
+#### Scenario: Runtime resolver returns a merged concrete type
+- **WHEN** the union resolver identifies a concrete type contributed by a later registration
+- **THEN** GraphQL validates that type against the completed union membership
+- **AND** a client can select it through an advertised inline fragment