From 3136ac9625b40c067a3a8c89fd0a1702329ab438 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski Date: Wed, 30 Sep 2026 17:55:32 +0200 Subject: [PATCH 01/16] docs(session-forms): document V1 choice forms for agents and frontends - Framework page: enabling the ask_user trait, the form definition and its limits, the answer message and self-contained answer record, read_form and the form index (including pending answers), late answers, one form per turn, answer admission, and security notes. - Frontend page: the question card, the wippy-form and wippy-form-answers components, the artifact state HTTP API and artifactState client, Host version requirements, accessibility notes and known gaps. --- en/framework/session-forms.md | 308 ++++++++++++++++ en/frontend/micro-frontends/session-forms.md | 347 +++++++++++++++++++ en/manifest.json | 4 +- 3 files changed, 658 insertions(+), 1 deletion(-) create mode 100644 en/framework/session-forms.md create mode 100644 en/frontend/micro-frontends/session-forms.md diff --git a/en/framework/session-forms.md b/en/framework/session-forms.md new file mode 100644 index 00000000..200d7666 --- /dev/null +++ b/en/framework/session-forms.md @@ -0,0 +1,308 @@ +--- +title: "Session Forms" +description: "Ask the user structured choice questions from an agent with the ask_user tool, and read the answer back as a self-contained record." +--- + +# Session Forms + +Session forms let an agent ask the user one or more choice questions and get +a structured answer back, without leaving a tool call waiting on human input. +The `wippy/session` module owns the feature: a trait that adds the `ask_user` +and `read_form` tools, an artifact that renders as a question card in the +chat, and an HTTP endpoint that accepts the answer and delivers it to the +session as an ordinary user message. + +V1 supports choice questions only: single selection, multiple selection, +optional required/optional, and an optional free-text "Other" answer. Plain +text, number, date, and other field types are a later release; a V1 renderer +detects an unsupported field type and shows a fallback rather than dropping +the question silently. + +This page documents the trait, the tool contracts, and how an answer reaches +the conversation. For the `wippy-form` / `wippy-form-answers` components and +the HTTP contract from the browser side, see +[Session Forms (frontend)](../frontend/micro-frontends/session-forms.md). + +## Enabling the trait + +Add `wippy.session.forms:ask_user` to an agent's `traits`: + +```yaml + - name: assistant + kind: registry.entry + meta: + type: agent.gen1 + title: Assistant + prompt: | + When you need the user to choose between concrete options before you + can continue, ask them with the ask_user tool instead of asking in + plain text. + model: gpt-4o + max_tokens: 4096 + traits: + - id: wippy.session.forms:ask_user +``` + +The trait requires a `wippy/session` version that ships session forms. With +an older one, an agent definition that references the trait fails to resolve +at lint time rather than silently doing nothing. + +The trait contributes two tools and a block of prompt text that explains +them to the model (ask at most one form per turn, read `answered_message` +back through `read_form`, treat a late answer as context only, and never +write a `` element by hand). An agent without the trait +cannot call `ask_user`, but its prompt still includes the deterministic form +index described below, and it can read a submitted answer like any other +user message. + +## The `ask_user` tool + +`ask_user` validates and normalizes the definition, then asks the session to +create the form. An invalid definition is a tool error (the call returns no +result and a message describing what to fix); nothing is stored in that +case, and the agent can retry in the same turn. + +| Key | Contract | +| --- | --- | +| `title` | Required plain text, 1 to 160 characters | +| `description` | Optional plain text, at most 1,000 characters | +| `submit_label` | Optional plain text, at most 40 characters | +| `answered_message` | Optional plain text, at most 200 characters. The user's chat message once they answer, written in the user's own voice by the agent that asks (see [What the agent receives](#what-the-agent-receives)). Never shown on the form. A form asked without it falls back to `Answered "".` | +| `fields` | 1 to 20 entries | +| `fields[].id` | Unique key matching `^[a-z][a-z0-9_]{0,39}$` | +| `fields[].type` | `"choice"` (the only V1 type) | +| `fields[].label` | The question, 1 to 240 characters | +| `fields[].description` | Optional help text, at most 1,000 characters | +| `fields[].required` | Boolean, default `false` | +| `fields[].options` | 1 to 20 distinct choices. A plain string is both the value and the label; use `{ "value", "label", "description"? }` when the stored value should differ from the shown text | +| `fields[].multiple` | Boolean, default `false`: allow selecting several options | +| `fields[].allow_other` | Boolean, default `false`: offer a free-text "Other" answer | + +The normalized definition is bounded to 32 KiB. That size is measured after +normalization, where a plain string option expands to `{"value": .., "label": +..}`, so a compact-looking definition with many short string options can be +well over the limit before it is written out this way; the tool error +reports the actual normalized size in that case. Labels and descriptions are +rendered as plain text, never parsed as Markdown or HTML, and control +characters other than tabs and newlines (in multi-line fields) are rejected. + +A successful call ends the agent's turn. The tool result is a factual, +past-tense sentence: + +```text +Form "Delivery preference" was created as <artifact-id>. Its answer will arrive as a user message. +``` + +The agent should not run a further model step to say "please fill in the +form" — the form is already visible. If it chooses to add a short +continuation anyway, that costs an extra model step and has no effect on +correctness: the form is already durably created either way. + +### One form per turn + +At most one form can be created per agent turn. A second `ask_user` call in +the same turn is rejected before anything is written: + +```text +This turn already asked the user with a form. No second form was created; wait for the answer to the first one. +``` + +A session can hold up to 100 unresolved (unanswered) forms at once. Above +that, `ask_user` is rejected with `too_many_forms` and the agent is asked to +resolve or supersede older forms; nothing is deleted automatically. + +A form's definition is immutable once created. There is no edit operation — +attempting to update a form artifact through the general artifact-update path +is rejected (`session_form: Session forms cannot be edited. Ask a new form +instead.`). To change a question, ask a new form. + +## What the agent receives + +The user answers on a question card (see the frontend page for the UI). The +accepted answer becomes one ordinary user message, built entirely on the +server — the browser never supplies its text. The message has exactly one +visible line, followed by an invisible carrier element that holds the full +answer as JSON: + +```text +Answered questions about the delivery of your order. + +<wippy-form-answers record='{"form_id":"<artifact-id>","form_version":1,"title":"Order details","late":false,"answers":{"delivery":{"question":"How should the parcel be delivered?","answer":{"value":"courier","label":"Courier","note":"Buzzer 12, back entrance"}},"extras":{"question":"Any extras for this order?","answer":[{"value":"gift_wrap","label":"Gift wrap"},{"other":"Remove the price tag"}]},"when":{"question":"When works best for delivery?","answer":null}}}'> +</wippy-form-answers> +``` + +The user sees only the first line: the `answered_message` the agent supplied +when it called `ask_user` (or the `Answered "<title>".` fallback). The +`wippy-form-answers` component the Session ships renders nothing, so the +record never appears in the chat, but the raw message text — including the +record attribute — is what the agent reads on its next turn. The answered +form card shown above the message is the user-facing summary; this record is +the machine-readable one. + +### Record shape + +The record is self-contained: an agent can act on it without the original +`ask_user` call, which a checkpoint may have summarized away. For each +question id, `answers[id]` has a `question` (the field's label) and an +`answer`: + +| Answer shape | When | +| --- | --- | +| `{"value": "courier", "label": "Courier"}` | A chosen option | +| `{"value": "courier", "label": "Courier", "note": "…"}` | A chosen option with the user's own note | +| `{"other": "…"}` | The user's own free-text answer | +| `[ ...one of the above... ]` | A multiple-selection question, in definition order, with an "Other" entry (if any) last | +| `null` | The question was left unanswered (only possible when not required) | + +The record also carries `form_id`, `form_version`, and `title`. A late +answer (see below) additionally carries `"late": true` and a `late_notice`. +The stored submission keeps only the normalized answer values; the record +itself is derived from those values plus the immutable definition on every +read, so the record in the answer message and the one `read_form` returns +for the same form always agree. + +## Late answers and the fresh-confirmation rule + +A form's staleness and its late flag serve different purposes and are tracked +separately. + +While a form is unanswered, it is **stale** when a different real user input +(a typed message, or a submission to another form) was durably accepted +after the form was created. Staleness is evaluated live, every time the form +state is read; assistant text, system events, tool results, and validation +failures never make a form stale. + +Once a form is answered, the acceptance transaction evaluates staleness one +final time against the same rule and freezes the result as the submission's +**late** flag. It does not change afterward, no matter what the conversation +does later. A late answer's record carries `"late": true` and: + +```text +late_notice: "The conversation moved on before this answer. Use it as context and ask for fresh confirmation before acting on the earlier request." +``` + +A form submission is never an authorization token for the action it was +originally asked about. The agent must still get explicit confirmation +before acting on a late answer, and any action tool that needs authorization +must enforce that itself — the forms feature only records what the user +chose. + +## `read_form` and the form index + +`read_form` takes a `form_id` (from the form index or an answer message) and +returns the state of one form belonging to the calling session; a form from +another session is not visible. Its result depends on the form's state: + +| `status` | Meaning | +| --- | --- | +| `unanswered` | Returns the form's `title` and `questions` (each with its options), so an agent that lost the original `ask_user` result can restate them | +| `answer_pending` | The user answered, but the answer has not been admitted into this session's history yet (see below). No answer values are returned — the agent must wait for the answer to arrive as a user message | +| `answered` | Returns the same self-contained record described above, plus `answered_at` | + +Every agent, with or without the trait, also gets a bounded, deterministic +index of the session's forms injected into its prompt (computed fresh on +every prompt build, not a copy that can drift): + +```text +Session forms (index; exact answers are in the answer messages and can be read with read_form when available): +- unanswered: "Delivery preference" form_id=... asked=... +- answer pending (arrives as a later user message): "Extras" form_id=... asked=... +- answered: "Order details" form_id=... answered=... late=false answer_message_id=... +(2 more unanswered and 1 more answered forms not listed) +``` + +The index lists up to 8 unanswered/pending forms (newest first) and up to 4 +answered forms (most recently answered first), bounded to 8 KiB, and reports +how many were omitted past that. A summarizing checkpoint is free text and +may drop form ids or values; this index is rebuilt from the stored artifacts +on every prompt, so it does not depend on the checkpoint having preserved +anything. + +## How answers are admitted + +Submitting a form's answer (see the frontend page for the HTTP contract) +commits the answer and the user message in one transaction, then publishes +an artifact-update event and wakes the owning session process. The row +itself, not the wake-up, is what makes delivery durable — a missed wake-up +does not lose the answer. + +Admission order follows the order answers were durably accepted, and depends +on what the session is doing: + +- **Idle session.** The answer is admitted immediately, and a new turn + starts to answer it. +- **A turn is running.** The answer stays out of that turn's prompt — it is + marked pending and `read_form` reports `answer_pending` for it — and is + admitted once the turn ends, in acceptance order together with any typed + input the session held during the turn. The next turn answers the latest + admitted message. +- **The user pressed Stop.** The answer is still admitted (it becomes + ordinary visible history), but no new turn starts for it. The form reads + as delivered; the user continues normally by sending a message. +- **The session is finishing, or the process is not running (idle timeout, + crash, restart).** The answer stays pending. The next time the session + process starts, it scans for pending answers before anything else and + queues their admission — recovery needs no external retry. + +The agent must never treat an `answer_pending` form as answered, and must +never guess its content before the real answer message arrives. + +## Security notes + +The answer message's text — the sentence and the record — is built entirely +by the server from the immutable definition and the validated, normalized +answers. The browser sends only structured `answers` keyed by field id; it +never sends message text. User-supplied text (an "Other" answer or a note) +is JSON-escaped data inside the record's `answer` object, never raw markup: +the server escapes `'`, `<`, `>`, and `&` inside the record so user text +cannot end the attribute, close the tag, or add markup. + +The trait's prompt explicitly tells the agent never to write a +`<wippy-form-answers>` element itself — the tag carries meaning only in the +exact wire format the server writes, and an agent-authored one would not +match a real accepted answer. + +Every state read or write checks authentication, then that the artifact +belongs to the caller and its session, then read (GET) or write (POST) +permission on that session, before doing anything with the form. A missing +artifact, another user's artifact, or an artifact whose session is gone or +not the caller's all return the same 404 — the endpoint does not reveal that +a foreign form exists. + +## Limits at a glance + +| Limit | Value | +| --- | --- | +| Form title | 160 characters | +| Description (form or field) | 1,000 characters | +| `submit_label` | 40 characters | +| `answered_message` | 200 characters | +| Fields per form | 1 to 20 | +| Field label | 240 characters | +| Options per field | 1 to 20 | +| Option text | 240 characters | +| "Other" answer text | 2,000 characters | +| Note text | 1,000 characters | +| Normalized definition size | 32 KiB | +| Submission request body | 64 KiB | +| Unresolved forms per session | 100 | +| Form index (prompt injection) | 8 unanswered/pending + 4 answered, 8 KiB total | + +There is no rate limit on form submission in V1. + +## Verifying + +Create or use an agent with the `wippy.session.forms:ask_user` trait, start a +session, and prompt it to ask a question that needs a decision. Confirm: the +question card appears in the chat, answering it produces a chat message with +exactly one visible sentence, and the agent's next turn correctly references +the answer (for example, by asking `read_form` or by acting on the choice). +To check late-answer handling, send a plain chat message after the form is +created but before answering it, then answer — the record should carry +`"late": true` and the agent should ask for confirmation before acting on +the original request. + +## See Also + +- [Session Forms (frontend)](../frontend/micro-frontends/session-forms.md) — the `wippy-form` / `wippy-form-answers` components, the artifact-state HTTP API, and the `artifactState` proxy client +- [Agents](agents.md) — traits, tools, and agent definitions in general diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md new file mode 100644 index 00000000..de3e3953 --- /dev/null +++ b/en/frontend/micro-frontends/session-forms.md @@ -0,0 +1,347 @@ +--- +title: "Session Forms" +description: "The wippy-form question card and the wippy-form-answers carrier element: what they render, how they load, and the artifact-state HTTP API behind them." +--- + +# Session Forms + +`wippy/session` ships two `view.component` web components that render a +Session `ask_user` form (see +[Session Forms (framework)](../../framework/session-forms.md) for the +`ask_user` tool and the answer contract): `<wippy-form>`, the interactive +question card, and `<wippy-form-answers>`, an invisible carrier that keeps a +form's answer record reachable to the agent without showing it to the user +twice. Like the chat elements in +[Chat Web Components](./chat-web-components.md), these are **host-provided +elements to consume** — the Session module registers and serves them; an +application embedding a chat surface does not author or bundle either one. + +## `<wippy-form>`: the question card + +For a V1 definition, every field is `type: "choice"`, and the component +renders a Claude-style question card rather than a plain fields form: one +question at a time for a several-question form, with a `‹ n/total ›` counter, +per-answer notes, an "Other" free-text row, a review step before sending, and +a read-only answered summary afterward. A mixed or non-`choice` definition +(reserved for a later release) falls back to a plain radio/checkbox fields +form. + +| Prop (HTML attribute) | Type | Default | Description | +| --- | --- | --- | --- | +| `form-version` | `number` | `1` | Definition schema version. A value other than `1` — from this prop or from the loaded state's own `form_version` — disables the interactive form and shows a compatibility notice instead of ever rendering a `Submit`. | +| `definition` | `object` | `null` | The immutable form definition: `title`, optional `description`, optional `submit_label`, optional `answered_message` (never displayed), and `fields`. | +| `state` | `string` | `"active"` | Package-tag lifecycle: `"active"` (answerable) or `"idle"` (already answered, read-only). Changing it reloads canonical state from the Host. | +| `density` | `string` | `"compact"` | `"compact"` or `"comfortable"` sizing. Read purely through a `:host([density="comfortable"])` CSS selector. | + +The component owns its own data loading (`GET` on mount, reload on +visibility change, a session-message event, or an artifact-update event), +submission (client-generated `request_id` reuse, one automatic retry on a +no-response network failure, and handling for a 422 field-error response and +a 409 already-submitted response), and offline detection. A host only needs +to mount the tag with these attributes. + +### Behavior + +- **One question at a time.** Answering (a click, or a number key for the + first nine rows) moves to the next unseen question; Previous/Next + navigate back to change an earlier answer. +- **Notes.** Every answer row has a note toggle. A note is the user's own + text about that one chosen option; it changes the answer's shape to + `{ "value": "…", "note": "…" }` rather than adding a separate field. +- **Other.** A joined free-text input with its own send button, offered only + when the field's `allow_other` is set. +- **Review step.** A several-question form ends on a review listing every + answer, with a single "Send answers" action — there is no per-question + submit once you reach it. +- **Answered summary.** Once submitted, the card shows a read-only summary + of exactly what was accepted, including any notes and the submission time. +- **No close or decline button**, and the card never takes focus on its own. + +Keyboard: number keys 1 to 9 answer or tick the corresponding row (the first +nine rows only — a question can have more options than that, they just don't +get a number); Shift+1–9 (or `N` on a focused row) opens that row's note; +Enter sends from Other or a note (or saves a note and ticks its row on a +several-answer question); Shift+Enter adds a line; Escape leaves a note or +Other box; arrow keys move between rows and between questions. All of it is +scoped to focus inside the card, so it never intercepts typing in the +surrounding chat composer. + +### Events + +| Event | Payload | When | +| --- | --- | --- | +| `answer-submitted` | `{ requestId, answerMessageId, late }` | After a submission is durably accepted, including an exact replay | +| `error` | `{ message, error }` | An unrecoverable component-level error | +| `invalid` | `{ message }` | Invalid props/config | + +## `<wippy-form-answers>`: the answer carrier + +The Session server writes this element into the user's chat message +immediately after they answer a form (see +[the record shape](../../framework/session-forms.md#record-shape)): + +```html +Answered questions about the delivery of your order. + +<wippy-form-answers record='{"form_id":"…","form_version":1,"title":"Order details","late":false,"answers":{...}}'> +</wippy-form-answers> +``` + +It renders nothing — no shadow-root content, no `<slot>`, and `:host { +display: none; }` as defense in depth. Its only prop is `record` (the +single-line JSON string); its only public member is a read-only +`answerRecord` getter that parses that attribute and returns the parsed +object, or `null` on missing/invalid JSON. It dispatches no events and makes +no host API calls of its own beyond the theme subscription every Wippy +element gets. + +**Why the record lives in an attribute, not text content.** Two failure +modes both leave the tag on the page with no children: the chat sanitizer +strips an unrecognized tag (for example, right after a fresh deploy, before +the Host has re-fetched the updated components list), and an unloaded or +failed component script leaves the browser treating the tag as an anonymous +`HTMLElement`, which still renders its children by default. An element with +no children renders nothing either way; one with visible text content would +have shown the raw JSON to the user for that entire window. Putting the +record in an attribute means every failure mode still shows nothing. + +**Agents must never emit this tag themselves.** It is written exclusively by +the Session server's message-composition code as part of the fixed answer +format; it carries no meaning outside that exact wire format. + +## How the components load + +Both are `view.component` registry entries with `auto_register: true`, +served by the Session module at `/wippy-session-forms` (`wippy-form`) and +`/wippy-session-form-answers` (`wippy-form-answers`). The Web Host auto-loads +every `auto_register: true` component at boot and allows its tag — plus its +declared prop attribute names, `definition`/`form-version`/`state`/`density` +for `wippy-form` and `record` for `wippy-form-answers` — through the chat +message sanitizer. `record` is declared as a `wippy.props` entry +specifically so the sanitizer's allowed-attribute list includes it; without +that declaration the attribute would still be stripped even with the tag +itself allowed through. + +## Host requirement + +`<wippy-form>` submits through `artifactState`, a typed client the Web Host +exports from every proxy realm (`$W.artifactState()` in an iframe, or the +named `artifactState` export from `@wippy-fe/proxy` in a host-mounted web +component). An older Host that predates this export shows the component in a +degraded, read-only state rather than failing silently: + +| Condition | What the card shows | +| --- | --- | +| Host has no `artifactState` export (older Web Host) | "This form needs a newer Web Host." | +| `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." | +| No artifact id is available in the element's context | The questions rendered read-only, with "This form cannot be submitted here." | + +None of these paths fabricate a success or a mock answer — see +[`instance.form` (deprecated)](#artifactstate-and-the-deprecated-instanceform) +below for the related history on the older adapter this replaced. + +## The artifact-state HTTP API + +`GET` / `POST /api/v1/artifact/{id}/state` reads a form's canonical state and +accepts its answer. The concrete path comes from the route table +(`artifacts.state`) and is overridable per deployment through +`feature.apiRoutes`, like any other Wippy Web Host route. + +### `GET /api/v1/artifact/{id}/state` + +```json +{ + "form_version": 1, + "artifact_id": "artifact-uuid", + "session_id": "session-uuid", + "status": "active", + "stale": false, + "late": false, + "content_version": 1, + "definition": { "title": "Delivery preference", "fields": [] }, + "data": null, + "submitted_at": null, + "answer_message_id": null, + "delivery": null +} +``` + +`status` is `"active"` (unanswered) or `"idle"` (answered). `stale` is +computed live and only meaningful while `status` is `"active"` — it is +`true` once a different real user input was durably accepted after the form +was created. `data` holds the exact accepted answers once answered, and +`delivery` reports `"pending"`, `"running"`, `"complete"`, or +`"interrupted"` for an answered form (never for an unanswered one), derived +from the message history rather than a stored flag. Responses always carry +`Cache-Control: no-store`. + +### `POST /api/v1/artifact/{id}/state` + +```json +{ + "form_version": 1, + "request_id": "client-generated-uuid", + "expected_content_version": 1, + "answers": { "delivery": "Courier" } +} +``` + +`request_id` should be generated once, at the moment the user attempts +submission, and reused unchanged on any retry of that same attempt — the +server recognizes a same-id, same-answers retry as a replay (`replayed: +true` in the response) rather than a conflict. `expected_content_version` is +optional; when present, it is checked against the artifact's current +revision so a stale client cannot silently overwrite a form's state. + +Success: + +```json +{ + "success": true, + "artifact_id": "artifact-uuid", + "request_id": "client-generated-uuid", + "answer_message_id": "message-uuid", + "content_version": 2, + "status": "idle", + "late": false, + "delivery": "pending", + "replayed": false +} +``` + +A `200` here means the answer and its user message are durably accepted — +not that the agent has replied yet. Show something like "Submitted. Waiting +for the assistant." + +| Status | Meaning | +| --- | --- | +| 200 | Accepted (or an exact replay of an already-accepted submission, `replayed: true`) | +| 400 | Malformed JSON, missing/invalid envelope fields, or a missing/invalid artifact id | +| 401 | No authenticated actor | +| 403 | Authenticated, but no read/write permission on the form's session | +| 404 | Artifact or session not found, not owned by the caller, or not a form | +| 409 `request_conflict` | Same `request_id`, different normalized answers than the first attempt with that id | +| 409 `already_submitted` | The form was already answered by a different request | +| 409 `version_conflict` | `expected_content_version` no longer matches the current revision | +| 413 | Request body over 64 KiB | +| 415 | `Content-Type` is not `application/json` | +| 422 | Field validation failed — `errors` keyed by field id, plus a `form_errors` list | +| 500 | Internal error; no mutation was applied | + +There is no `429` in V1 — submissions are not rate-limited server-side. + +## The `artifactState` proxy client + +```typescript +const client = (await $W.artifactState())('artifact-uuid') +// or, inside a web component: import { artifactState } from '@wippy-fe/proxy' + +const state = await client.get() +const result = await client.submit({ + form_version: 1, + request_id: crypto.randomUUID(), + expected_content_version: state.content_version, + answers: { color: 'blue' }, +}) +``` + +- The route is re-resolved fresh on every call — nothing is cached at + `artifactState(artifactId)` construction time, and no global config is + mutated. +- `artifactId` is validated up front: an empty or whitespace-only id throws + synchronously. +- Every failure — an HTTP status or a network error — rejects with a typed + `ArtifactStateError` (`status`, `code`, and, for a 422, `errors` keyed by + field id plus `formErrors`). It never fabricates a success or failure body. + +```typescript +try { + await client.submit(envelope) +} +catch (error) { + if (isArtifactStateError(error) && error.status === 422) { + // error.errors: Record<string, { code: string, message: string }[]> + } + throw error +} +``` + +Prefer `isArtifactStateError(error)` over `error instanceof +ArtifactStateError`: the class is built separately into every proxy entry +point and into the published `@wippy-fe/proxy` npm package, so an +`instanceof` check against a class imported from a *different* bundle's copy +can silently never match, even for an error that same client threw. +`isArtifactStateError` checks a realm-stable brand instead. (The class also +overrides `Symbol.hasInstance` to run the same check, so a plain +`instanceof` happens to work too — `isArtifactStateError` is just the +harder-to-get-wrong spelling.) + +### `artifactState` and the deprecated `instance.form` + +`instance.form.get()` / `.submit(data)` is a thin backward-compatibility +shim over `artifactState(appConfig.context.resourceId)`. It no longer +fabricates data on failure: a 422 still maps to the legacy `{ success: false, +errors }` shape, but every other failure (401, 404, 409, 5xx, network) now +rethrows instead of returning a randomized mock success or failure. New code +should call `instance.artifactState(artifactId)` directly rather than the +deprecated shim. + +## Styling API + +`<wippy-form>` follows the Session Forms styling contract: every visual +value is a `--wippy-form-*` custom property with a semantic theme-variable +fallback (never a raw hex as the primary fallback), every restylable piece +is exposed as a `::part()`, state is reflected as both a `<part>-<state>` +part and a `w-form__<part>--<state>` class, and state a stylesheet needs is +a host attribute (`density`, `card-state`, `collapsed`). The full token, +part, and host-attribute tables, plus a restyle example, live in the +package's own README (`frontend/wippy-form/README.md` in the `wippy/session` +source). `<wippy-form-answers>` has no visible surface and so exposes no +styling API at all — hiding the record is its entire purpose. + +## Accessibility + +Each question has an accessible group label (`role="radiogroup"` for a +single-selection field with `aria-required` when required, `role="group"` +for a multiple-selection field). Field-level errors are connected with +`aria-describedby` rather than a generic alert role, and a single polite +live region announces submission-result banners and validation-summary text +so a screen reader user hears the outcome without focus being yanked around. +The keyboard behavior described [above](#behavior) covers answering, +navigation, and notes without a pointer. + +## Known gaps + +- **D27: unchecked-control contrast.** The tick boxes, radio marks, and + input edges use the theme's existing surface-300/700 border colors as-is + (roughly 1.3–1.4:1 contrast), with no local override. This is deferred to + a theme-level fix, not specific to this component. +- **The four action buttons are unstyled PrimeVue defaults.** The two "Send" + buttons and the two composer send buttons follow the theme's own primary + button color, not `--wippy-form-accent`; an inline-style workaround that + routed them through the token was tried and reverted (it re-implemented + the theme's own button look by hand). Retinting `--wippy-form-accent` + alone leaves these four on the old color while rows, the counter, key + badges, and the focus ring follow the new one. +- **Notes and Other text-box color are the theme's own `.p-textarea` + default** — no `--wippy-form-input-bg` / `--wippy-form-input-border` + tokens exist yet. +- **A handful of V1 UI defaults were shipped without an explicit product + decision** and are revisited after V1: the note answer shape + (`{value, note}` vs. a separate field), that a newly opened card never + steals keyboard focus, that only backticks render as inline code (nothing + else gets Markdown-style formatting), and that only the first nine rows of + a question get a number-key badge with no cap on how many options a + question can have. + +## See Also + +- [Session Forms (framework)](../../framework/session-forms.md) — the + `ask_user` / `read_form` tools, the trait, and how an answer is admitted + into the conversation +- [Chat Web Components](./chat-web-components.md) — other host-provided, + auto-registered elements delivered the same way +- [Proxy API](./proxy-api.md) — the rest of `@wippy-fe/proxy` / + `getWippyApi()` +- [Web Component Recipe](./web-component.md) — building your own + `view.component`, for contrast with these host-provided ones diff --git a/en/manifest.json b/en/manifest.json index eb822d09..c1da8854 100644 --- a/en/manifest.json +++ b/en/manifest.json @@ -159,7 +159,8 @@ {"title": "Embeddings", "path": "framework/embeddings"}, {"title": "Bootloader", "path": "framework/bootloader"}, {"title": "Migrations", "path": "framework/migration"}, - {"title": "Usage Tracking", "path": "framework/usage"} + {"title": "Usage Tracking", "path": "framework/usage"}, + {"title": "Session Forms", "path": "framework/session-forms"} ] }, { @@ -200,6 +201,7 @@ {"title": "Page Recipe", "path": "frontend/micro-frontends/micro-frontend-app"}, {"title": "Web Component Recipe", "path": "frontend/micro-frontends/web-component"}, {"title": "Chat Web Components", "path": "frontend/micro-frontends/chat-web-components"}, + {"title": "Session Forms", "path": "frontend/micro-frontends/session-forms"}, {"title": "Proxy API", "path": "frontend/micro-frontends/proxy-api"}, {"title": "Surface Portability", "path": "frontend/micro-frontends/surface-portability"}, {"title": "Surface Migration", "path": "frontend/micro-frontends/surface-migration"}, From 36fb2e64c53016cb8fdcb7c4300a11c5180b4f22 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Wed, 30 Sep 2026 22:42:30 +0200 Subject: [PATCH 02/16] docs(session-forms): document steering exclusion, plugin recovery, and answer re-dating The framework page didn't mention that form answers are never steered into a running turn (unlike typed input, which follows the session's own steering trait), that the user's session plugin starts a stopped session holding an unadmitted answer both at plugin start and on each periodic scan, that the same plugin start settles stale "running" sessions with no live process back to idle, or that an admitted answer's message row is re-dated to the moment of admission while the artifact-state API's submitted_at keeps the original acceptance time. Brings the page in line with the Session README and the plugin/message-handler source. --- en/framework/session-forms.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/en/framework/session-forms.md b/en/framework/session-forms.md index 200d7666..e01ce62b 100644 --- a/en/framework/session-forms.md +++ b/en/framework/session-forms.md @@ -226,6 +226,14 @@ an artifact-update event and wakes the owning session process. The row itself, not the wake-up, is what makes delivery durable — a missed wake-up does not lose the answer. +A form answer is never steered into a running turn. It stays pending until +the turn ends, no matter how the session is configured. Typed input, by +contrast, follows the session's own steering setting. It can be admitted +mid-turn when the agent has the `wippy.session.traits:steering` trait, or +the session sets a `steer` input-policy override. Once a turn ends, pending +answers and any steered input the session held are admitted together, in +the order they were durably accepted. + Admission order follows the order answers were durably accepted, and depends on what the session is doing: @@ -244,6 +252,21 @@ on what the session is doing: process starts, it scans for pending answers before anything else and queues their admission — recovery needs no external retry. +The user's session plugin also drives this recovery from outside any one +session. It starts a stopped session that still holds an unadmitted answer, +once right after the plugin itself starts and again on every periodic scan +after that, so an answer is still delivered even if its original wake-up was +lost. The same plugin start also settles any of the user's sessions left +stored as "running" with no live process, for example after a runtime +restart, back to idle, so their form answers read as interrupted rather than +perpetually running. + +Once admitted, the answer's message row is re-dated to the moment of +admission rather than the moment it was accepted, so its place in the +visible history follows admission order. The `submitted_at` the +artifact-state API returns (see the frontend page) is unaffected and keeps +the original acceptance time. + The agent must never treat an `answer_pending` form as answered, and must never guess its content before the real answer message arrives. From 1187262c9a20a939d6dd12f8d5d939f2e9968cbd Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Wed, 30 Sep 2026 22:42:37 +0200 Subject: [PATCH 03/16] docs(session-forms): fix status codes and accessibility claims, drop narration The frontend page had drifted from the shipped code: a form artifact that exists but isn't a session form returns 400 not_a_form, not 404; the question card also reloads on the Host's @reconnect event and the browser's online event; and field errors render as role="alert" elements linked by aria-describedby, not aria-describedby "instead of" a role. The accessibility section now also covers the roving tabindex on a single-selection group, that Escape in a note or Other box keeps the typed draft, and where focus goes after a full submission. Also removes process narration and local decision ids ("D27", "tried and reverted", "no longer fabricates" / "now rethrows", "shipped without an explicit product decision") in favor of stating current behavior and defaults directly. --- en/frontend/micro-frontends/session-forms.md | 79 +++++++++++--------- 1 file changed, 44 insertions(+), 35 deletions(-) diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index de3e3953..b7f80330 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -34,11 +34,12 @@ form. | `density` | `string` | `"compact"` | `"compact"` or `"comfortable"` sizing. Read purely through a `:host([density="comfortable"])` CSS selector. | The component owns its own data loading (`GET` on mount, reload on -visibility change, a session-message event, or an artifact-update event), -submission (client-generated `request_id` reuse, one automatic retry on a -no-response network failure, and handling for a 422 field-error response and -a 409 already-submitted response), and offline detection. A host only needs -to mount the tag with these attributes. +visibility change, a session-message event, an artifact-update event, the +Host's `@reconnect` event after a WebSocket reconnect, or the browser's +`online` event), submission (client-generated `request_id` reuse, one +automatic retry on a no-response network failure, and handling for a 422 +field-error response and a 409 already-submitted response), and offline +detection. A host only needs to mount the tag with these attributes. ### Behavior @@ -216,10 +217,10 @@ for the assistant." | Status | Meaning | | --- | --- | | 200 | Accepted (or an exact replay of an already-accepted submission, `replayed: true`) | -| 400 | Malformed JSON, missing/invalid envelope fields, or a missing/invalid artifact id | +| 400 | Malformed JSON, missing/invalid envelope fields, a missing/invalid artifact id, or `not_a_form` for an artifact that exists but is not a session form | | 401 | No authenticated actor | | 403 | Authenticated, but no read/write permission on the form's session | -| 404 | Artifact or session not found, not owned by the caller, or not a form | +| 404 | Artifact or session not found, or not owned by the caller | | 409 `request_conflict` | Same `request_id`, different normalized answers than the first attempt with that id | | 409 `already_submitted` | The form was already answered by a different request | | 409 `version_conflict` | `expected_content_version` no longer matches the current revision | @@ -279,12 +280,12 @@ harder-to-get-wrong spelling.) ### `artifactState` and the deprecated `instance.form` `instance.form.get()` / `.submit(data)` is a thin backward-compatibility -shim over `artifactState(appConfig.context.resourceId)`. It no longer -fabricates data on failure: a 422 still maps to the legacy `{ success: false, -errors }` shape, but every other failure (401, 404, 409, 5xx, network) now -rethrows instead of returning a randomized mock success or failure. New code -should call `instance.artifactState(artifactId)` directly rather than the -deprecated shim. +shim over `artifactState(appConfig.context.resourceId)`. A 422 maps to the +legacy `{ success: false, errors }` shape. Every other failure (401, 404, +409, 5xx, network) rethrows the same error `artifactState` would throw, +rather than returning a mock success or failure. New code should call +`instance.artifactState(artifactId)` directly rather than this deprecated +shim. ## Styling API @@ -301,38 +302,46 @@ styling API at all — hiding the record is its entire purpose. ## Accessibility -Each question has an accessible group label (`role="radiogroup"` for a -single-selection field with `aria-required` when required, `role="group"` -for a multiple-selection field). Field-level errors are connected with -`aria-describedby` rather than a generic alert role, and a single polite -live region announces submission-result banners and validation-summary text -so a screen reader user hears the outcome without focus being yanked around. +Each question has an accessible group label: `role="radiogroup"` with +`aria-required` when required for a single-selection field, or `role="group"` +for a multiple-selection field. A single-selection group is one Tab stop, +with a roving `tabindex` that arrow keys move between its rows (the +WAI-ARIA radio group pattern). A multiple-selection group leaves every row +its own Tab stop instead, since each is an independent checkbox. +Field-level errors render as a `role="alert"` element, linked to its group +or text box through `aria-describedby`, so a screen reader announces the +error text as soon as it appears. A single polite live region announces +question and review navigation (for example "Question 2 of 4" or "Review +your answers"), tick/untick changes, and submission-result and +validation-summary text, without moving focus. + The keyboard behavior described [above](#behavior) covers answering, -navigation, and notes without a pointer. +navigation, and notes without a pointer, including that Escape in a note or +the Other box only closes the editor. The typed draft stays saved with that +answer and is not discarded. After a full submission is accepted, focus +moves to the read-only summary's status text, so it is not lost when the +card swaps from the active view to the answered one. ## Known gaps -- **D27: unchecked-control contrast.** The tick boxes, radio marks, and - input edges use the theme's existing surface-300/700 border colors as-is - (roughly 1.3–1.4:1 contrast), with no local override. This is deferred to - a theme-level fix, not specific to this component. +- **Unchecked-control contrast.** The tick boxes, radio marks, and input + edges use the theme's existing surface-300/700 border colors as-is + (roughly 1.3 to 1.4:1 contrast), with no local override. This needs a + theme-level fix, not one specific to this component. - **The four action buttons are unstyled PrimeVue defaults.** The two "Send" buttons and the two composer send buttons follow the theme's own primary - button color, not `--wippy-form-accent`; an inline-style workaround that - routed them through the token was tried and reverted (it re-implemented - the theme's own button look by hand). Retinting `--wippy-form-accent` + button color, not `--wippy-form-accent`. Retinting `--wippy-form-accent` alone leaves these four on the old color while rows, the counter, key badges, and the focus ring follow the new one. - **Notes and Other text-box color are the theme's own `.p-textarea` - default** — no `--wippy-form-input-bg` / `--wippy-form-input-border` + default.** No `--wippy-form-input-bg` / `--wippy-form-input-border` tokens exist yet. -- **A handful of V1 UI defaults were shipped without an explicit product - decision** and are revisited after V1: the note answer shape - (`{value, note}` vs. a separate field), that a newly opened card never - steals keyboard focus, that only backticks render as inline code (nothing - else gets Markdown-style formatting), and that only the first nine rows of - a question get a number-key badge with no cap on how many options a - question can have. +- **A few V1 defaults, revisited after V1:** the note answer shape + (`{value, note}` vs. a separate field), a newly opened card does not take + keyboard focus on its own, only backticks render as inline code (no other + Markdown-style formatting), and only the first nine rows of a question + get a number-key badge, with no cap on how many options a question can + have. ## See Also From 018e7c3020fa5848887fd2eaff6506099107fb73 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Wed, 30 Sep 2026 22:43:22 +0200 Subject: [PATCH 04/16] docs(session-forms): show the fallback sentence with its real quotes --- en/framework/session-forms.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/en/framework/session-forms.md b/en/framework/session-forms.md index e01ce62b..60d16b38 100644 --- a/en/framework/session-forms.md +++ b/en/framework/session-forms.md @@ -67,7 +67,7 @@ case, and the agent can retry in the same turn. | `title` | Required plain text, 1 to 160 characters | | `description` | Optional plain text, at most 1,000 characters | | `submit_label` | Optional plain text, at most 40 characters | -| `answered_message` | Optional plain text, at most 200 characters. The user's chat message once they answer, written in the user's own voice by the agent that asks (see [What the agent receives](#what-the-agent-receives)). Never shown on the form. A form asked without it falls back to `Answered "<title>".` | +| `answered_message` | Optional plain text, at most 200 characters. The user's chat message once they answer, written in the user's own voice by the agent that asks (see [What the agent receives](#what-the-agent-receives)). Never shown on the form. A form asked without it falls back to `Answered “<title>”.` | | `fields` | 1 to 20 entries | | `fields[].id` | Unique key matching `^[a-z][a-z0-9_]{0,39}$` | | `fields[].type` | `"choice"` (the only V1 type) | @@ -132,7 +132,7 @@ Answered questions about the delivery of your order. ``` The user sees only the first line: the `answered_message` the agent supplied -when it called `ask_user` (or the `Answered "<title>".` fallback). The +when it called `ask_user` (or the `Answered “<title>”.` fallback). The `wippy-form-answers` component the Session ships renders nothing, so the record never appears in the chat, but the raw message text — including the record attribute — is what the agent reads on its next turn. The answered From 944e9448861beb5877cd215dbfb4e6385c2a4442 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 1 Oct 2026 04:23:25 +0200 Subject: [PATCH 05/16] docs(session-forms): document enforced-Stop admission and rollback behavior An enforced Stop (the session plugin cancels/terminates a session that outlives the 10s deadline) now admits that turn's pending answers with no new turn, matching an honored Stop; the framework page described only the honored-Stop case. Also fix the plugin-recovery paragraph: "reads as interrupted" only applies to an answer already admitted before the process disappeared, not to one still pending, which is unaffected by the status settling and simply gets a turn on the next start. Add a rollback section: removing the ask_user trait is config-only and leaves open and answered forms readable; downgrading the Session module below the release that shipped forms is a separate, riskier action that can leave a consumer's own forms-related registry entries unresolved at boot (confirmed against a demo fixture; the trait-only case was not tested). --- en/framework/session-forms.md | 50 +++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/en/framework/session-forms.md b/en/framework/session-forms.md index 60d16b38..956b85bd 100644 --- a/en/framework/session-forms.md +++ b/en/framework/session-forms.md @@ -246,7 +246,12 @@ on what the session is doing: admitted message. - **The user pressed Stop.** The answer is still admitted (it becomes ordinary visible history), but no new turn starts for it. The form reads - as delivered; the user continues normally by sending a message. + as delivered; the user continues normally by sending a message. The same + holds when the session plugin has to enforce the Stop itself: if a turn + does not stop within 10 seconds, the plugin cancels, and then terminates, + the session process. Its pending answers are admitted with no turn exactly + as an honored Stop's would be — they do not wait for the next session + start to run an unattended turn. - **The session is finishing, or the process is not running (idle timeout, crash, restart).** The answer stays pending. The next time the session process starts, it scans for pending answers before anything else and @@ -256,10 +261,17 @@ The user's session plugin also drives this recovery from outside any one session. It starts a stopped session that still holds an unadmitted answer, once right after the plugin itself starts and again on every periodic scan after that, so an answer is still delivered even if its original wake-up was -lost. The same plugin start also settles any of the user's sessions left -stored as "running" with no live process, for example after a runtime -restart, back to idle, so their form answers read as interrupted rather than -perpetually running. +lost — that start admits the answer and runs a turn for it, like any other +session start with a pending answer. + +The same plugin start also settles any of the user's sessions left stored as +"running" with no live process, for example after a runtime restart, back to +idle. This settling only changes how an **already-admitted** answer reads: +one the turn had already picked up before the process disappeared now reads +as interrupted ("send a message to continue"), instead of perpetually +running. A **pending** answer is not affected by this settling at all — it +is unrelated to the session's stored status, and simply gets admitted with a +turn the next time the session starts, as described above. Once admitted, the answer's message row is re-dated to the moment of admission rather than the moment it was accepted, so its place in the @@ -292,6 +304,34 @@ artifact, another user's artifact, or an artifact whose session is gone or not the caller's all return the same 404 — the endpoint does not reveal that a foreign form exists. +## Disabling and rolling back + +Disabling new form creation is a config-only change: remove +`wippy.session.forms:ask_user` from an agent's `traits:` list. There is no +deploy step, no feature flag, and no separate kill switch for V1. + +- **Open (unanswered) forms stay answerable.** The state API's read/write + checks are session-ownership checks, not trait checks, so a form asked + before the trait was removed can still be submitted afterward. +- **Answered forms stay readable**, with or without the trait on any agent: + an answered form is an ordinary artifact plus an ordinary user chat + message, and `read_form` and the prompt's form index work the same for + every agent. +- **Do not downgrade the `wippy/session` module below the release that + shipped Session Forms while any form artifacts exist.** Rendering + `wippy-form` / `wippy-form-answers` needs their `view.component` registry + entries to still be registered and served by the running module version. + A consumer that also registers its own forms-related entries can fail to + boot entirely on an older module — confirmed in testing: pointing a demo + consumer at the last pre-forms Session release left one of its own + registry entries unresolved, and the whole runtime refused to start + (`failed to load state: unresolved dependencies after retry: …`). Whether + an agent's `wippy.session.forms:ask_user` trait reference alone (with no + consumer-side forms entries) would also block a boot on an older module + was not tested — treat it as an open risk, not a cleared case. Removing + the trait is the supported way to stop new forms; downgrading the module + itself is a separate, riskier action with this failure mode. + ## Limits at a glance | Limit | Value | From 3a3bbbf53d32d1b507d9f2909b1b341e71ff0149 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 1 Oct 2026 04:23:32 +0200 Subject: [PATCH 06/16] docs(session-forms): correct the Host requirement and add diagnostics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit State the actual Host requirement: no release up to and including 1.0.60 exports artifactState, so the requirement is the first Web Host release after 1.0.60 that includes Session Forms (version not assigned yet), with the npm @wippy-fe/proxy peer tracking the same release. Record a confirmed gap in the old-Host fallback: the component checks for an artifact id before it checks for Host capability, and no real old Host sets one without the other, so "needs a newer Web Host" is unreachable in practice — an old Host (tested against the published 1.0.59) always shows "This form cannot be submitted here." instead, with no crash, no mock data, and the chat sentence still readable. A fix is in progress but not in this release yet. Add a Diagnostics section: what each card-state value means, the two load-failure log lines and their one-per-tag dedup, and what @reconnect is for. --- en/frontend/micro-frontends/session-forms.md | 64 +++++++++++++++++--- 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index b7f80330..7d116e80 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -128,18 +128,39 @@ itself allowed through. `<wippy-form>` submits through `artifactState`, a typed client the Web Host exports from every proxy realm (`$W.artifactState()` in an iframe, or the named `artifactState` export from `@wippy-fe/proxy` in a host-mounted web -component). An older Host that predates this export shows the component in a -degraded, read-only state rather than failing silently: +component). No Web Host release up to and including 1.0.60 exports it. The +Host requirement for Session Forms is **the first Web Host release after +1.0.60 that includes Session Forms** — a specific version number has not +been assigned yet. The matching npm `@wippy-fe/proxy` peer version on the +`wippy-form` / `wippy-form-answers` packages tracks that same release once +it exists. + +None of the paths below fabricate a success or a mock answer — see +[`instance.form` (deprecated)](#artifactstate-and-the-deprecated-instanceform) +below for the related history on the older adapter this replaced. | Condition | What the card shows | | --- | --- | -| Host has no `artifactState` export (older Web Host) | "This form needs a newer Web Host." | -| `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." | | No artifact id is available in the element's context | The questions rendered read-only, with "This form cannot be submitted here." | +| An artifact id is available, but the Host has no `artifactState` export | "This form needs a newer Web Host." | +| `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." | -None of these paths fabricate a success or a mock answer — see -[`instance.form` (deprecated)](#artifactstate-and-the-deprecated-instanceform) -below for the related history on the older adapter this replaced. +**Known gap, confirmed in testing against the published Host 1.0.59.** Every +Web Host release that predates Session Forms also predates the +`data-wippy-artifact-id` attribute the component reads its artifact id from, +so in practice an old Host always hits the first row above — "This form +cannot be submitted here.", with every option rendered but disabled and no +accepted values shown — and never the second: the component checks for an +artifact id before it checks for the Host capability, and no real Host sets +one without the other. On the published 1.0.59 release, this was confirmed +harmless but unhelpful: the chat message's one visible sentence still read +correctly, there was no mock data and no crash, but neither an open nor an +already-answered form showed a useful message (an answered form's card +showed "—" in place of its accepted values). A fix to check the Host +capability directly, independent of the artifact id, is in progress and not +in this release yet. Until it lands, treat "This form cannot be submitted +here." on an old Host as the practical equivalent of "needs a newer Web +Host," not as a configuration problem to debug. ## The artifact-state HTTP API @@ -343,6 +364,35 @@ card swaps from the active view to the answered one. get a number-key badge, with no cap on how many options a question can have. +## Diagnostics + +`<wippy-form>` reflects its own state as the `card-state` host attribute. +It exists for styling, but it is also the fastest way to read what the +component is doing from the DOM or an end-to-end test: + +| `card-state` | Meaning | +| --- | --- | +| `loading` | Before the artifact's first `GET` resolves; `<wippy-loading>` shows instead of the card. | +| `active` | Answerable: a question, the review step, or briefly, the submitting state. | +| `review` | The review step of a several-question form, before "Send answers". | +| `answered` | The read-only summary of an accepted submission. | +| `unsupported` | An unrecognized `form-version` (from the prop or the loaded state). Takes priority over every other value — never an interactive or submittable card. | + +A missing or failed component bundle — the `wippy-form` script never +registers, or registration times out — never reaches any `card-state` +above: the Host's own component loader shows "This part of the page could +not load. Reload to try again." in its place. The real cause goes only to +the browser console, as one of two load-failure log lines: a script error +("script failed to load") or a registration timeout ("failed to load in +time"), logged once per failed tag rather than once per card that tried to +mount it. A later retry that successfully registers the tag updates every +card still waiting on it. + +A reload is also triggered by the proxy's `@reconnect` event — fired with no +payload after the Host's WebSocket reconnects following a drop — so a form +left stale through a brief backend restart or network blip corrects itself +once the socket comes back, without a manual page reload. + ## See Also - [Session Forms (framework)](../../framework/session-forms.md) — the From 374507e63142c30a5592129aa674f065508b7a14 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 1 Oct 2026 09:18:41 +0200 Subject: [PATCH 07/16] docs(session-forms): document the old-Host card, a missing bundle and the consumer sign-in requirement The old-Host fallback is fixed for new forms. On a Web Host without the artifactState export the card shows the questions with disabled options, no submit control and card-state "unsupported". The notice says the form needs a newer Web Host and that an answer already sent is in the chat. When the Host passes state "idle" it says the form was answered. This replaces the confirmed-gap text that said the notice was unreachable. The condition table now lists the checks in the order the component runs them. A bundle that failed to load is not retried in the page, because the browser keeps a failed script load for the life of the page, so the diagnostics now say to reload. The framework page gets a Compatibility section covering old Hosts, unknown form versions, a missing bundle, and the userspace/users 0.1.9 requirement for sign-in on runtime v0.3.43a. --- en/framework/session-forms.md | 18 +++++++ en/frontend/micro-frontends/session-forms.md | 54 +++++++++++--------- 2 files changed, 49 insertions(+), 23 deletions(-) diff --git a/en/framework/session-forms.md b/en/framework/session-forms.md index 956b85bd..baaa1281 100644 --- a/en/framework/session-forms.md +++ b/en/framework/session-forms.md @@ -332,6 +332,24 @@ deploy step, no feature flag, and no separate kill switch for V1. the trait is the supported way to stop new forms; downgrading the module itself is a separate, riskier action with this failure mode. +## Compatibility + +- **Web Host.** The question card submits through the `artifactState` client, + which only a Web Host release that includes Session Forms provides (see + [Host requirement](../frontend/micro-frontends/session-forms.md#host-requirement)). + On an older Host the card shows the questions with disabled options and a + notice that the form needs a newer Web Host, and nothing can be submitted. + The user's answer message and the agent's reply stay readable in the chat. +- **Unknown form version.** A form whose `form_version` is not `1` shows a + notice and never a submit control. +- **Missing component bundle.** The Host shows its load-failure fallback in + place of the card. Reloading the page is the way to recover. +- **Consumer applications on runtime v0.3.43a.** Sign-in needs + `userspace/users` 0.1.9 or later. A consumer whose lock pins 0.1.8 answers + the sign-in request with a 500 error from `user_groups_repo`, because 0.1.9 + adds the login security policies that 0.1.8 lacks. This was observed with + a consumer that has no Session Forms and does not depend on this feature. + ## Limits at a glance | Limit | Value | diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index 7d116e80..a81e1e11 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -139,28 +139,34 @@ None of the paths below fabricate a success or a mock answer — see [`instance.form` (deprecated)](#artifactstate-and-the-deprecated-instanceform) below for the related history on the older adapter this replaced. +The component checks the conditions in the order of this table, and the first +one that applies decides what the card shows. + | Condition | What the card shows | | --- | --- | -| No artifact id is available in the element's context | The questions rendered read-only, with "This form cannot be submitted here." | -| An artifact id is available, but the Host has no `artifactState` export | "This form needs a newer Web Host." | -| `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." | - -**Known gap, confirmed in testing against the published Host 1.0.59.** Every -Web Host release that predates Session Forms also predates the -`data-wippy-artifact-id` attribute the component reads its artifact id from, -so in practice an old Host always hits the first row above — "This form -cannot be submitted here.", with every option rendered but disabled and no -accepted values shown — and never the second: the component checks for an -artifact id before it checks for the Host capability, and no real Host sets -one without the other. On the published 1.0.59 release, this was confirmed -harmless but unhelpful: the chat message's one visible sentence still read -correctly, there was no mock data and no crash, but neither an open nor an -already-answered form showed a useful message (an answered form's card -showed "—" in place of its accepted values). A fix to check the Host -capability directly, independent of the artifact id, is in progress and not -in this release yet. Until it lands, treat "This form cannot be submitted -here." on an old Host as the practical equivalent of "needs a newer Web -Host," not as a configuration problem to debug. +| `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." The card reflects `card-state="unsupported"`. | +| The Host has no `artifactState` export (every Web Host release before Session Forms) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. | +| The Host exports `artifactState`, but no artifact id is available in the element's context | The questions rendered read-only, with "This form cannot be submitted here." | + +### Behavior on a Web Host that predates Session Forms + +A Web Host from before Session Forms has neither the `artifactState` export +nor the `data-wippy-artifact-id` attribute, so the component checks for the +export first. The card shows the real questions with disabled options, and +nothing on it can be submitted. Every option is unselected, because the saved +answer cannot be read without the artifact-state API, so the card cannot show +what was chosen. The notice therefore points to the chat, where the user's +one-line answer message and the agent's reply stay readable. The hidden +answer record never appears, and nothing is mocked. + +On the published Web Host 1.0.59 with the current Session, a newly asked form +shows the questions with disabled radio buttons, no buttons in the card, +`card-state="unsupported"`, and the "needs a newer Web Host" notice with no +placeholder rows. An older chat of answered forms shows the same notice on +each card and keeps its answer messages and agent replies readable. The +sentence about the answer being in the chat, and the "This form was answered" +variant, are covered by the component's unit tests. Both are planned to be +verified in a browser on a published 1.0.59 Host. ## The artifact-state HTTP API @@ -376,7 +382,7 @@ component is doing from the DOM or an end-to-end test: | `active` | Answerable: a question, the review step, or briefly, the submitting state. | | `review` | The review step of a several-question form, before "Send answers". | | `answered` | The read-only summary of an accepted submission. | -| `unsupported` | An unrecognized `form-version` (from the prop or the loaded state). Takes priority over every other value — never an interactive or submittable card. | +| `unsupported` | An unrecognized `form-version` (from the prop or the loaded state), or a Web Host without the `artifactState` export. Takes priority over every other value — never an interactive or submittable card. | A missing or failed component bundle — the `wippy-form` script never registers, or registration times out — never reaches any `card-state` @@ -385,8 +391,10 @@ not load. Reload to try again." in its place. The real cause goes only to the browser console, as one of two load-failure log lines: a script error ("script failed to load") or a registration timeout ("failed to load in time"), logged once per failed tag rather than once per card that tried to -mount it. A later retry that successfully registers the tag updates every -card still waiting on it. +mount it. The way to recover is to reload the page. The browser keeps a +failed script load for the life of the page, so the Host cannot fetch the +same bundle URL again, and a retry in the page does not help. Once the tag is +defined, every card still waiting on it updates without further action. A reload is also triggered by the proxy's `@reconnect` event — fired with no payload after the Host's WebSocket reconnects following a drop — so a form From ba88e83e60c60452c6b596765691536022a2f441 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 1 Oct 2026 09:56:10 +0200 Subject: [PATCH 08/16] docs(session-forms): state the old-Host card wording as observed --- en/frontend/micro-frontends/session-forms.md | 827 +++++++++---------- 1 file changed, 413 insertions(+), 414 deletions(-) diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index a81e1e11..3fe2088e 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -1,414 +1,413 @@ ---- -title: "Session Forms" -description: "The wippy-form question card and the wippy-form-answers carrier element: what they render, how they load, and the artifact-state HTTP API behind them." ---- - -# Session Forms - -`wippy/session` ships two `view.component` web components that render a -Session `ask_user` form (see -[Session Forms (framework)](../../framework/session-forms.md) for the -`ask_user` tool and the answer contract): `<wippy-form>`, the interactive -question card, and `<wippy-form-answers>`, an invisible carrier that keeps a -form's answer record reachable to the agent without showing it to the user -twice. Like the chat elements in -[Chat Web Components](./chat-web-components.md), these are **host-provided -elements to consume** — the Session module registers and serves them; an -application embedding a chat surface does not author or bundle either one. - -## `<wippy-form>`: the question card - -For a V1 definition, every field is `type: "choice"`, and the component -renders a Claude-style question card rather than a plain fields form: one -question at a time for a several-question form, with a `‹ n/total ›` counter, -per-answer notes, an "Other" free-text row, a review step before sending, and -a read-only answered summary afterward. A mixed or non-`choice` definition -(reserved for a later release) falls back to a plain radio/checkbox fields -form. - -| Prop (HTML attribute) | Type | Default | Description | -| --- | --- | --- | --- | -| `form-version` | `number` | `1` | Definition schema version. A value other than `1` — from this prop or from the loaded state's own `form_version` — disables the interactive form and shows a compatibility notice instead of ever rendering a `Submit`. | -| `definition` | `object` | `null` | The immutable form definition: `title`, optional `description`, optional `submit_label`, optional `answered_message` (never displayed), and `fields`. | -| `state` | `string` | `"active"` | Package-tag lifecycle: `"active"` (answerable) or `"idle"` (already answered, read-only). Changing it reloads canonical state from the Host. | -| `density` | `string` | `"compact"` | `"compact"` or `"comfortable"` sizing. Read purely through a `:host([density="comfortable"])` CSS selector. | - -The component owns its own data loading (`GET` on mount, reload on -visibility change, a session-message event, an artifact-update event, the -Host's `@reconnect` event after a WebSocket reconnect, or the browser's -`online` event), submission (client-generated `request_id` reuse, one -automatic retry on a no-response network failure, and handling for a 422 -field-error response and a 409 already-submitted response), and offline -detection. A host only needs to mount the tag with these attributes. - -### Behavior - -- **One question at a time.** Answering (a click, or a number key for the - first nine rows) moves to the next unseen question; Previous/Next - navigate back to change an earlier answer. -- **Notes.** Every answer row has a note toggle. A note is the user's own - text about that one chosen option; it changes the answer's shape to - `{ "value": "…", "note": "…" }` rather than adding a separate field. -- **Other.** A joined free-text input with its own send button, offered only - when the field's `allow_other` is set. -- **Review step.** A several-question form ends on a review listing every - answer, with a single "Send answers" action — there is no per-question - submit once you reach it. -- **Answered summary.** Once submitted, the card shows a read-only summary - of exactly what was accepted, including any notes and the submission time. -- **No close or decline button**, and the card never takes focus on its own. - -Keyboard: number keys 1 to 9 answer or tick the corresponding row (the first -nine rows only — a question can have more options than that, they just don't -get a number); Shift+1–9 (or `N` on a focused row) opens that row's note; -Enter sends from Other or a note (or saves a note and ticks its row on a -several-answer question); Shift+Enter adds a line; Escape leaves a note or -Other box; arrow keys move between rows and between questions. All of it is -scoped to focus inside the card, so it never intercepts typing in the -surrounding chat composer. - -### Events - -| Event | Payload | When | -| --- | --- | --- | -| `answer-submitted` | `{ requestId, answerMessageId, late }` | After a submission is durably accepted, including an exact replay | -| `error` | `{ message, error }` | An unrecoverable component-level error | -| `invalid` | `{ message }` | Invalid props/config | - -## `<wippy-form-answers>`: the answer carrier - -The Session server writes this element into the user's chat message -immediately after they answer a form (see -[the record shape](../../framework/session-forms.md#record-shape)): - -```html -Answered questions about the delivery of your order. - -<wippy-form-answers record='{"form_id":"…","form_version":1,"title":"Order details","late":false,"answers":{...}}'> -</wippy-form-answers> -``` - -It renders nothing — no shadow-root content, no `<slot>`, and `:host { -display: none; }` as defense in depth. Its only prop is `record` (the -single-line JSON string); its only public member is a read-only -`answerRecord` getter that parses that attribute and returns the parsed -object, or `null` on missing/invalid JSON. It dispatches no events and makes -no host API calls of its own beyond the theme subscription every Wippy -element gets. - -**Why the record lives in an attribute, not text content.** Two failure -modes both leave the tag on the page with no children: the chat sanitizer -strips an unrecognized tag (for example, right after a fresh deploy, before -the Host has re-fetched the updated components list), and an unloaded or -failed component script leaves the browser treating the tag as an anonymous -`HTMLElement`, which still renders its children by default. An element with -no children renders nothing either way; one with visible text content would -have shown the raw JSON to the user for that entire window. Putting the -record in an attribute means every failure mode still shows nothing. - -**Agents must never emit this tag themselves.** It is written exclusively by -the Session server's message-composition code as part of the fixed answer -format; it carries no meaning outside that exact wire format. - -## How the components load - -Both are `view.component` registry entries with `auto_register: true`, -served by the Session module at `/wippy-session-forms` (`wippy-form`) and -`/wippy-session-form-answers` (`wippy-form-answers`). The Web Host auto-loads -every `auto_register: true` component at boot and allows its tag — plus its -declared prop attribute names, `definition`/`form-version`/`state`/`density` -for `wippy-form` and `record` for `wippy-form-answers` — through the chat -message sanitizer. `record` is declared as a `wippy.props` entry -specifically so the sanitizer's allowed-attribute list includes it; without -that declaration the attribute would still be stripped even with the tag -itself allowed through. - -## Host requirement - -`<wippy-form>` submits through `artifactState`, a typed client the Web Host -exports from every proxy realm (`$W.artifactState()` in an iframe, or the -named `artifactState` export from `@wippy-fe/proxy` in a host-mounted web -component). No Web Host release up to and including 1.0.60 exports it. The -Host requirement for Session Forms is **the first Web Host release after -1.0.60 that includes Session Forms** — a specific version number has not -been assigned yet. The matching npm `@wippy-fe/proxy` peer version on the -`wippy-form` / `wippy-form-answers` packages tracks that same release once -it exists. - -None of the paths below fabricate a success or a mock answer — see -[`instance.form` (deprecated)](#artifactstate-and-the-deprecated-instanceform) -below for the related history on the older adapter this replaced. - -The component checks the conditions in the order of this table, and the first -one that applies decides what the card shows. - -| Condition | What the card shows | -| --- | --- | -| `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." The card reflects `card-state="unsupported"`. | -| The Host has no `artifactState` export (every Web Host release before Session Forms) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. | -| The Host exports `artifactState`, but no artifact id is available in the element's context | The questions rendered read-only, with "This form cannot be submitted here." | - -### Behavior on a Web Host that predates Session Forms - -A Web Host from before Session Forms has neither the `artifactState` export -nor the `data-wippy-artifact-id` attribute, so the component checks for the -export first. The card shows the real questions with disabled options, and -nothing on it can be submitted. Every option is unselected, because the saved -answer cannot be read without the artifact-state API, so the card cannot show -what was chosen. The notice therefore points to the chat, where the user's -one-line answer message and the agent's reply stay readable. The hidden -answer record never appears, and nothing is mocked. - -On the published Web Host 1.0.59 with the current Session, a newly asked form -shows the questions with disabled radio buttons, no buttons in the card, -`card-state="unsupported"`, and the "needs a newer Web Host" notice with no -placeholder rows. An older chat of answered forms shows the same notice on -each card and keeps its answer messages and agent replies readable. The -sentence about the answer being in the chat, and the "This form was answered" -variant, are covered by the component's unit tests. Both are planned to be -verified in a browser on a published 1.0.59 Host. - -## The artifact-state HTTP API - -`GET` / `POST /api/v1/artifact/{id}/state` reads a form's canonical state and -accepts its answer. The concrete path comes from the route table -(`artifacts.state`) and is overridable per deployment through -`feature.apiRoutes`, like any other Wippy Web Host route. - -### `GET /api/v1/artifact/{id}/state` - -```json -{ - "form_version": 1, - "artifact_id": "artifact-uuid", - "session_id": "session-uuid", - "status": "active", - "stale": false, - "late": false, - "content_version": 1, - "definition": { "title": "Delivery preference", "fields": [] }, - "data": null, - "submitted_at": null, - "answer_message_id": null, - "delivery": null -} -``` - -`status` is `"active"` (unanswered) or `"idle"` (answered). `stale` is -computed live and only meaningful while `status` is `"active"` — it is -`true` once a different real user input was durably accepted after the form -was created. `data` holds the exact accepted answers once answered, and -`delivery` reports `"pending"`, `"running"`, `"complete"`, or -`"interrupted"` for an answered form (never for an unanswered one), derived -from the message history rather than a stored flag. Responses always carry -`Cache-Control: no-store`. - -### `POST /api/v1/artifact/{id}/state` - -```json -{ - "form_version": 1, - "request_id": "client-generated-uuid", - "expected_content_version": 1, - "answers": { "delivery": "Courier" } -} -``` - -`request_id` should be generated once, at the moment the user attempts -submission, and reused unchanged on any retry of that same attempt — the -server recognizes a same-id, same-answers retry as a replay (`replayed: -true` in the response) rather than a conflict. `expected_content_version` is -optional; when present, it is checked against the artifact's current -revision so a stale client cannot silently overwrite a form's state. - -Success: - -```json -{ - "success": true, - "artifact_id": "artifact-uuid", - "request_id": "client-generated-uuid", - "answer_message_id": "message-uuid", - "content_version": 2, - "status": "idle", - "late": false, - "delivery": "pending", - "replayed": false -} -``` - -A `200` here means the answer and its user message are durably accepted — -not that the agent has replied yet. Show something like "Submitted. Waiting -for the assistant." - -| Status | Meaning | -| --- | --- | -| 200 | Accepted (or an exact replay of an already-accepted submission, `replayed: true`) | -| 400 | Malformed JSON, missing/invalid envelope fields, a missing/invalid artifact id, or `not_a_form` for an artifact that exists but is not a session form | -| 401 | No authenticated actor | -| 403 | Authenticated, but no read/write permission on the form's session | -| 404 | Artifact or session not found, or not owned by the caller | -| 409 `request_conflict` | Same `request_id`, different normalized answers than the first attempt with that id | -| 409 `already_submitted` | The form was already answered by a different request | -| 409 `version_conflict` | `expected_content_version` no longer matches the current revision | -| 413 | Request body over 64 KiB | -| 415 | `Content-Type` is not `application/json` | -| 422 | Field validation failed — `errors` keyed by field id, plus a `form_errors` list | -| 500 | Internal error; no mutation was applied | - -There is no `429` in V1 — submissions are not rate-limited server-side. - -## The `artifactState` proxy client - -```typescript -const client = (await $W.artifactState())('artifact-uuid') -// or, inside a web component: import { artifactState } from '@wippy-fe/proxy' - -const state = await client.get() -const result = await client.submit({ - form_version: 1, - request_id: crypto.randomUUID(), - expected_content_version: state.content_version, - answers: { color: 'blue' }, -}) -``` - -- The route is re-resolved fresh on every call — nothing is cached at - `artifactState(artifactId)` construction time, and no global config is - mutated. -- `artifactId` is validated up front: an empty or whitespace-only id throws - synchronously. -- Every failure — an HTTP status or a network error — rejects with a typed - `ArtifactStateError` (`status`, `code`, and, for a 422, `errors` keyed by - field id plus `formErrors`). It never fabricates a success or failure body. - -```typescript -try { - await client.submit(envelope) -} -catch (error) { - if (isArtifactStateError(error) && error.status === 422) { - // error.errors: Record<string, { code: string, message: string }[]> - } - throw error -} -``` - -Prefer `isArtifactStateError(error)` over `error instanceof -ArtifactStateError`: the class is built separately into every proxy entry -point and into the published `@wippy-fe/proxy` npm package, so an -`instanceof` check against a class imported from a *different* bundle's copy -can silently never match, even for an error that same client threw. -`isArtifactStateError` checks a realm-stable brand instead. (The class also -overrides `Symbol.hasInstance` to run the same check, so a plain -`instanceof` happens to work too — `isArtifactStateError` is just the -harder-to-get-wrong spelling.) - -### `artifactState` and the deprecated `instance.form` - -`instance.form.get()` / `.submit(data)` is a thin backward-compatibility -shim over `artifactState(appConfig.context.resourceId)`. A 422 maps to the -legacy `{ success: false, errors }` shape. Every other failure (401, 404, -409, 5xx, network) rethrows the same error `artifactState` would throw, -rather than returning a mock success or failure. New code should call -`instance.artifactState(artifactId)` directly rather than this deprecated -shim. - -## Styling API - -`<wippy-form>` follows the Session Forms styling contract: every visual -value is a `--wippy-form-*` custom property with a semantic theme-variable -fallback (never a raw hex as the primary fallback), every restylable piece -is exposed as a `::part()`, state is reflected as both a `<part>-<state>` -part and a `w-form__<part>--<state>` class, and state a stylesheet needs is -a host attribute (`density`, `card-state`, `collapsed`). The full token, -part, and host-attribute tables, plus a restyle example, live in the -package's own README (`frontend/wippy-form/README.md` in the `wippy/session` -source). `<wippy-form-answers>` has no visible surface and so exposes no -styling API at all — hiding the record is its entire purpose. - -## Accessibility - -Each question has an accessible group label: `role="radiogroup"` with -`aria-required` when required for a single-selection field, or `role="group"` -for a multiple-selection field. A single-selection group is one Tab stop, -with a roving `tabindex` that arrow keys move between its rows (the -WAI-ARIA radio group pattern). A multiple-selection group leaves every row -its own Tab stop instead, since each is an independent checkbox. -Field-level errors render as a `role="alert"` element, linked to its group -or text box through `aria-describedby`, so a screen reader announces the -error text as soon as it appears. A single polite live region announces -question and review navigation (for example "Question 2 of 4" or "Review -your answers"), tick/untick changes, and submission-result and -validation-summary text, without moving focus. - -The keyboard behavior described [above](#behavior) covers answering, -navigation, and notes without a pointer, including that Escape in a note or -the Other box only closes the editor. The typed draft stays saved with that -answer and is not discarded. After a full submission is accepted, focus -moves to the read-only summary's status text, so it is not lost when the -card swaps from the active view to the answered one. - -## Known gaps - -- **Unchecked-control contrast.** The tick boxes, radio marks, and input - edges use the theme's existing surface-300/700 border colors as-is - (roughly 1.3 to 1.4:1 contrast), with no local override. This needs a - theme-level fix, not one specific to this component. -- **The four action buttons are unstyled PrimeVue defaults.** The two "Send" - buttons and the two composer send buttons follow the theme's own primary - button color, not `--wippy-form-accent`. Retinting `--wippy-form-accent` - alone leaves these four on the old color while rows, the counter, key - badges, and the focus ring follow the new one. -- **Notes and Other text-box color are the theme's own `.p-textarea` - default.** No `--wippy-form-input-bg` / `--wippy-form-input-border` - tokens exist yet. -- **A few V1 defaults, revisited after V1:** the note answer shape - (`{value, note}` vs. a separate field), a newly opened card does not take - keyboard focus on its own, only backticks render as inline code (no other - Markdown-style formatting), and only the first nine rows of a question - get a number-key badge, with no cap on how many options a question can - have. - -## Diagnostics - -`<wippy-form>` reflects its own state as the `card-state` host attribute. -It exists for styling, but it is also the fastest way to read what the -component is doing from the DOM or an end-to-end test: - -| `card-state` | Meaning | -| --- | --- | -| `loading` | Before the artifact's first `GET` resolves; `<wippy-loading>` shows instead of the card. | -| `active` | Answerable: a question, the review step, or briefly, the submitting state. | -| `review` | The review step of a several-question form, before "Send answers". | -| `answered` | The read-only summary of an accepted submission. | -| `unsupported` | An unrecognized `form-version` (from the prop or the loaded state), or a Web Host without the `artifactState` export. Takes priority over every other value — never an interactive or submittable card. | - -A missing or failed component bundle — the `wippy-form` script never -registers, or registration times out — never reaches any `card-state` -above: the Host's own component loader shows "This part of the page could -not load. Reload to try again." in its place. The real cause goes only to -the browser console, as one of two load-failure log lines: a script error -("script failed to load") or a registration timeout ("failed to load in -time"), logged once per failed tag rather than once per card that tried to -mount it. The way to recover is to reload the page. The browser keeps a -failed script load for the life of the page, so the Host cannot fetch the -same bundle URL again, and a retry in the page does not help. Once the tag is -defined, every card still waiting on it updates without further action. - -A reload is also triggered by the proxy's `@reconnect` event — fired with no -payload after the Host's WebSocket reconnects following a drop — so a form -left stale through a brief backend restart or network blip corrects itself -once the socket comes back, without a manual page reload. - -## See Also - -- [Session Forms (framework)](../../framework/session-forms.md) — the - `ask_user` / `read_form` tools, the trait, and how an answer is admitted - into the conversation -- [Chat Web Components](./chat-web-components.md) — other host-provided, - auto-registered elements delivered the same way -- [Proxy API](./proxy-api.md) — the rest of `@wippy-fe/proxy` / - `getWippyApi()` -- [Web Component Recipe](./web-component.md) — building your own - `view.component`, for contrast with these host-provided ones +--- +title: "Session Forms" +description: "The wippy-form question card and the wippy-form-answers carrier element: what they render, how they load, and the artifact-state HTTP API behind them." +--- + +# Session Forms + +`wippy/session` ships two `view.component` web components that render a +Session `ask_user` form (see +[Session Forms (framework)](../../framework/session-forms.md) for the +`ask_user` tool and the answer contract): `<wippy-form>`, the interactive +question card, and `<wippy-form-answers>`, an invisible carrier that keeps a +form's answer record reachable to the agent without showing it to the user +twice. Like the chat elements in +[Chat Web Components](./chat-web-components.md), these are **host-provided +elements to consume** — the Session module registers and serves them; an +application embedding a chat surface does not author or bundle either one. + +## `<wippy-form>`: the question card + +For a V1 definition, every field is `type: "choice"`, and the component +renders a Claude-style question card rather than a plain fields form: one +question at a time for a several-question form, with a `‹ n/total ›` counter, +per-answer notes, an "Other" free-text row, a review step before sending, and +a read-only answered summary afterward. A mixed or non-`choice` definition +(reserved for a later release) falls back to a plain radio/checkbox fields +form. + +| Prop (HTML attribute) | Type | Default | Description | +| --- | --- | --- | --- | +| `form-version` | `number` | `1` | Definition schema version. A value other than `1` — from this prop or from the loaded state's own `form_version` — disables the interactive form and shows a compatibility notice instead of ever rendering a `Submit`. | +| `definition` | `object` | `null` | The immutable form definition: `title`, optional `description`, optional `submit_label`, optional `answered_message` (never displayed), and `fields`. | +| `state` | `string` | `"active"` | Package-tag lifecycle: `"active"` (answerable) or `"idle"` (already answered, read-only). Changing it reloads canonical state from the Host. | +| `density` | `string` | `"compact"` | `"compact"` or `"comfortable"` sizing. Read purely through a `:host([density="comfortable"])` CSS selector. | + +The component owns its own data loading (`GET` on mount, reload on +visibility change, a session-message event, an artifact-update event, the +Host's `@reconnect` event after a WebSocket reconnect, or the browser's +`online` event), submission (client-generated `request_id` reuse, one +automatic retry on a no-response network failure, and handling for a 422 +field-error response and a 409 already-submitted response), and offline +detection. A host only needs to mount the tag with these attributes. + +### Behavior + +- **One question at a time.** Answering (a click, or a number key for the + first nine rows) moves to the next unseen question; Previous/Next + navigate back to change an earlier answer. +- **Notes.** Every answer row has a note toggle. A note is the user's own + text about that one chosen option; it changes the answer's shape to + `{ "value": "…", "note": "…" }` rather than adding a separate field. +- **Other.** A joined free-text input with its own send button, offered only + when the field's `allow_other` is set. +- **Review step.** A several-question form ends on a review listing every + answer, with a single "Send answers" action — there is no per-question + submit once you reach it. +- **Answered summary.** Once submitted, the card shows a read-only summary + of exactly what was accepted, including any notes and the submission time. +- **No close or decline button**, and the card never takes focus on its own. + +Keyboard: number keys 1 to 9 answer or tick the corresponding row (the first +nine rows only — a question can have more options than that, they just don't +get a number); Shift+1–9 (or `N` on a focused row) opens that row's note; +Enter sends from Other or a note (or saves a note and ticks its row on a +several-answer question); Shift+Enter adds a line; Escape leaves a note or +Other box; arrow keys move between rows and between questions. All of it is +scoped to focus inside the card, so it never intercepts typing in the +surrounding chat composer. + +### Events + +| Event | Payload | When | +| --- | --- | --- | +| `answer-submitted` | `{ requestId, answerMessageId, late }` | After a submission is durably accepted, including an exact replay | +| `error` | `{ message, error }` | An unrecoverable component-level error | +| `invalid` | `{ message }` | Invalid props/config | + +## `<wippy-form-answers>`: the answer carrier + +The Session server writes this element into the user's chat message +immediately after they answer a form (see +[the record shape](../../framework/session-forms.md#record-shape)): + +```html +Answered questions about the delivery of your order. + +<wippy-form-answers record='{"form_id":"…","form_version":1,"title":"Order details","late":false,"answers":{...}}'> +</wippy-form-answers> +``` + +It renders nothing — no shadow-root content, no `<slot>`, and `:host { +display: none; }` as defense in depth. Its only prop is `record` (the +single-line JSON string); its only public member is a read-only +`answerRecord` getter that parses that attribute and returns the parsed +object, or `null` on missing/invalid JSON. It dispatches no events and makes +no host API calls of its own beyond the theme subscription every Wippy +element gets. + +**Why the record lives in an attribute, not text content.** Two failure +modes both leave the tag on the page with no children: the chat sanitizer +strips an unrecognized tag (for example, right after a fresh deploy, before +the Host has re-fetched the updated components list), and an unloaded or +failed component script leaves the browser treating the tag as an anonymous +`HTMLElement`, which still renders its children by default. An element with +no children renders nothing either way; one with visible text content would +have shown the raw JSON to the user for that entire window. Putting the +record in an attribute means every failure mode still shows nothing. + +**Agents must never emit this tag themselves.** It is written exclusively by +the Session server's message-composition code as part of the fixed answer +format; it carries no meaning outside that exact wire format. + +## How the components load + +Both are `view.component` registry entries with `auto_register: true`, +served by the Session module at `/wippy-session-forms` (`wippy-form`) and +`/wippy-session-form-answers` (`wippy-form-answers`). The Web Host auto-loads +every `auto_register: true` component at boot and allows its tag — plus its +declared prop attribute names, `definition`/`form-version`/`state`/`density` +for `wippy-form` and `record` for `wippy-form-answers` — through the chat +message sanitizer. `record` is declared as a `wippy.props` entry +specifically so the sanitizer's allowed-attribute list includes it; without +that declaration the attribute would still be stripped even with the tag +itself allowed through. + +## Host requirement + +`<wippy-form>` submits through `artifactState`, a typed client the Web Host +exports from every proxy realm (`$W.artifactState()` in an iframe, or the +named `artifactState` export from `@wippy-fe/proxy` in a host-mounted web +component). No Web Host release up to and including 1.0.60 exports it. The +Host requirement for Session Forms is **the first Web Host release after +1.0.60 that includes Session Forms** — a specific version number has not +been assigned yet. The matching npm `@wippy-fe/proxy` peer version on the +`wippy-form` / `wippy-form-answers` packages tracks that same release once +it exists. + +None of the paths below fabricate a success or a mock answer — see +[`instance.form` (deprecated)](#artifactstate-and-the-deprecated-instanceform) +below for the related history on the older adapter this replaced. + +The component checks the conditions in the order of this table, and the first +one that applies decides what the card shows. + +| Condition | What the card shows | +| --- | --- | +| `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." The card reflects `card-state="unsupported"`. | +| The Host has no `artifactState` export (every Web Host release before Session Forms) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. | +| The Host exports `artifactState`, but no artifact id is available in the element's context | The questions rendered read-only, with "This form cannot be submitted here." | + +### Behavior on a Web Host that predates Session Forms + +A Web Host from before Session Forms has neither the `artifactState` export +nor the `data-wippy-artifact-id` attribute, so the component checks for the +export first. The card shows the real questions with disabled options, and +nothing on it can be submitted. Every option is unselected, because the saved +answer cannot be read without the artifact-state API, so the card cannot show +what was chosen. The notice therefore points to the chat, where the user's +one-line answer message and the agent's reply stay readable. The hidden +answer record never appears, and nothing is mocked. + +On the published Web Host 1.0.59 with the current Session, a newly asked form +shows the questions with disabled radio buttons, no buttons in the card, +`card-state="unsupported"`, and the "needs a newer Web Host" notice with no +placeholder rows, and the notice reads "This form needs a newer Web Host. If +you already answered it, your answer is in the chat." In a chat of answered +forms, each card reads "This form was answered. Your answer is in the chat.", +and the answer messages and agent replies stay readable. + +## The artifact-state HTTP API + +`GET` / `POST /api/v1/artifact/{id}/state` reads a form's canonical state and +accepts its answer. The concrete path comes from the route table +(`artifacts.state`) and is overridable per deployment through +`feature.apiRoutes`, like any other Wippy Web Host route. + +### `GET /api/v1/artifact/{id}/state` + +```json +{ + "form_version": 1, + "artifact_id": "artifact-uuid", + "session_id": "session-uuid", + "status": "active", + "stale": false, + "late": false, + "content_version": 1, + "definition": { "title": "Delivery preference", "fields": [] }, + "data": null, + "submitted_at": null, + "answer_message_id": null, + "delivery": null +} +``` + +`status` is `"active"` (unanswered) or `"idle"` (answered). `stale` is +computed live and only meaningful while `status` is `"active"` — it is +`true` once a different real user input was durably accepted after the form +was created. `data` holds the exact accepted answers once answered, and +`delivery` reports `"pending"`, `"running"`, `"complete"`, or +`"interrupted"` for an answered form (never for an unanswered one), derived +from the message history rather than a stored flag. Responses always carry +`Cache-Control: no-store`. + +### `POST /api/v1/artifact/{id}/state` + +```json +{ + "form_version": 1, + "request_id": "client-generated-uuid", + "expected_content_version": 1, + "answers": { "delivery": "Courier" } +} +``` + +`request_id` should be generated once, at the moment the user attempts +submission, and reused unchanged on any retry of that same attempt — the +server recognizes a same-id, same-answers retry as a replay (`replayed: +true` in the response) rather than a conflict. `expected_content_version` is +optional; when present, it is checked against the artifact's current +revision so a stale client cannot silently overwrite a form's state. + +Success: + +```json +{ + "success": true, + "artifact_id": "artifact-uuid", + "request_id": "client-generated-uuid", + "answer_message_id": "message-uuid", + "content_version": 2, + "status": "idle", + "late": false, + "delivery": "pending", + "replayed": false +} +``` + +A `200` here means the answer and its user message are durably accepted — +not that the agent has replied yet. Show something like "Submitted. Waiting +for the assistant." + +| Status | Meaning | +| --- | --- | +| 200 | Accepted (or an exact replay of an already-accepted submission, `replayed: true`) | +| 400 | Malformed JSON, missing/invalid envelope fields, a missing/invalid artifact id, or `not_a_form` for an artifact that exists but is not a session form | +| 401 | No authenticated actor | +| 403 | Authenticated, but no read/write permission on the form's session | +| 404 | Artifact or session not found, or not owned by the caller | +| 409 `request_conflict` | Same `request_id`, different normalized answers than the first attempt with that id | +| 409 `already_submitted` | The form was already answered by a different request | +| 409 `version_conflict` | `expected_content_version` no longer matches the current revision | +| 413 | Request body over 64 KiB | +| 415 | `Content-Type` is not `application/json` | +| 422 | Field validation failed — `errors` keyed by field id, plus a `form_errors` list | +| 500 | Internal error; no mutation was applied | + +There is no `429` in V1 — submissions are not rate-limited server-side. + +## The `artifactState` proxy client + +```typescript +const client = (await $W.artifactState())('artifact-uuid') +// or, inside a web component: import { artifactState } from '@wippy-fe/proxy' + +const state = await client.get() +const result = await client.submit({ + form_version: 1, + request_id: crypto.randomUUID(), + expected_content_version: state.content_version, + answers: { color: 'blue' }, +}) +``` + +- The route is re-resolved fresh on every call — nothing is cached at + `artifactState(artifactId)` construction time, and no global config is + mutated. +- `artifactId` is validated up front: an empty or whitespace-only id throws + synchronously. +- Every failure — an HTTP status or a network error — rejects with a typed + `ArtifactStateError` (`status`, `code`, and, for a 422, `errors` keyed by + field id plus `formErrors`). It never fabricates a success or failure body. + +```typescript +try { + await client.submit(envelope) +} +catch (error) { + if (isArtifactStateError(error) && error.status === 422) { + // error.errors: Record<string, { code: string, message: string }[]> + } + throw error +} +``` + +Prefer `isArtifactStateError(error)` over `error instanceof +ArtifactStateError`: the class is built separately into every proxy entry +point and into the published `@wippy-fe/proxy` npm package, so an +`instanceof` check against a class imported from a *different* bundle's copy +can silently never match, even for an error that same client threw. +`isArtifactStateError` checks a realm-stable brand instead. (The class also +overrides `Symbol.hasInstance` to run the same check, so a plain +`instanceof` happens to work too — `isArtifactStateError` is just the +harder-to-get-wrong spelling.) + +### `artifactState` and the deprecated `instance.form` + +`instance.form.get()` / `.submit(data)` is a thin backward-compatibility +shim over `artifactState(appConfig.context.resourceId)`. A 422 maps to the +legacy `{ success: false, errors }` shape. Every other failure (401, 404, +409, 5xx, network) rethrows the same error `artifactState` would throw, +rather than returning a mock success or failure. New code should call +`instance.artifactState(artifactId)` directly rather than this deprecated +shim. + +## Styling API + +`<wippy-form>` follows the Session Forms styling contract: every visual +value is a `--wippy-form-*` custom property with a semantic theme-variable +fallback (never a raw hex as the primary fallback), every restylable piece +is exposed as a `::part()`, state is reflected as both a `<part>-<state>` +part and a `w-form__<part>--<state>` class, and state a stylesheet needs is +a host attribute (`density`, `card-state`, `collapsed`). The full token, +part, and host-attribute tables, plus a restyle example, live in the +package's own README (`frontend/wippy-form/README.md` in the `wippy/session` +source). `<wippy-form-answers>` has no visible surface and so exposes no +styling API at all — hiding the record is its entire purpose. + +## Accessibility + +Each question has an accessible group label: `role="radiogroup"` with +`aria-required` when required for a single-selection field, or `role="group"` +for a multiple-selection field. A single-selection group is one Tab stop, +with a roving `tabindex` that arrow keys move between its rows (the +WAI-ARIA radio group pattern). A multiple-selection group leaves every row +its own Tab stop instead, since each is an independent checkbox. +Field-level errors render as a `role="alert"` element, linked to its group +or text box through `aria-describedby`, so a screen reader announces the +error text as soon as it appears. A single polite live region announces +question and review navigation (for example "Question 2 of 4" or "Review +your answers"), tick/untick changes, and submission-result and +validation-summary text, without moving focus. + +The keyboard behavior described [above](#behavior) covers answering, +navigation, and notes without a pointer, including that Escape in a note or +the Other box only closes the editor. The typed draft stays saved with that +answer and is not discarded. After a full submission is accepted, focus +moves to the read-only summary's status text, so it is not lost when the +card swaps from the active view to the answered one. + +## Known gaps + +- **Unchecked-control contrast.** The tick boxes, radio marks, and input + edges use the theme's existing surface-300/700 border colors as-is + (roughly 1.3 to 1.4:1 contrast), with no local override. This needs a + theme-level fix, not one specific to this component. +- **The four action buttons are unstyled PrimeVue defaults.** The two "Send" + buttons and the two composer send buttons follow the theme's own primary + button color, not `--wippy-form-accent`. Retinting `--wippy-form-accent` + alone leaves these four on the old color while rows, the counter, key + badges, and the focus ring follow the new one. +- **Notes and Other text-box color are the theme's own `.p-textarea` + default.** No `--wippy-form-input-bg` / `--wippy-form-input-border` + tokens exist yet. +- **A few V1 defaults, revisited after V1:** the note answer shape + (`{value, note}` vs. a separate field), a newly opened card does not take + keyboard focus on its own, only backticks render as inline code (no other + Markdown-style formatting), and only the first nine rows of a question + get a number-key badge, with no cap on how many options a question can + have. + +## Diagnostics + +`<wippy-form>` reflects its own state as the `card-state` host attribute. +It exists for styling, but it is also the fastest way to read what the +component is doing from the DOM or an end-to-end test: + +| `card-state` | Meaning | +| --- | --- | +| `loading` | Before the artifact's first `GET` resolves; `<wippy-loading>` shows instead of the card. | +| `active` | Answerable: a question, the review step, or briefly, the submitting state. | +| `review` | The review step of a several-question form, before "Send answers". | +| `answered` | The read-only summary of an accepted submission. | +| `unsupported` | An unrecognized `form-version` (from the prop or the loaded state), or a Web Host without the `artifactState` export. Takes priority over every other value — never an interactive or submittable card. | + +A missing or failed component bundle — the `wippy-form` script never +registers, or registration times out — never reaches any `card-state` +above: the Host's own component loader shows "This part of the page could +not load. Reload to try again." in its place. The real cause goes only to +the browser console, as one of two load-failure log lines: a script error +("script failed to load") or a registration timeout ("failed to load in +time"), logged once per failed tag rather than once per card that tried to +mount it. The way to recover is to reload the page. The browser keeps a +failed script load for the life of the page, so the Host cannot fetch the +same bundle URL again, and a retry in the page does not help. Once the tag is +defined, every card still waiting on it updates without further action. + +A reload is also triggered by the proxy's `@reconnect` event — fired with no +payload after the Host's WebSocket reconnects following a drop — so a form +left stale through a brief backend restart or network blip corrects itself +once the socket comes back, without a manual page reload. + +## See Also + +- [Session Forms (framework)](../../framework/session-forms.md) — the + `ask_user` / `read_form` tools, the trait, and how an answer is admitted + into the conversation +- [Chat Web Components](./chat-web-components.md) — other host-provided, + auto-registered elements delivered the same way +- [Proxy API](./proxy-api.md) — the rest of `@wippy-fe/proxy` / + `getWippyApi()` +- [Web Component Recipe](./web-component.md) — building your own + `view.component`, for contrast with these host-provided ones From 1c0bd77c829a0de89d42b4fe1570364ae1f0cb2e Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 1 Oct 2026 14:28:07 +0200 Subject: [PATCH 09/16] docs(session-forms): state behavior instead of test history, require Web Host 1.0.61, plain-writing pass Remove test and observation narration from the rollback and old-Host sections, require Web Host 1.0.61 or later, correct the trait prompt summary and the late flag (always present in the record), drop the unrelated userspace/users sign-in note, and apply the plain-writing rules (no dashes, no decorative bold, shorter lists) to both pages. --- en/framework/session-forms.md | 344 +++++++-------- en/frontend/micro-frontends/session-forms.md | 433 ++++++++++--------- 2 files changed, 390 insertions(+), 387 deletions(-) diff --git a/en/framework/session-forms.md b/en/framework/session-forms.md index baaa1281..ff744bbf 100644 --- a/en/framework/session-forms.md +++ b/en/framework/session-forms.md @@ -7,16 +7,16 @@ description: "Ask the user structured choice questions from an agent with the as Session forms let an agent ask the user one or more choice questions and get a structured answer back, without leaving a tool call waiting on human input. -The `wippy/session` module owns the feature: a trait that adds the `ask_user` -and `read_form` tools, an artifact that renders as a question card in the -chat, and an HTTP endpoint that accepts the answer and delivers it to the -session as an ordinary user message. +The `wippy/session` module owns the feature. It provides a trait that adds the +`ask_user` and `read_form` tools, an artifact that renders as a question card +in the chat, and an HTTP endpoint that accepts the answer and delivers it to +the session as an ordinary user message. -V1 supports choice questions only: single selection, multiple selection, -optional required/optional, and an optional free-text "Other" answer. Plain -text, number, date, and other field types are a later release; a V1 renderer -detects an unsupported field type and shows a fallback rather than dropping -the question silently. +This release supports choice questions only. A choice question allows a single +or a multiple selection, can be required or optional, and can offer a +free-text "Other" answer. Other field types are planned for a later release. +A renderer that meets a field type it does not support shows a fallback form +and never drops the question silently. This page documents the trait, the tool contracts, and how an answer reaches the conversation. For the `wippy-form` / `wippy-form-answers` components and @@ -47,20 +47,28 @@ The trait requires a `wippy/session` version that ships session forms. With an older one, an agent definition that references the trait fails to resolve at lint time rather than silently doing nothing. -The trait contributes two tools and a block of prompt text that explains -them to the model (ask at most one form per turn, read `answered_message` -back through `read_form`, treat a late answer as context only, and never -write a `<wippy-form-answers>` element by hand). An agent without the trait -cannot call `ask_user`, but its prompt still includes the deterministic form -index described below, and it can read a submitted answer like any other -user message. +The trait contributes two tools and a block of prompt text. The prompt tells +the model the following. + +- Use `ask_user` only when it needs a decision between concrete options, and + ask at most one form per turn. +- Set `answered_message` to a short sentence in the user's voice. It becomes + the user's chat message when they answer. +- Treat an answer with `"late": true` as context only, and confirm with the + user before acting on the earlier request. +- Call `read_form` with a `form_id` to see an earlier form, and never write a + `<wippy-form-answers>` element by hand. + +An agent without the trait cannot call `ask_user`, but its prompt still +includes the deterministic form index described below, and it can read a +submitted answer like any other user message. ## The `ask_user` tool `ask_user` validates and normalizes the definition, then asks the session to -create the form. An invalid definition is a tool error (the call returns no -result and a message describing what to fix); nothing is stored in that -case, and the agent can retry in the same turn. +create the form. An invalid definition is a tool error. The call returns no +result and a message that describes what to fix, nothing is stored, and the +agent can retry in the same turn. | Key | Contract | | --- | --- | @@ -70,21 +78,21 @@ case, and the agent can retry in the same turn. | `answered_message` | Optional plain text, at most 200 characters. The user's chat message once they answer, written in the user's own voice by the agent that asks (see [What the agent receives](#what-the-agent-receives)). Never shown on the form. A form asked without it falls back to `Answered “<title>”.` | | `fields` | 1 to 20 entries | | `fields[].id` | Unique key matching `^[a-z][a-z0-9_]{0,39}$` | -| `fields[].type` | `"choice"` (the only V1 type) | +| `fields[].type` | `"choice"`, the only type in this release | | `fields[].label` | The question, 1 to 240 characters | | `fields[].description` | Optional help text, at most 1,000 characters | | `fields[].required` | Boolean, default `false` | -| `fields[].options` | 1 to 20 distinct choices. A plain string is both the value and the label; use `{ "value", "label", "description"? }` when the stored value should differ from the shown text | +| `fields[].options` | 1 to 20 distinct choices. A plain string is both the value and the label. Use `{ "value", "label", "description"? }` when the stored value should differ from the shown text | | `fields[].multiple` | Boolean, default `false`: allow selecting several options | | `fields[].allow_other` | Boolean, default `false`: offer a free-text "Other" answer | -The normalized definition is bounded to 32 KiB. That size is measured after +The normalized definition is bounded to 32 KiB. The size is measured after normalization, where a plain string option expands to `{"value": .., "label": -..}`, so a compact-looking definition with many short string options can be -well over the limit before it is written out this way; the tool error -reports the actual normalized size in that case. Labels and descriptions are -rendered as plain text, never parsed as Markdown or HTML, and control -characters other than tabs and newlines (in multi-line fields) are rejected. +..}`, so a definition with many short string options can be well over the +limit even when it looks compact. In that case the tool error reports the +actual normalized size. Labels and descriptions are rendered as plain text and +are never parsed as Markdown or HTML. Control characters other than tabs and +newlines (in multi-line fields) are rejected. A successful call ends the agent's turn. The tool result is a factual, past-tense sentence: @@ -94,9 +102,9 @@ Form "Delivery preference" was created as <artifact-id>. Its answer will arrive ``` The agent should not run a further model step to say "please fill in the -form" — the form is already visible. If it chooses to add a short -continuation anyway, that costs an extra model step and has no effect on -correctness: the form is already durably created either way. +form", because the form is already visible. A short continuation costs an +extra model step and does not affect correctness, because the form is already +stored. ### One form per turn @@ -109,18 +117,18 @@ This turn already asked the user with a form. No second form was created; wait f A session can hold up to 100 unresolved (unanswered) forms at once. Above that, `ask_user` is rejected with `too_many_forms` and the agent is asked to -resolve or supersede older forms; nothing is deleted automatically. +resolve or supersede older forms. Nothing is deleted automatically. -A form's definition is immutable once created. There is no edit operation — -attempting to update a form artifact through the general artifact-update path -is rejected (`session_form: Session forms cannot be edited. Ask a new form -instead.`). To change a question, ask a new form. +A form's definition is immutable once created. There is no edit operation, and +an attempt to update a form artifact through the general artifact-update path +is rejected with `session_form: Session forms cannot be edited. Ask a new form +instead.` To change a question, ask a new form. ## What the agent receives The user answers on a question card (see the frontend page for the UI). The accepted answer becomes one ordinary user message, built entirely on the -server — the browser never supplies its text. The message has exactly one +server, and the browser never supplies its text. The message has exactly one visible line, followed by an invisible carrier element that holds the full answer as JSON: @@ -131,17 +139,17 @@ Answered questions about the delivery of your order. </wippy-form-answers> ``` -The user sees only the first line: the `answered_message` the agent supplied -when it called `ask_user` (or the `Answered “<title>”.` fallback). The -`wippy-form-answers` component the Session ships renders nothing, so the -record never appears in the chat, but the raw message text — including the -record attribute — is what the agent reads on its next turn. The answered -form card shown above the message is the user-facing summary; this record is -the machine-readable one. +The user sees only the first line, which is the `answered_message` the agent +supplied when it called `ask_user` (or the `Answered “<title>”.` fallback). +The `wippy-form-answers` component that the Session ships renders nothing, so +the record never appears in the chat. The agent reads the raw message text, +including the record attribute, on its next turn. The answered form card shown +above the message is the summary for the user, and the record is the summary +for the agent. ### Record shape -The record is self-contained: an agent can act on it without the original +The record is self-contained, so an agent can act on it without the original `ask_user` call, which a checkpoint may have summarized away. For each question id, `answers[id]` has a `question` (the field's label) and an `answer`: @@ -154,27 +162,29 @@ question id, `answers[id]` has a `question` (the field's label) and an | `[ ...one of the above... ]` | A multiple-selection question, in definition order, with an "Other" entry (if any) last | | `null` | The question was left unanswered (only possible when not required) | -The record also carries `form_id`, `form_version`, and `title`. A late -answer (see below) additionally carries `"late": true` and a `late_notice`. -The stored submission keeps only the normalized answer values; the record -itself is derived from those values plus the immutable definition on every -read, so the record in the answer message and the one `read_form` returns -for the same form always agree. +The record also carries `form_id`, `form_version`, `title` and `late`. The +`late` value is `false` unless the answer was late (see below). A late answer +has `"late": true` and adds a `late_notice`. + +The stored submission keeps only the normalized answer values. The record is +derived from those values and the immutable definition on every read, so the +record in the answer message and the one `read_form` returns for the same form +always agree. ## Late answers and the fresh-confirmation rule A form's staleness and its late flag serve different purposes and are tracked separately. -While a form is unanswered, it is **stale** when a different real user input -(a typed message, or a submission to another form) was durably accepted -after the form was created. Staleness is evaluated live, every time the form -state is read; assistant text, system events, tool results, and validation -failures never make a form stale. +While a form is unanswered, it is stale when a different real user input (a +typed message, or a submission to another form) was durably accepted after the +form was created. Staleness is evaluated live, every time the form state is +read. Assistant text, system events, tool results, and validation failures +never make a form stale. Once a form is answered, the acceptance transaction evaluates staleness one final time against the same rule and freezes the result as the submission's -**late** flag. It does not change afterward, no matter what the conversation +late flag. The flag does not change afterward, no matter what the conversation does later. A late answer's record carries `"late": true` and: ```text @@ -182,26 +192,26 @@ late_notice: "The conversation moved on before this answer. Use it as context an ``` A form submission is never an authorization token for the action it was -originally asked about. The agent must still get explicit confirmation -before acting on a late answer, and any action tool that needs authorization -must enforce that itself — the forms feature only records what the user +originally asked about. The agent must still get explicit confirmation before +acting on a late answer, and any action tool that needs authorization must +enforce that itself, because the forms feature only records what the user chose. ## `read_form` and the form index `read_form` takes a `form_id` (from the form index or an answer message) and -returns the state of one form belonging to the calling session; a form from -another session is not visible. Its result depends on the form's state: +returns the state of one form belonging to the calling session. A form from +another session is not visible. The result depends on the form's state: | `status` | Meaning | | --- | --- | | `unanswered` | Returns the form's `title` and `questions` (each with its options), so an agent that lost the original `ask_user` result can restate them | -| `answer_pending` | The user answered, but the answer has not been admitted into this session's history yet (see below). No answer values are returned — the agent must wait for the answer to arrive as a user message | +| `answer_pending` | The user answered, but the answer has not been admitted into this session's history yet (see below). No answer values are returned, and the agent must wait for the answer to arrive as a user message | | `answered` | Returns the same self-contained record described above, plus `answered_at` | Every agent, with or without the trait, also gets a bounded, deterministic -index of the session's forms injected into its prompt (computed fresh on -every prompt build, not a copy that can drift): +index of the session's forms in its prompt. The index is computed fresh on +every prompt build, so it cannot drift from the stored forms: ```text Session forms (index; exact answers are in the answer messages and can be read with read_form when available): @@ -211,144 +221,134 @@ Session forms (index; exact answers are in the answer messages and can be read w (2 more unanswered and 1 more answered forms not listed) ``` -The index lists up to 8 unanswered/pending forms (newest first) and up to 4 -answered forms (most recently answered first), bounded to 8 KiB, and reports -how many were omitted past that. A summarizing checkpoint is free text and -may drop form ids or values; this index is rebuilt from the stored artifacts -on every prompt, so it does not depend on the checkpoint having preserved +The index lists up to 8 unanswered or pending forms (newest first) and up to 4 +answered forms (most recently answered first), bounded to 8 KiB, and it +reports how many were omitted. A summarizing checkpoint is free text and may +drop form ids or values. The index is rebuilt from the stored artifacts on +every prompt, so it does not depend on the checkpoint having preserved anything. ## How answers are admitted Submitting a form's answer (see the frontend page for the HTTP contract) -commits the answer and the user message in one transaction, then publishes -an artifact-update event and wakes the owning session process. The row -itself, not the wake-up, is what makes delivery durable — a missed wake-up -does not lose the answer. - -A form answer is never steered into a running turn. It stays pending until -the turn ends, no matter how the session is configured. Typed input, by -contrast, follows the session's own steering setting. It can be admitted -mid-turn when the agent has the `wippy.session.traits:steering` trait, or -the session sets a `steer` input-policy override. Once a turn ends, pending -answers and any steered input the session held are admitted together, in -the order they were durably accepted. - -Admission order follows the order answers were durably accepted, and depends -on what the session is doing: - -- **Idle session.** The answer is admitted immediately, and a new turn +commits the answer and the user message in one transaction, then publishes an +artifact-update event and wakes the owning session process. The stored row, +and not the wake-up, makes delivery durable, so a missed wake-up does not lose +the answer. + +A form answer is never steered into a running turn. It stays pending until the +turn ends, no matter how the session is configured. Typed input follows the +session's own steering setting instead. It can be admitted mid-turn when the +agent has the `wippy.session.traits:steering` trait, or when the session sets +a `steer` input-policy override. Once a turn ends, pending answers and any +steered input the session held are admitted together, in the order they were +durably accepted. + +Admission order follows the order in which answers were durably accepted, and +the rest depends on what the session is doing: + +- If the session is idle, the answer is admitted immediately and a new turn starts to answer it. -- **A turn is running.** The answer stays out of that turn's prompt — it is - marked pending and `read_form` reports `answer_pending` for it — and is +- If a turn is running, the answer stays out of that turn's prompt. It is + marked pending, and `read_form` reports `answer_pending` for it. It is admitted once the turn ends, in acceptance order together with any typed - input the session held during the turn. The next turn answers the latest + input the session held during the turn, and the next turn answers the latest admitted message. -- **The user pressed Stop.** The answer is still admitted (it becomes - ordinary visible history), but no new turn starts for it. The form reads - as delivered; the user continues normally by sending a message. The same - holds when the session plugin has to enforce the Stop itself: if a turn - does not stop within 10 seconds, the plugin cancels, and then terminates, - the session process. Its pending answers are admitted with no turn exactly - as an honored Stop's would be — they do not wait for the next session - start to run an unattended turn. -- **The session is finishing, or the process is not running (idle timeout, - crash, restart).** The answer stays pending. The next time the session - process starts, it scans for pending answers before anything else and - queues their admission — recovery needs no external retry. +- If the user pressed Stop, the answer is still admitted and becomes ordinary + visible history, but no new turn starts for it. The form reads as delivered, + and the user continues by sending a message. The same holds when the session + plugin has to enforce the Stop itself. If a turn does not stop within 10 + seconds, the plugin cancels and then terminates the session process, and the + pending answers are admitted with no turn exactly as an honored Stop's would + be. They do not wait for the next session start to run an unattended turn. +- If the session is finishing, or the process is not running (idle timeout, + crash, restart), the answer stays pending. The next time the session process + starts, it scans for pending answers before anything else and queues their + admission, so recovery needs no external retry. The user's session plugin also drives this recovery from outside any one session. It starts a stopped session that still holds an unadmitted answer, once right after the plugin itself starts and again on every periodic scan -after that, so an answer is still delivered even if its original wake-up was -lost — that start admits the answer and runs a turn for it, like any other -session start with a pending answer. +after that. An answer is therefore still delivered when its original wake-up +was lost, and the start admits the answer and runs a turn for it, like any +other session start with a pending answer. The same plugin start also settles any of the user's sessions left stored as "running" with no live process, for example after a runtime restart, back to -idle. This settling only changes how an **already-admitted** answer reads: -one the turn had already picked up before the process disappeared now reads -as interrupted ("send a message to continue"), instead of perpetually -running. A **pending** answer is not affected by this settling at all — it -is unrelated to the session's stored status, and simply gets admitted with a -turn the next time the session starts, as described above. +idle. The settling changes only how an already-admitted answer reads. An +answer that the turn had picked up before the process disappeared now reads as +interrupted ("send a message to continue") and no longer reads as running. A +pending answer is not affected by the settling, because it is unrelated to the +session's stored status. It is admitted with a turn the next time the session +starts, as described above. Once admitted, the answer's message row is re-dated to the moment of -admission rather than the moment it was accepted, so its place in the -visible history follows admission order. The `submitted_at` the -artifact-state API returns (see the frontend page) is unaffected and keeps -the original acceptance time. +admission rather than the moment it was accepted, so its place in the visible +history follows admission order. The `submitted_at` that the artifact-state API +returns (see the frontend page) is unaffected and keeps the original +acceptance time. The agent must never treat an `answer_pending` form as answered, and must never guess its content before the real answer message arrives. ## Security notes -The answer message's text — the sentence and the record — is built entirely -by the server from the immutable definition and the validated, normalized -answers. The browser sends only structured `answers` keyed by field id; it -never sends message text. User-supplied text (an "Other" answer or a note) -is JSON-escaped data inside the record's `answer` object, never raw markup: -the server escapes `'`, `<`, `>`, and `&` inside the record so user text -cannot end the attribute, close the tag, or add markup. +The text of the answer message, which is the sentence and the record, is built +entirely by the server from the immutable definition and the validated, +normalized answers. The browser sends only structured `answers` keyed by field +id and never sends message text. User-supplied text (an "Other" answer or a +note) is JSON-escaped data inside the record's `answer` object and is never raw +markup. The server escapes `'`, `<`, `>`, and `&` inside the record, so user +text cannot end the attribute, close the tag, or add markup. -The trait's prompt explicitly tells the agent never to write a -`<wippy-form-answers>` element itself — the tag carries meaning only in the -exact wire format the server writes, and an agent-authored one would not -match a real accepted answer. +The trait's prompt tells the agent never to write a `<wippy-form-answers>` +element itself. The tag carries meaning only in the exact wire format the +server writes, and an agent-authored one would not match a real accepted +answer. Every state read or write checks authentication, then that the artifact belongs to the caller and its session, then read (GET) or write (POST) permission on that session, before doing anything with the form. A missing -artifact, another user's artifact, or an artifact whose session is gone or -not the caller's all return the same 404 — the endpoint does not reveal that +artifact, another user's artifact, and an artifact whose session is gone or +not the caller's all return the same 404, so the endpoint does not reveal that a foreign form exists. ## Disabling and rolling back -Disabling new form creation is a config-only change: remove +Disabling new form creation is a config-only change. Remove `wippy.session.forms:ask_user` from an agent's `traits:` list. There is no -deploy step, no feature flag, and no separate kill switch for V1. +deploy step, no feature flag, and no separate kill switch. -- **Open (unanswered) forms stay answerable.** The state API's read/write - checks are session-ownership checks, not trait checks, so a form asked +- Open (unanswered) forms stay answerable. The state API's read and write + checks are session-ownership checks and not trait checks, so a form asked before the trait was removed can still be submitted afterward. -- **Answered forms stay readable**, with or without the trait on any agent: - an answered form is an ordinary artifact plus an ordinary user chat - message, and `read_form` and the prompt's form index work the same for - every agent. -- **Do not downgrade the `wippy/session` module below the release that - shipped Session Forms while any form artifacts exist.** Rendering - `wippy-form` / `wippy-form-answers` needs their `view.component` registry - entries to still be registered and served by the running module version. - A consumer that also registers its own forms-related entries can fail to - boot entirely on an older module — confirmed in testing: pointing a demo - consumer at the last pre-forms Session release left one of its own - registry entries unresolved, and the whole runtime refused to start - (`failed to load state: unresolved dependencies after retry: …`). Whether - an agent's `wippy.session.forms:ask_user` trait reference alone (with no - consumer-side forms entries) would also block a boot on an older module - was not tested — treat it as an open risk, not a cleared case. Removing - the trait is the supported way to stop new forms; downgrading the module - itself is a separate, riskier action with this failure mode. +- Answered forms stay readable, with or without the trait on any agent. An + answered form is an ordinary artifact plus an ordinary user chat message, + and `read_form` and the prompt's form index work the same for every agent. +- Do not downgrade the `wippy/session` module below the release that shipped + Session Forms while any form artifacts exist. Rendering `wippy-form` and + `wippy-form-answers` needs their `view.component` registry entries to be + registered and served by the running module version. A consumer that + registers its own forms-related entries can fail to boot on an older module, + because one of those entries stays unresolved and the runtime refuses to + start with `failed to load state: unresolved dependencies after retry: …`. + The boot behavior of an older module is not defined for a consumer whose + only reference is an agent's `wippy.session.forms:ask_user` trait, so treat + that case as a risk too. Removing the trait is the supported way to stop new + forms. Downgrading the module is a separate action with this failure mode. ## Compatibility -- **Web Host.** The question card submits through the `artifactState` client, - which only a Web Host release that includes Session Forms provides (see +- The question card submits through the `artifactState` client, which only + Web Host 1.0.61 or later provides (see [Host requirement](../frontend/micro-frontends/session-forms.md#host-requirement)). On an older Host the card shows the questions with disabled options and a notice that the form needs a newer Web Host, and nothing can be submitted. The user's answer message and the agent's reply stay readable in the chat. -- **Unknown form version.** A form whose `form_version` is not `1` shows a - notice and never a submit control. -- **Missing component bundle.** The Host shows its load-failure fallback in - place of the card. Reloading the page is the way to recover. -- **Consumer applications on runtime v0.3.43a.** Sign-in needs - `userspace/users` 0.1.9 or later. A consumer whose lock pins 0.1.8 answers - the sign-in request with a 500 error from `user_groups_repo`, because 0.1.9 - adds the login security policies that 0.1.8 lacks. This was observed with - a consumer that has no Session Forms and does not depend on this feature. +- A form whose `form_version` is not `1` shows a notice and never a submit + control. +- When the component bundle is missing, the Host shows its load-failure + fallback in place of the card, and reloading the page recovers it. ## Limits at a glance @@ -369,21 +369,23 @@ deploy step, no feature flag, and no separate kill switch for V1. | Unresolved forms per session | 100 | | Form index (prompt injection) | 8 unanswered/pending + 4 answered, 8 KiB total | -There is no rate limit on form submission in V1. +Form submission has no rate limit. ## Verifying Create or use an agent with the `wippy.session.forms:ask_user` trait, start a -session, and prompt it to ask a question that needs a decision. Confirm: the -question card appears in the chat, answering it produces a chat message with -exactly one visible sentence, and the agent's next turn correctly references -the answer (for example, by asking `read_form` or by acting on the choice). +session, and prompt it to ask a question that needs a decision. The question +card should appear in the chat. Answering it should produce a chat message +with exactly one visible sentence, and the agent's next turn should reference +the answer correctly, for example by calling `read_form` or by acting on the +choice. + To check late-answer handling, send a plain chat message after the form is -created but before answering it, then answer — the record should carry -`"late": true` and the agent should ask for confirmation before acting on -the original request. +created and before answering it, and then answer. The record should carry +`"late": true`, and the agent should ask for confirmation before acting on the +original request. -## See Also +## See also -- [Session Forms (frontend)](../frontend/micro-frontends/session-forms.md) — the `wippy-form` / `wippy-form-answers` components, the artifact-state HTTP API, and the `artifactState` proxy client -- [Agents](agents.md) — traits, tools, and agent definitions in general +- [Session Forms (frontend)](../frontend/micro-frontends/session-forms.md): the `wippy-form` and `wippy-form-answers` components, the artifact-state HTTP API, and the `artifactState` proxy client +- [Agents](agents.md): traits, tools, and agent definitions in general diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index 3fe2088e..81288ca4 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -8,64 +8,71 @@ description: "The wippy-form question card and the wippy-form-answers carrier el `wippy/session` ships two `view.component` web components that render a Session `ask_user` form (see [Session Forms (framework)](../../framework/session-forms.md) for the -`ask_user` tool and the answer contract): `<wippy-form>`, the interactive -question card, and `<wippy-form-answers>`, an invisible carrier that keeps a +`ask_user` tool and the answer contract). `<wippy-form>` is the interactive +question card. `<wippy-form-answers>` is an invisible carrier that keeps a form's answer record reachable to the agent without showing it to the user twice. Like the chat elements in -[Chat Web Components](./chat-web-components.md), these are **host-provided -elements to consume** — the Session module registers and serves them; an -application embedding a chat surface does not author or bundle either one. +[Chat Web Components](./chat-web-components.md), both are host-provided +elements to consume. The Session module registers and serves them, and an +application that embeds a chat surface does not author or bundle either one. ## `<wippy-form>`: the question card -For a V1 definition, every field is `type: "choice"`, and the component -renders a Claude-style question card rather than a plain fields form: one -question at a time for a several-question form, with a `‹ n/total ›` counter, +For a version 1 definition, every field has `type: "choice"`, and the +component renders a question card instead of a plain fields form. A form with +several questions shows one question at a time with a `‹ n/total ›` counter, per-answer notes, an "Other" free-text row, a review step before sending, and a read-only answered summary afterward. A mixed or non-`choice` definition -(reserved for a later release) falls back to a plain radio/checkbox fields +(reserved for a later release) falls back to a plain radio and checkbox fields form. | Prop (HTML attribute) | Type | Default | Description | | --- | --- | --- | --- | -| `form-version` | `number` | `1` | Definition schema version. A value other than `1` — from this prop or from the loaded state's own `form_version` — disables the interactive form and shows a compatibility notice instead of ever rendering a `Submit`. | +| `form-version` | `number` | `1` | Definition schema version. A value other than `1`, whether it comes from this prop or from the loaded state's own `form_version`, disables the interactive form and shows a compatibility notice instead of ever rendering a `Submit`. | | `definition` | `object` | `null` | The immutable form definition: `title`, optional `description`, optional `submit_label`, optional `answered_message` (never displayed), and `fields`. | | `state` | `string` | `"active"` | Package-tag lifecycle: `"active"` (answerable) or `"idle"` (already answered, read-only). Changing it reloads canonical state from the Host. | | `density` | `string` | `"compact"` | `"compact"` or `"comfortable"` sizing. Read purely through a `:host([density="comfortable"])` CSS selector. | -The component owns its own data loading (`GET` on mount, reload on -visibility change, a session-message event, an artifact-update event, the -Host's `@reconnect` event after a WebSocket reconnect, or the browser's -`online` event), submission (client-generated `request_id` reuse, one -automatic retry on a no-response network failure, and handling for a 422 -field-error response and a 409 already-submitted response), and offline -detection. A host only needs to mount the tag with these attributes. +The component owns its own data loading, submission, and offline detection. A +host only needs to mount the tag with these attributes. + +- It loads the state with a `GET` on mount, and reloads it on a visibility + change, a session-message event, an artifact-update event, the Host's + `@reconnect` event after a WebSocket reconnect, or the browser's `online` + event. +- It submits with a client-generated `request_id` that it reuses on a retry, + retries once automatically after a network failure with no response, and + handles a 422 field-error response and a 409 already-submitted response. ### Behavior -- **One question at a time.** Answering (a click, or a number key for the - first nine rows) moves to the next unseen question; Previous/Next - navigate back to change an earlier answer. -- **Notes.** Every answer row has a note toggle. A note is the user's own - text about that one chosen option; it changes the answer's shape to - `{ "value": "…", "note": "…" }` rather than adding a separate field. -- **Other.** A joined free-text input with its own send button, offered only - when the field's `allow_other` is set. -- **Review step.** A several-question form ends on a review listing every - answer, with a single "Send answers" action — there is no per-question - submit once you reach it. -- **Answered summary.** Once submitted, the card shows a read-only summary - of exactly what was accepted, including any notes and the submission time. -- **No close or decline button**, and the card never takes focus on its own. - -Keyboard: number keys 1 to 9 answer or tick the corresponding row (the first -nine rows only — a question can have more options than that, they just don't -get a number); Shift+1–9 (or `N` on a focused row) opens that row's note; -Enter sends from Other or a note (or saves a note and ticks its row on a -several-answer question); Shift+Enter adds a line; Escape leaves a note or -Other box; arrow keys move between rows and between questions. All of it is -scoped to focus inside the card, so it never intercepts typing in the -surrounding chat composer. +- The card shows one question at a time. Answering (a click, or a number key + for the first nine rows) moves to the next unseen question, and Previous and + Next navigate back to change an earlier answer. A form with several + questions ends on a review that lists every answer, with a single "Send + answers" action. There is no per-question submit once the review is reached. +- Every answer row has a note toggle, and the field's `allow_other` setting + controls the "Other" row. + - A note is the user's own text about that one chosen option. It changes the + answer's shape to `{ "value": "…", "note": "…" }` and does not add a + separate field. + - "Other" is a joined free-text input with its own send button, offered only + when the field's `allow_other` is set. +- Once submitted, the card shows a read-only summary of exactly what was + accepted, including any notes and the submission time. The card has no close + or decline button, and it never takes focus on its own. + +The keyboard shortcuts are scoped to focus inside the card, so they never +intercept typing in the surrounding chat composer. + +| Key | Action | +| --- | --- | +| 1 to 9 | Answers or ticks the corresponding row. Only the first nine rows get a number, and a question can have more options than that | +| Shift+1 to 9, or N on a focused row | Opens that row's note | +| Enter | Sends from Other or a note, or saves a note and ticks its row on a several-answer question | +| Shift+Enter | Adds a line | +| Escape | Leaves a note or Other box | +| Arrow keys | Move between rows and between questions | ### Events @@ -88,90 +95,83 @@ Answered questions about the delivery of your order. </wippy-form-answers> ``` -It renders nothing — no shadow-root content, no `<slot>`, and `:host { -display: none; }` as defense in depth. Its only prop is `record` (the -single-line JSON string); its only public member is a read-only +It renders nothing. It has no shadow-root content and no `<slot>`, and it sets +`:host { display: none; }` as defense in depth. Its only prop is `record` (the +single-line JSON string), and its only public member is a read-only `answerRecord` getter that parses that attribute and returns the parsed -object, or `null` on missing/invalid JSON. It dispatches no events and makes -no host API calls of its own beyond the theme subscription every Wippy +object, or `null` on missing or invalid JSON. It dispatches no events and +makes no host API calls of its own beyond the theme subscription every Wippy element gets. -**Why the record lives in an attribute, not text content.** Two failure -modes both leave the tag on the page with no children: the chat sanitizer -strips an unrecognized tag (for example, right after a fresh deploy, before -the Host has re-fetched the updated components list), and an unloaded or -failed component script leaves the browser treating the tag as an anonymous -`HTMLElement`, which still renders its children by default. An element with -no children renders nothing either way; one with visible text content would -have shown the raw JSON to the user for that entire window. Putting the -record in an attribute means every failure mode still shows nothing. +Agents must never emit this tag themselves. It is written exclusively by the +Session server's message-composition code as part of the fixed answer format, +and it carries no meaning outside that exact wire format. -**Agents must never emit this tag themselves.** It is written exclusively by -the Session server's message-composition code as part of the fixed answer -format; it carries no meaning outside that exact wire format. +### Why the record lives in an attribute + +Two failure modes both leave the tag on the page with no children. In the +first, the chat sanitizer strips an unrecognized tag, for example right after +a fresh deploy and before the Host has re-fetched the updated components list. +In the second, an unloaded or failed component script leaves the browser +treating the tag as an anonymous `HTMLElement`, which still renders its +children by default. An element with no children renders nothing either way, +and an element with visible text content would have shown the raw JSON to the +user for that entire window. Because the record is in an attribute, every +failure mode still shows nothing. ## How the components load -Both are `view.component` registry entries with `auto_register: true`, -served by the Session module at `/wippy-session-forms` (`wippy-form`) and +Both are `view.component` registry entries with `auto_register: true`, served +by the Session module at `/wippy-session-forms` (`wippy-form`) and `/wippy-session-form-answers` (`wippy-form-answers`). The Web Host auto-loads -every `auto_register: true` component at boot and allows its tag — plus its -declared prop attribute names, `definition`/`form-version`/`state`/`density` -for `wippy-form` and `record` for `wippy-form-answers` — through the chat -message sanitizer. `record` is declared as a `wippy.props` entry -specifically so the sanitizer's allowed-attribute list includes it; without -that declaration the attribute would still be stripped even with the tag -itself allowed through. +every `auto_register: true` component at boot and allows its tag, plus its +declared prop attribute names, through the chat message sanitizer. The names +are `definition`, `form-version`, `state` and `density` for `wippy-form`, and +`record` for `wippy-form-answers`. `record` is declared as a `wippy.props` +entry so that the sanitizer's allowed-attribute list includes it. Without that +declaration the attribute is stripped even when the tag itself is allowed +through. ## Host requirement -`<wippy-form>` submits through `artifactState`, a typed client the Web Host -exports from every proxy realm (`$W.artifactState()` in an iframe, or the +`<wippy-form>` submits through `artifactState`, a typed client that the Web +Host exports from every proxy realm (`$W.artifactState()` in an iframe, or the named `artifactState` export from `@wippy-fe/proxy` in a host-mounted web -component). No Web Host release up to and including 1.0.60 exports it. The -Host requirement for Session Forms is **the first Web Host release after -1.0.60 that includes Session Forms** — a specific version number has not -been assigned yet. The matching npm `@wippy-fe/proxy` peer version on the -`wippy-form` / `wippy-form-answers` packages tracks that same release once -it exists. - -None of the paths below fabricate a success or a mock answer — see -[`instance.form` (deprecated)](#artifactstate-and-the-deprecated-instanceform) -below for the related history on the older adapter this replaced. +component). Web Host 1.0.61 or later exports it, and no earlier release does. +The matching npm release is `@wippy-fe/*` 0.0.61. -The component checks the conditions in the order of this table, and the first -one that applies decides what the card shows. +The component never fabricates a success or a mock answer. It checks the +conditions in the order of the following table, and the first one that +applies decides what the card shows. | Condition | What the card shows | | --- | --- | | `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." The card reflects `card-state="unsupported"`. | -| The Host has no `artifactState` export (every Web Host release before Session Forms) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. | +| The Host has no `artifactState` export (every Web Host release before 1.0.61) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. | | The Host exports `artifactState`, but no artifact id is available in the element's context | The questions rendered read-only, with "This form cannot be submitted here." | -### Behavior on a Web Host that predates Session Forms - -A Web Host from before Session Forms has neither the `artifactState` export -nor the `data-wippy-artifact-id` attribute, so the component checks for the -export first. The card shows the real questions with disabled options, and -nothing on it can be submitted. Every option is unselected, because the saved -answer cannot be read without the artifact-state API, so the card cannot show -what was chosen. The notice therefore points to the chat, where the user's -one-line answer message and the agent's reply stay readable. The hidden -answer record never appears, and nothing is mocked. - -On the published Web Host 1.0.59 with the current Session, a newly asked form -shows the questions with disabled radio buttons, no buttons in the card, -`card-state="unsupported"`, and the "needs a newer Web Host" notice with no -placeholder rows, and the notice reads "This form needs a newer Web Host. If -you already answered it, your answer is in the chat." In a chat of answered -forms, each card reads "This form was answered. Your answer is in the chat.", -and the answer messages and agent replies stay readable. +### Behavior on a Web Host before 1.0.61 + +A Web Host from before 1.0.61 has neither the `artifactState` export nor the +`data-wippy-artifact-id` attribute, so the component checks for the export +first. A newly asked form shows the real questions with disabled radio +buttons, no buttons in the card, and no placeholder rows. Every option is +unselected, because the saved answer cannot be read without the artifact-state +API, so the card cannot show what was chosen. The notice therefore points to +the chat, where the user's one-line answer message and the agent's reply stay +readable. The hidden answer record never appears, and nothing is mocked. In a +chat of answered forms, each card reads "This form was answered. Your answer is +in the chat." + +The older `instance.form` adapter that `artifactState` replaces is described +under [`artifactState` and the deprecated +`instance.form`](#artifactstate-and-the-deprecated-instanceform). ## The artifact-state HTTP API -`GET` / `POST /api/v1/artifact/{id}/state` reads a form's canonical state and -accepts its answer. The concrete path comes from the route table -(`artifacts.state`) and is overridable per deployment through +`GET` and `POST /api/v1/artifact/{id}/state` read a form's canonical state and +accept its answer. The concrete path comes from the route table +(`artifacts.state`) and can be overridden per deployment through `feature.apiRoutes`, like any other Wippy Web Host route. ### `GET /api/v1/artifact/{id}/state` @@ -193,13 +193,13 @@ accepts its answer. The concrete path comes from the route table } ``` -`status` is `"active"` (unanswered) or `"idle"` (answered). `stale` is -computed live and only meaningful while `status` is `"active"` — it is -`true` once a different real user input was durably accepted after the form -was created. `data` holds the exact accepted answers once answered, and -`delivery` reports `"pending"`, `"running"`, `"complete"`, or -`"interrupted"` for an answered form (never for an unanswered one), derived -from the message history rather than a stored flag. Responses always carry +`status` is `"active"` (unanswered) or `"idle"` (answered). `stale` is computed +live and is meaningful only while `status` is `"active"`. It is `true` once a +different real user input was durably accepted after the form was created. +`data` holds the exact accepted answers once answered. `delivery` reports +`"pending"`, `"running"`, `"complete"`, or `"interrupted"` for an answered +form, and it is `null` for an unanswered one. It is derived from the message +history and not from a stored flag. Responses always carry `Cache-Control: no-store`. ### `POST /api/v1/artifact/{id}/state` @@ -214,11 +214,11 @@ from the message history rather than a stored flag. Responses always carry ``` `request_id` should be generated once, at the moment the user attempts -submission, and reused unchanged on any retry of that same attempt — the -server recognizes a same-id, same-answers retry as a replay (`replayed: -true` in the response) rather than a conflict. `expected_content_version` is -optional; when present, it is checked against the artifact's current -revision so a stale client cannot silently overwrite a form's state. +submission, and reused unchanged on any retry of that same attempt. The server +recognizes a same-id, same-answers retry as a replay (`replayed: true` in the +response) and not as a conflict. `expected_content_version` is optional. When +it is present, it is checked against the artifact's current revision, so a +stale client cannot silently overwrite a form's state. Success: @@ -236,9 +236,9 @@ Success: } ``` -A `200` here means the answer and its user message are durably accepted — -not that the agent has replied yet. Show something like "Submitted. Waiting -for the assistant." +A `200` here means the answer and its user message are durably accepted. It +does not mean the agent has replied yet, so show something like "Submitted. +Waiting for the assistant." | Status | Meaning | | --- | --- | @@ -252,10 +252,10 @@ for the assistant." | 409 `version_conflict` | `expected_content_version` no longer matches the current revision | | 413 | Request body over 64 KiB | | 415 | `Content-Type` is not `application/json` | -| 422 | Field validation failed — `errors` keyed by field id, plus a `form_errors` list | +| 422 | Field validation failed, with `errors` keyed by field id and a `form_errors` list | | 500 | Internal error; no mutation was applied | -There is no `429` in V1 — submissions are not rate-limited server-side. +Submissions are not rate-limited server-side, so the API never returns `429`. ## The `artifactState` proxy client @@ -272,14 +272,14 @@ const result = await client.submit({ }) ``` -- The route is re-resolved fresh on every call — nothing is cached at - `artifactState(artifactId)` construction time, and no global config is - mutated. -- `artifactId` is validated up front: an empty or whitespace-only id throws - synchronously. -- Every failure — an HTTP status or a network error — rejects with a typed - `ArtifactStateError` (`status`, `code`, and, for a 422, `errors` keyed by - field id plus `formErrors`). It never fabricates a success or failure body. +- The route is re-resolved on every call. Nothing is cached when + `artifactState(artifactId)` is constructed, and no global config is mutated. +- `artifactId` is validated up front, and an empty or whitespace-only id + throws synchronously. +- Every failure, whether an HTTP status or a network error, rejects with a + typed `ArtifactStateError` (`status`, `code`, and, for a 422, `errors` keyed + by field id plus `formErrors`). The client never fabricates a success or + failure body. ```typescript try { @@ -294,85 +294,86 @@ catch (error) { ``` Prefer `isArtifactStateError(error)` over `error instanceof -ArtifactStateError`: the class is built separately into every proxy entry -point and into the published `@wippy-fe/proxy` npm package, so an -`instanceof` check against a class imported from a *different* bundle's copy -can silently never match, even for an error that same client threw. -`isArtifactStateError` checks a realm-stable brand instead. (The class also -overrides `Symbol.hasInstance` to run the same check, so a plain -`instanceof` happens to work too — `isArtifactStateError` is just the -harder-to-get-wrong spelling.) +ArtifactStateError`. The class is built separately into every proxy entry +point and into the published `@wippy-fe/proxy` npm package, so an `instanceof` +check against a class imported from a different bundle's copy can silently +never match, even for an error that the same client threw. +`isArtifactStateError` checks a brand that is stable across realms. The class +also overrides `Symbol.hasInstance` to run the same check, so a plain +`instanceof` works too, but `isArtifactStateError` is the safer spelling. ### `artifactState` and the deprecated `instance.form` -`instance.form.get()` / `.submit(data)` is a thin backward-compatibility +`instance.form.get()` and `.submit(data)` are a thin backward-compatibility shim over `artifactState(appConfig.context.resourceId)`. A 422 maps to the -legacy `{ success: false, errors }` shape. Every other failure (401, 404, -409, 5xx, network) rethrows the same error `artifactState` would throw, -rather than returning a mock success or failure. New code should call -`instance.artifactState(artifactId)` directly rather than this deprecated -shim. +legacy `{ success: false, errors }` shape. Every other failure (401, 404, 409, +5xx, network) rethrows the same error that `artifactState` would throw, and +the shim never returns a mock success or failure. New code should call +`instance.artifactState(artifactId)` directly and not this deprecated shim. ## Styling API -`<wippy-form>` follows the Session Forms styling contract: every visual -value is a `--wippy-form-*` custom property with a semantic theme-variable -fallback (never a raw hex as the primary fallback), every restylable piece -is exposed as a `::part()`, state is reflected as both a `<part>-<state>` -part and a `w-form__<part>--<state>` class, and state a stylesheet needs is -a host attribute (`density`, `card-state`, `collapsed`). The full token, -part, and host-attribute tables, plus a restyle example, live in the -package's own README (`frontend/wippy-form/README.md` in the `wippy/session` -source). `<wippy-form-answers>` has no visible surface and so exposes no -styling API at all — hiding the record is its entire purpose. +`<wippy-form>` follows the Session Forms styling contract. + +- Every visual value is a `--wippy-form-*` custom property with a semantic + theme-variable fallback, and never a raw hex as the primary fallback. +- Every restylable piece is exposed as a `::part()`. State is reflected as + both a `<part>-<state>` part and a `w-form__<part>--<state>` class. +- State that a stylesheet needs is a host attribute (`density`, `card-state`, + `collapsed`). + +The full token, part, and host-attribute tables, plus a restyle example, are +in the package's own README (`frontend/wippy-form/README.md` in the +`wippy/session` source). `<wippy-form-answers>` has no visible surface and +exposes no styling API, because hiding the record is its entire purpose. ## Accessibility -Each question has an accessible group label: `role="radiogroup"` with -`aria-required` when required for a single-selection field, or `role="group"` -for a multiple-selection field. A single-selection group is one Tab stop, -with a roving `tabindex` that arrow keys move between its rows (the -WAI-ARIA radio group pattern). A multiple-selection group leaves every row -its own Tab stop instead, since each is an independent checkbox. -Field-level errors render as a `role="alert"` element, linked to its group -or text box through `aria-describedby`, so a screen reader announces the -error text as soon as it appears. A single polite live region announces -question and review navigation (for example "Question 2 of 4" or "Review -your answers"), tick/untick changes, and submission-result and -validation-summary text, without moving focus. - -The keyboard behavior described [above](#behavior) covers answering, -navigation, and notes without a pointer, including that Escape in a note or -the Other box only closes the editor. The typed draft stays saved with that -answer and is not discarded. After a full submission is accepted, focus -moves to the read-only summary's status text, so it is not lost when the -card swaps from the active view to the answered one. +Each question has an accessible group label. A single-selection field is a +`role="radiogroup"` with `aria-required` when required, and a +multiple-selection field is a `role="group"`. A single-selection group is one +Tab stop, with a roving `tabindex` that arrow keys move between its rows (the +WAI-ARIA radio group pattern). A multiple-selection group leaves every row its +own Tab stop, because each row is an independent checkbox. + +A field-level error renders as a `role="alert"` element, linked to its group +or text box through `aria-describedby`, so a screen reader announces the error +text as soon as it appears. A single polite live region announces question and +review navigation (for example "Question 2 of 4" or "Review your answers"), +tick and untick changes, and submission-result and validation-summary text, +without moving focus. + +The [keyboard behavior](#behavior) covers answering, navigation, and notes +without a pointer. Escape in a note or the Other box only closes the editor, +and the typed draft stays saved with that answer. After a full submission is +accepted, focus moves to the read-only summary's status text, so it is not +lost when the card swaps from the active view to the answered one. ## Known gaps -- **Unchecked-control contrast.** The tick boxes, radio marks, and input - edges use the theme's existing surface-300/700 border colors as-is - (roughly 1.3 to 1.4:1 contrast), with no local override. This needs a - theme-level fix, not one specific to this component. -- **The four action buttons are unstyled PrimeVue defaults.** The two "Send" - buttons and the two composer send buttons follow the theme's own primary - button color, not `--wippy-form-accent`. Retinting `--wippy-form-accent` - alone leaves these four on the old color while rows, the counter, key - badges, and the focus ring follow the new one. -- **Notes and Other text-box color are the theme's own `.p-textarea` - default.** No `--wippy-form-input-bg` / `--wippy-form-input-border` - tokens exist yet. -- **A few V1 defaults, revisited after V1:** the note answer shape - (`{value, note}` vs. a separate field), a newly opened card does not take - keyboard focus on its own, only backticks render as inline code (no other - Markdown-style formatting), and only the first nine rows of a question - get a number-key badge, with no cap on how many options a question can - have. +- The tick boxes, radio marks, and input edges use the theme's existing + surface-300/700 border colors, which give roughly 1.3 to 1.4:1 contrast, + with no local override. The fix belongs in the theme and not in this + component. +- The two "Send" buttons and the two composer send buttons are unstyled + PrimeVue defaults. They follow the theme's own primary button color and not + `--wippy-form-accent`, so retinting `--wippy-form-accent` alone leaves them + on the old color while rows, the counter, key badges, and the focus ring + follow the new one. +- The Notes and Other text boxes use the theme's own `.p-textarea` colors. + No `--wippy-form-input-bg` or `--wippy-form-input-border` tokens exist yet. +- The following defaults may change in a later release: + - The answer shape of a note (`{value, note}` or a separate field). + - A newly opened card does not take keyboard focus on its own. + - Only backticks render as inline code, with no other Markdown-style + formatting. + - Only the first nine rows of a question get a number-key badge, and there + is no cap on how many options a question can have. ## Diagnostics -`<wippy-form>` reflects its own state as the `card-state` host attribute. -It exists for styling, but it is also the fastest way to read what the +`<wippy-form>` reflects its own state as the `card-state` host attribute. The +attribute exists for styling, and it is also the fastest way to read what the component is doing from the DOM or an end-to-end test: | `card-state` | Meaning | @@ -381,33 +382,33 @@ component is doing from the DOM or an end-to-end test: | `active` | Answerable: a question, the review step, or briefly, the submitting state. | | `review` | The review step of a several-question form, before "Send answers". | | `answered` | The read-only summary of an accepted submission. | -| `unsupported` | An unrecognized `form-version` (from the prop or the loaded state), or a Web Host without the `artifactState` export. Takes priority over every other value — never an interactive or submittable card. | - -A missing or failed component bundle — the `wippy-form` script never -registers, or registration times out — never reaches any `card-state` -above: the Host's own component loader shows "This part of the page could -not load. Reload to try again." in its place. The real cause goes only to -the browser console, as one of two load-failure log lines: a script error -("script failed to load") or a registration timeout ("failed to load in -time"), logged once per failed tag rather than once per card that tried to -mount it. The way to recover is to reload the page. The browser keeps a -failed script load for the life of the page, so the Host cannot fetch the -same bundle URL again, and a retry in the page does not help. Once the tag is -defined, every card still waiting on it updates without further action. - -A reload is also triggered by the proxy's `@reconnect` event — fired with no -payload after the Host's WebSocket reconnects following a drop — so a form -left stale through a brief backend restart or network blip corrects itself -once the socket comes back, without a manual page reload. - -## See Also - -- [Session Forms (framework)](../../framework/session-forms.md) — the - `ask_user` / `read_form` tools, the trait, and how an answer is admitted +| `unsupported` | An unrecognized `form-version` (from the prop or the loaded state), or a Web Host without the `artifactState` export. It takes priority over every other value, and the card is never interactive or submittable. | + +A missing or failed component bundle never reaches any `card-state` above. The +`wippy-form` script never registers, or registration times out, and the Host's +own component loader shows "This part of the page could not load. Reload to +try again." in its place. The real cause goes only to the browser console, as +one of two load-failure log lines: a script error ("script failed to load") or +a registration timeout ("failed to load in time"). Each is logged once per +failed tag and not once per card that tried to mount it. The way to recover is +to reload the page. The browser keeps a failed script load for the life of the +page, so the Host cannot fetch the same bundle URL again, and a retry in the +page does not help. Once the tag is defined, every card still waiting on it +updates without further action. + +The proxy's `@reconnect` event also triggers a reload. It fires with no +payload after the Host's WebSocket reconnects following a drop, so a form left +stale through a brief backend restart or network blip corrects itself once the +socket comes back, without a manual page reload. + +## See also + +- [Session Forms (framework)](../../framework/session-forms.md): the + `ask_user` and `read_form` tools, the trait, and how an answer is admitted into the conversation -- [Chat Web Components](./chat-web-components.md) — other host-provided, +- [Chat Web Components](./chat-web-components.md): other host-provided, auto-registered elements delivered the same way -- [Proxy API](./proxy-api.md) — the rest of `@wippy-fe/proxy` / +- [Proxy API](./proxy-api.md): the rest of `@wippy-fe/proxy` and `getWippyApi()` -- [Web Component Recipe](./web-component.md) — building your own +- [Web Component Recipe](./web-component.md): building your own `view.component`, for contrast with these host-provided ones From 6ed57cc2903d26c463fe489165e85605606c4b44 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 1 Oct 2026 18:03:11 +0200 Subject: [PATCH 10/16] docs(session-forms): tighten the framework page and fix the read_form results The admission section is now two sentences and a table, and the compatibility and limits sections are gone because the frontend page and the tool table already hold those facts. The read_form table shows the real result shape of each status, and the option description limit is stated. The text no longer mentions dismissing forms or a fallback fields form. --- en/framework/session-forms.md | 253 ++++++++++------------------------ 1 file changed, 73 insertions(+), 180 deletions(-) diff --git a/en/framework/session-forms.md b/en/framework/session-forms.md index ff744bbf..da9328f7 100644 --- a/en/framework/session-forms.md +++ b/en/framework/session-forms.md @@ -12,16 +12,15 @@ The `wippy/session` module owns the feature. It provides a trait that adds the in the chat, and an HTTP endpoint that accepts the answer and delivers it to the session as an ordinary user message. -This release supports choice questions only. A choice question allows a single -or a multiple selection, can be required or optional, and can offer a -free-text "Other" answer. Other field types are planned for a later release. -A renderer that meets a field type it does not support shows a fallback form -and never drops the question silently. +Only choice questions are supported. A choice question takes one or several +selections, can be required or optional, and can offer a free-text "Other" +answer. -This page documents the trait, the tool contracts, and how an answer reaches -the conversation. For the `wippy-form` / `wippy-form-answers` components and -the HTTP contract from the browser side, see -[Session Forms (frontend)](../frontend/micro-frontends/session-forms.md). +For the `wippy-form` and `wippy-form-answers` components and the browser side +of the HTTP contract, see +[Session Forms (frontend)](../frontend/micro-frontends/session-forms.md). The +Web Host version that the question card needs is listed under +[Host requirement](../frontend/micro-frontends/session-forms.md#host-requirement). ## Enabling the trait @@ -43,9 +42,9 @@ Add `wippy.session.forms:ask_user` to an agent's `traits`: - id: wippy.session.forms:ask_user ``` -The trait requires a `wippy/session` version that ships session forms. With -an older one, an agent definition that references the trait fails to resolve -at lint time rather than silently doing nothing. +The trait needs a `wippy/session` release that ships Session Forms. With an +older release, an agent that references the trait fails to resolve at lint +time. The trait contributes two tools and a block of prompt text. The prompt tells the model the following. @@ -57,11 +56,12 @@ the model the following. - Treat an answer with `"late": true` as context only, and confirm with the user before acting on the earlier request. - Call `read_form` with a `form_id` to see an earlier form, and never write a - `<wippy-form-answers>` element by hand. + `<wippy-form-answers>` element by hand, because the element carries meaning + only in the exact format the server writes. An agent without the trait cannot call `ask_user`, but its prompt still -includes the deterministic form index described below, and it can read a -submitted answer like any other user message. +includes the form index described below, and it can read a submitted answer +like any other user message. ## The `ask_user` tool @@ -82,30 +82,26 @@ agent can retry in the same turn. | `fields[].label` | The question, 1 to 240 characters | | `fields[].description` | Optional help text, at most 1,000 characters | | `fields[].required` | Boolean, default `false` | -| `fields[].options` | 1 to 20 distinct choices. A plain string is both the value and the label. Use `{ "value", "label", "description"? }` when the stored value should differ from the shown text | -| `fields[].multiple` | Boolean, default `false`: allow selecting several options | -| `fields[].allow_other` | Boolean, default `false`: offer a free-text "Other" answer | +| `fields[].options` | 1 to 20 distinct choices. A plain string is both the value and the label. Use `{ "value", "label", "description"? }` when the stored value should differ from the shown text. Value and label are at most 240 characters, and `description` is at most 1,000 | +| `fields[].multiple` | Boolean, default `false`. Allows selecting several options | +| `fields[].allow_other` | Boolean, default `false`. Offers a free-text "Other" answer | The normalized definition is bounded to 32 KiB. The size is measured after normalization, where a plain string option expands to `{"value": .., "label": ..}`, so a definition with many short string options can be well over the limit even when it looks compact. In that case the tool error reports the -actual normalized size. Labels and descriptions are rendered as plain text and -are never parsed as Markdown or HTML. Control characters other than tabs and -newlines (in multi-line fields) are rejected. +actual normalized size. Labels and descriptions are never parsed as Markdown or +HTML, and the card shows only text in backticks as inline code. Control +characters other than tabs and newlines (in multi-line fields) are rejected. -A successful call ends the agent's turn. The tool result is a factual, -past-tense sentence: +A successful call ends the agent's turn and returns the text below. The trait +prompt tells the agent not to add a follow-up, because the form is already +visible. ```text Form "Delivery preference" was created as <artifact-id>. Its answer will arrive as a user message. ``` -The agent should not run a further model step to say "please fill in the -form", because the form is already visible. A short continuation costs an -extra model step and does not affect correctness, because the form is already -stored. - ### One form per turn At most one form can be created per agent turn. A second `ask_user` call in @@ -116,8 +112,8 @@ This turn already asked the user with a form. No second form was created; wait f ``` A session can hold up to 100 unresolved (unanswered) forms at once. Above -that, `ask_user` is rejected with `too_many_forms` and the agent is asked to -resolve or supersede older forms. Nothing is deleted automatically. +that, `ask_user` is rejected with `too_many_forms` until the user answers +older forms. Nothing is deleted automatically. A form's definition is immutable once created. There is no edit operation, and an attempt to update a form artifact through the general artifact-update path @@ -126,11 +122,10 @@ instead.` To change a question, ask a new form. ## What the agent receives -The user answers on a question card (see the frontend page for the UI). The -accepted answer becomes one ordinary user message, built entirely on the -server, and the browser never supplies its text. The message has exactly one -visible line, followed by an invisible carrier element that holds the full -answer as JSON: +The user answers on a question card. The accepted answer becomes one ordinary +user message, built entirely on the server, and the browser never supplies its +text. The message has exactly one visible line, followed by an invisible +carrier element that holds the full answer as JSON: ```text Answered questions about the delivery of your order. @@ -141,11 +136,9 @@ Answered questions about the delivery of your order. The user sees only the first line, which is the `answered_message` the agent supplied when it called `ask_user` (or the `Answered “<title>”.` fallback). -The `wippy-form-answers` component that the Session ships renders nothing, so -the record never appears in the chat. The agent reads the raw message text, -including the record attribute, on its next turn. The answered form card shown -above the message is the summary for the user, and the record is the summary -for the agent. +The `wippy-form-answers` element renders nothing, so the record never appears +in the chat. The agent reads the raw message text, including the record +attribute, on its next turn. ### Record shape @@ -157,8 +150,8 @@ question id, `answers[id]` has a `question` (the field's label) and an | Answer shape | When | | --- | --- | | `{"value": "courier", "label": "Courier"}` | A chosen option | -| `{"value": "courier", "label": "Courier", "note": "…"}` | A chosen option with the user's own note | -| `{"other": "…"}` | The user's own free-text answer | +| `{"value": "courier", "label": "Courier", "note": "…"}` | A chosen option with the user's own note, at most 1,000 characters | +| `{"other": "…"}` | The user's own free-text answer, at most 2,000 characters | | `[ ...one of the above... ]` | A multiple-selection question, in definition order, with an "Other" entry (if any) last | | `null` | The question was left unanswered (only possible when not required) | @@ -203,15 +196,16 @@ chose. returns the state of one form belonging to the calling session. A form from another session is not visible. The result depends on the form's state: -| `status` | Meaning | +| `status` | Result | | --- | --- | -| `unanswered` | Returns the form's `title` and `questions` (each with its options), so an agent that lost the original `ask_user` result can restate them | -| `answer_pending` | The user answered, but the answer has not been admitted into this session's history yet (see below). No answer values are returned, and the agent must wait for the answer to arrive as a user message | -| `answered` | Returns the same self-contained record described above, plus `answered_at` | +| `unanswered` | `{ status, form_id, title, questions }`, where each question carries its options, so an agent that lost the original `ask_user` result can restate them | +| `answer_pending` | `{ status, form_id, title, note }`. The user answered, but the answer has not been admitted into the session's history yet (see below). No answer values are returned, and the `note` tells the agent to wait for the answer to arrive as a user message | +| `answered` | `{ status, answered_at, form }`, where `form` is the self-contained record described above | Every agent, with or without the trait, also gets a bounded, deterministic -index of the session's forms in its prompt. The index is computed fresh on -every prompt build, so it cannot drift from the stored forms: +index of the session's forms in its prompt. The index is rebuilt from the +stored forms on every prompt build, so it cannot drift from them, and it does +not depend on a checkpoint having kept any form ids or values. ```text Session forms (index; exact answers are in the answer messages and can be read with read_form when available): @@ -223,153 +217,52 @@ Session forms (index; exact answers are in the answer messages and can be read w The index lists up to 8 unanswered or pending forms (newest first) and up to 4 answered forms (most recently answered first), bounded to 8 KiB, and it -reports how many were omitted. A summarizing checkpoint is free text and may -drop form ids or values. The index is rebuilt from the stored artifacts on -every prompt, so it does not depend on the checkpoint having preserved -anything. +reports how many were omitted. ## How answers are admitted -Submitting a form's answer (see the frontend page for the HTTP contract) -commits the answer and the user message in one transaction, then publishes an -artifact-update event and wakes the owning session process. The stored row, -and not the wake-up, makes delivery durable, so a missed wake-up does not lose -the answer. - -A form answer is never steered into a running turn. It stays pending until the -turn ends, no matter how the session is configured. Typed input follows the -session's own steering setting instead. It can be admitted mid-turn when the -agent has the `wippy.session.traits:steering` trait, or when the session sets -a `steer` input-policy override. Once a turn ends, pending answers and any -steered input the session held are admitted together, in the order they were -durably accepted. - -Admission order follows the order in which answers were durably accepted, and -the rest depends on what the session is doing: - -- If the session is idle, the answer is admitted immediately and a new turn - starts to answer it. -- If a turn is running, the answer stays out of that turn's prompt. It is - marked pending, and `read_form` reports `answer_pending` for it. It is - admitted once the turn ends, in acceptance order together with any typed - input the session held during the turn, and the next turn answers the latest - admitted message. -- If the user pressed Stop, the answer is still admitted and becomes ordinary - visible history, but no new turn starts for it. The form reads as delivered, - and the user continues by sending a message. The same holds when the session - plugin has to enforce the Stop itself. If a turn does not stop within 10 - seconds, the plugin cancels and then terminates the session process, and the - pending answers are admitted with no turn exactly as an honored Stop's would - be. They do not wait for the next session start to run an unattended turn. -- If the session is finishing, or the process is not running (idle timeout, - crash, restart), the answer stays pending. The next time the session process - starts, it scans for pending answers before anything else and queues their - admission, so recovery needs no external retry. - -The user's session plugin also drives this recovery from outside any one -session. It starts a stopped session that still holds an unadmitted answer, -once right after the plugin itself starts and again on every periodic scan -after that. An answer is therefore still delivered when its original wake-up -was lost, and the start admits the answer and runs a turn for it, like any -other session start with a pending answer. - -The same plugin start also settles any of the user's sessions left stored as -"running" with no live process, for example after a runtime restart, back to -idle. The settling changes only how an already-admitted answer reads. An -answer that the turn had picked up before the process disappeared now reads as -interrupted ("send a message to continue") and no longer reads as running. A -pending answer is not affected by the settling, because it is unrelated to the -session's stored status. It is admitted with a turn the next time the session -starts, as described above. - -Once admitted, the answer's message row is re-dated to the moment of -admission rather than the moment it was accepted, so its place in the visible -history follows admission order. The `submitted_at` that the artifact-state API -returns (see the frontend page) is unaffected and keeps the original -acceptance time. - -The agent must never treat an `answer_pending` form as answered, and must -never guess its content before the real answer message arrives. +Submitting an answer commits it together with the user message in one +transaction, so the stored row, and not the wake-up of the session process, +makes delivery durable. A form answer is never steered into a running turn, +whatever the steering setting. Typed input follows the session's steering +setting. -## Security notes +| When the answer is accepted | What happens | +| --- | --- | +| The session is idle | The answer is admitted at once, and a new turn starts | +| A turn is running | The answer is pending, and `read_form` reports `answer_pending`. It is admitted when the turn ends, in acceptance order together with any typed input the session held during the turn | +| The user pressed Stop | The answer is admitted into the history and no turn starts. The same happens when the session plugin has to cancel or terminate a session that does not stop in time | +| The session is finishing, or its process is not running | The answer stays pending until the process starts again. The session plugin starts stopped sessions that hold pending answers | -The text of the answer message, which is the sentence and the record, is built -entirely by the server from the immutable definition and the validated, -normalized answers. The browser sends only structured `answers` keyed by field -id and never sends message text. User-supplied text (an "Other" answer or a -note) is JSON-escaped data inside the record's `answer` object and is never raw -markup. The server escapes `'`, `<`, `>`, and `&` inside the record, so user -text cannot end the attribute, close the tag, or add markup. - -The trait's prompt tells the agent never to write a `<wippy-form-answers>` -element itself. The tag carries meaning only in the exact wire format the -server writes, and an agent-authored one would not match a real accepted -answer. +Once admitted, the answer's message is dated at the moment of admission, so +its place in the visible history follows admission order. The `submitted_at` +value that the artifact-state API returns keeps the original acceptance time. + +## Security notes -Every state read or write checks authentication, then that the artifact -belongs to the caller and its session, then read (GET) or write (POST) -permission on that session, before doing anything with the form. A missing -artifact, another user's artifact, and an artifact whose session is gone or -not the caller's all return the same 404, so the endpoint does not reveal that -a foreign form exists. +The server builds the answer message from the immutable definition and the +validated, normalized answers. The browser sends only answers keyed by field +id, never message text. User text (an "Other" answer or a note) is +JSON-escaped data inside the record, and the server escapes `'`, `<`, `>`, and +`&` in the record, so user text cannot end the attribute, close the tag, or +add markup. The checks that the state endpoint applies to every request are +listed in [The artifact-state HTTP API](../frontend/micro-frontends/session-forms.md#the-artifact-state-http-api). ## Disabling and rolling back -Disabling new form creation is a config-only change. Remove -`wippy.session.forms:ask_user` from an agent's `traits:` list. There is no -deploy step, no feature flag, and no separate kill switch. +To stop new forms, remove `wippy.session.forms:ask_user` from an agent's +`traits` list. - Open (unanswered) forms stay answerable. The state API's read and write checks are session-ownership checks and not trait checks, so a form asked before the trait was removed can still be submitted afterward. - Answered forms stay readable, with or without the trait on any agent. An answered form is an ordinary artifact plus an ordinary user chat message, - and `read_form` and the prompt's form index work the same for every agent. -- Do not downgrade the `wippy/session` module below the release that shipped - Session Forms while any form artifacts exist. Rendering `wippy-form` and - `wippy-form-answers` needs their `view.component` registry entries to be - registered and served by the running module version. A consumer that - registers its own forms-related entries can fail to boot on an older module, - because one of those entries stays unresolved and the runtime refuses to - start with `failed to load state: unresolved dependencies after retry: …`. - The boot behavior of an older module is not defined for a consumer whose - only reference is an agent's `wippy.session.forms:ask_user` trait, so treat - that case as a risk too. Removing the trait is the supported way to stop new - forms. Downgrading the module is a separate action with this failure mode. - -## Compatibility - -- The question card submits through the `artifactState` client, which only - Web Host 1.0.61 or later provides (see - [Host requirement](../frontend/micro-frontends/session-forms.md#host-requirement)). - On an older Host the card shows the questions with disabled options and a - notice that the form needs a newer Web Host, and nothing can be submitted. - The user's answer message and the agent's reply stay readable in the chat. -- A form whose `form_version` is not `1` shows a notice and never a submit - control. -- When the component bundle is missing, the Host shows its load-failure - fallback in place of the card, and reloading the page recovers it. - -## Limits at a glance - -| Limit | Value | -| --- | --- | -| Form title | 160 characters | -| Description (form or field) | 1,000 characters | -| `submit_label` | 40 characters | -| `answered_message` | 200 characters | -| Fields per form | 1 to 20 | -| Field label | 240 characters | -| Options per field | 1 to 20 | -| Option text | 240 characters | -| "Other" answer text | 2,000 characters | -| Note text | 1,000 characters | -| Normalized definition size | 32 KiB | -| Submission request body | 64 KiB | -| Unresolved forms per session | 100 | -| Form index (prompt injection) | 8 unanswered/pending + 4 answered, 8 KiB total | - -Form submission has no rate limit. + and `read_form` and the form index work the same for every agent. +- Do not downgrade `wippy/session` below the release that shipped Session + Forms while form artifacts exist. The module registers the `wippy-form` and + `wippy-form-answers` components, and an older module can fail to start with + `failed to load state: unresolved dependencies after retry: …`. ## Verifying From 8f1f6b0fe443e98023e933fbf78246de611763a4 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 1 Oct 2026 18:03:13 +0200 Subject: [PATCH 11/16] docs(session-forms): tighten the frontend page and match the 1.0.61 Host source The Host requirement table now holds the whole pre-1.0.61 behavior, and repeated notes on the carrier element, reconnect and accessibility are gone. The GET example has a real field, the POST section states the request_id and answers rules, and the 404 and permission checks live here. The isArtifactStateError paragraph now matches the Host source, where the class overrides Symbol.hasInstance to check the same brand. --- en/frontend/micro-frontends/session-forms.md | 786 +++++++++---------- 1 file changed, 372 insertions(+), 414 deletions(-) diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index 81288ca4..cc53de57 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -1,414 +1,372 @@ ---- -title: "Session Forms" -description: "The wippy-form question card and the wippy-form-answers carrier element: what they render, how they load, and the artifact-state HTTP API behind them." ---- - -# Session Forms - -`wippy/session` ships two `view.component` web components that render a -Session `ask_user` form (see -[Session Forms (framework)](../../framework/session-forms.md) for the -`ask_user` tool and the answer contract). `<wippy-form>` is the interactive -question card. `<wippy-form-answers>` is an invisible carrier that keeps a -form's answer record reachable to the agent without showing it to the user -twice. Like the chat elements in -[Chat Web Components](./chat-web-components.md), both are host-provided -elements to consume. The Session module registers and serves them, and an -application that embeds a chat surface does not author or bundle either one. - -## `<wippy-form>`: the question card - -For a version 1 definition, every field has `type: "choice"`, and the -component renders a question card instead of a plain fields form. A form with -several questions shows one question at a time with a `‹ n/total ›` counter, -per-answer notes, an "Other" free-text row, a review step before sending, and -a read-only answered summary afterward. A mixed or non-`choice` definition -(reserved for a later release) falls back to a plain radio and checkbox fields -form. - -| Prop (HTML attribute) | Type | Default | Description | -| --- | --- | --- | --- | -| `form-version` | `number` | `1` | Definition schema version. A value other than `1`, whether it comes from this prop or from the loaded state's own `form_version`, disables the interactive form and shows a compatibility notice instead of ever rendering a `Submit`. | -| `definition` | `object` | `null` | The immutable form definition: `title`, optional `description`, optional `submit_label`, optional `answered_message` (never displayed), and `fields`. | -| `state` | `string` | `"active"` | Package-tag lifecycle: `"active"` (answerable) or `"idle"` (already answered, read-only). Changing it reloads canonical state from the Host. | -| `density` | `string` | `"compact"` | `"compact"` or `"comfortable"` sizing. Read purely through a `:host([density="comfortable"])` CSS selector. | - -The component owns its own data loading, submission, and offline detection. A -host only needs to mount the tag with these attributes. - -- It loads the state with a `GET` on mount, and reloads it on a visibility - change, a session-message event, an artifact-update event, the Host's - `@reconnect` event after a WebSocket reconnect, or the browser's `online` - event. -- It submits with a client-generated `request_id` that it reuses on a retry, - retries once automatically after a network failure with no response, and - handles a 422 field-error response and a 409 already-submitted response. - -### Behavior - -- The card shows one question at a time. Answering (a click, or a number key - for the first nine rows) moves to the next unseen question, and Previous and - Next navigate back to change an earlier answer. A form with several - questions ends on a review that lists every answer, with a single "Send - answers" action. There is no per-question submit once the review is reached. -- Every answer row has a note toggle, and the field's `allow_other` setting - controls the "Other" row. - - A note is the user's own text about that one chosen option. It changes the - answer's shape to `{ "value": "…", "note": "…" }` and does not add a - separate field. - - "Other" is a joined free-text input with its own send button, offered only - when the field's `allow_other` is set. -- Once submitted, the card shows a read-only summary of exactly what was - accepted, including any notes and the submission time. The card has no close - or decline button, and it never takes focus on its own. - -The keyboard shortcuts are scoped to focus inside the card, so they never -intercept typing in the surrounding chat composer. - -| Key | Action | -| --- | --- | -| 1 to 9 | Answers or ticks the corresponding row. Only the first nine rows get a number, and a question can have more options than that | -| Shift+1 to 9, or N on a focused row | Opens that row's note | -| Enter | Sends from Other or a note, or saves a note and ticks its row on a several-answer question | -| Shift+Enter | Adds a line | -| Escape | Leaves a note or Other box | -| Arrow keys | Move between rows and between questions | - -### Events - -| Event | Payload | When | -| --- | --- | --- | -| `answer-submitted` | `{ requestId, answerMessageId, late }` | After a submission is durably accepted, including an exact replay | -| `error` | `{ message, error }` | An unrecoverable component-level error | -| `invalid` | `{ message }` | Invalid props/config | - -## `<wippy-form-answers>`: the answer carrier - -The Session server writes this element into the user's chat message -immediately after they answer a form (see -[the record shape](../../framework/session-forms.md#record-shape)): - -```html -Answered questions about the delivery of your order. - -<wippy-form-answers record='{"form_id":"…","form_version":1,"title":"Order details","late":false,"answers":{...}}'> -</wippy-form-answers> -``` - -It renders nothing. It has no shadow-root content and no `<slot>`, and it sets -`:host { display: none; }` as defense in depth. Its only prop is `record` (the -single-line JSON string), and its only public member is a read-only -`answerRecord` getter that parses that attribute and returns the parsed -object, or `null` on missing or invalid JSON. It dispatches no events and -makes no host API calls of its own beyond the theme subscription every Wippy -element gets. - -Agents must never emit this tag themselves. It is written exclusively by the -Session server's message-composition code as part of the fixed answer format, -and it carries no meaning outside that exact wire format. - -### Why the record lives in an attribute - -Two failure modes both leave the tag on the page with no children. In the -first, the chat sanitizer strips an unrecognized tag, for example right after -a fresh deploy and before the Host has re-fetched the updated components list. -In the second, an unloaded or failed component script leaves the browser -treating the tag as an anonymous `HTMLElement`, which still renders its -children by default. An element with no children renders nothing either way, -and an element with visible text content would have shown the raw JSON to the -user for that entire window. Because the record is in an attribute, every -failure mode still shows nothing. - -## How the components load - -Both are `view.component` registry entries with `auto_register: true`, served -by the Session module at `/wippy-session-forms` (`wippy-form`) and -`/wippy-session-form-answers` (`wippy-form-answers`). The Web Host auto-loads -every `auto_register: true` component at boot and allows its tag, plus its -declared prop attribute names, through the chat message sanitizer. The names -are `definition`, `form-version`, `state` and `density` for `wippy-form`, and -`record` for `wippy-form-answers`. `record` is declared as a `wippy.props` -entry so that the sanitizer's allowed-attribute list includes it. Without that -declaration the attribute is stripped even when the tag itself is allowed -through. - -## Host requirement - -`<wippy-form>` submits through `artifactState`, a typed client that the Web -Host exports from every proxy realm (`$W.artifactState()` in an iframe, or the -named `artifactState` export from `@wippy-fe/proxy` in a host-mounted web -component). Web Host 1.0.61 or later exports it, and no earlier release does. -The matching npm release is `@wippy-fe/*` 0.0.61. - -The component never fabricates a success or a mock answer. It checks the -conditions in the order of the following table, and the first one that -applies decides what the card shows. - -| Condition | What the card shows | -| --- | --- | -| `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." The card reflects `card-state="unsupported"`. | -| The Host has no `artifactState` export (every Web Host release before 1.0.61) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. | -| The Host exports `artifactState`, but no artifact id is available in the element's context | The questions rendered read-only, with "This form cannot be submitted here." | - -### Behavior on a Web Host before 1.0.61 - -A Web Host from before 1.0.61 has neither the `artifactState` export nor the -`data-wippy-artifact-id` attribute, so the component checks for the export -first. A newly asked form shows the real questions with disabled radio -buttons, no buttons in the card, and no placeholder rows. Every option is -unselected, because the saved answer cannot be read without the artifact-state -API, so the card cannot show what was chosen. The notice therefore points to -the chat, where the user's one-line answer message and the agent's reply stay -readable. The hidden answer record never appears, and nothing is mocked. In a -chat of answered forms, each card reads "This form was answered. Your answer is -in the chat." - -The older `instance.form` adapter that `artifactState` replaces is described -under [`artifactState` and the deprecated -`instance.form`](#artifactstate-and-the-deprecated-instanceform). - -## The artifact-state HTTP API - -`GET` and `POST /api/v1/artifact/{id}/state` read a form's canonical state and -accept its answer. The concrete path comes from the route table -(`artifacts.state`) and can be overridden per deployment through -`feature.apiRoutes`, like any other Wippy Web Host route. - -### `GET /api/v1/artifact/{id}/state` - -```json -{ - "form_version": 1, - "artifact_id": "artifact-uuid", - "session_id": "session-uuid", - "status": "active", - "stale": false, - "late": false, - "content_version": 1, - "definition": { "title": "Delivery preference", "fields": [] }, - "data": null, - "submitted_at": null, - "answer_message_id": null, - "delivery": null -} -``` - -`status` is `"active"` (unanswered) or `"idle"` (answered). `stale` is computed -live and is meaningful only while `status` is `"active"`. It is `true` once a -different real user input was durably accepted after the form was created. -`data` holds the exact accepted answers once answered. `delivery` reports -`"pending"`, `"running"`, `"complete"`, or `"interrupted"` for an answered -form, and it is `null` for an unanswered one. It is derived from the message -history and not from a stored flag. Responses always carry -`Cache-Control: no-store`. - -### `POST /api/v1/artifact/{id}/state` - -```json -{ - "form_version": 1, - "request_id": "client-generated-uuid", - "expected_content_version": 1, - "answers": { "delivery": "Courier" } -} -``` - -`request_id` should be generated once, at the moment the user attempts -submission, and reused unchanged on any retry of that same attempt. The server -recognizes a same-id, same-answers retry as a replay (`replayed: true` in the -response) and not as a conflict. `expected_content_version` is optional. When -it is present, it is checked against the artifact's current revision, so a -stale client cannot silently overwrite a form's state. - -Success: - -```json -{ - "success": true, - "artifact_id": "artifact-uuid", - "request_id": "client-generated-uuid", - "answer_message_id": "message-uuid", - "content_version": 2, - "status": "idle", - "late": false, - "delivery": "pending", - "replayed": false -} -``` - -A `200` here means the answer and its user message are durably accepted. It -does not mean the agent has replied yet, so show something like "Submitted. -Waiting for the assistant." - -| Status | Meaning | -| --- | --- | -| 200 | Accepted (or an exact replay of an already-accepted submission, `replayed: true`) | -| 400 | Malformed JSON, missing/invalid envelope fields, a missing/invalid artifact id, or `not_a_form` for an artifact that exists but is not a session form | -| 401 | No authenticated actor | -| 403 | Authenticated, but no read/write permission on the form's session | -| 404 | Artifact or session not found, or not owned by the caller | -| 409 `request_conflict` | Same `request_id`, different normalized answers than the first attempt with that id | -| 409 `already_submitted` | The form was already answered by a different request | -| 409 `version_conflict` | `expected_content_version` no longer matches the current revision | -| 413 | Request body over 64 KiB | -| 415 | `Content-Type` is not `application/json` | -| 422 | Field validation failed, with `errors` keyed by field id and a `form_errors` list | -| 500 | Internal error; no mutation was applied | - -Submissions are not rate-limited server-side, so the API never returns `429`. - -## The `artifactState` proxy client - -```typescript -const client = (await $W.artifactState())('artifact-uuid') -// or, inside a web component: import { artifactState } from '@wippy-fe/proxy' - -const state = await client.get() -const result = await client.submit({ - form_version: 1, - request_id: crypto.randomUUID(), - expected_content_version: state.content_version, - answers: { color: 'blue' }, -}) -``` - -- The route is re-resolved on every call. Nothing is cached when - `artifactState(artifactId)` is constructed, and no global config is mutated. -- `artifactId` is validated up front, and an empty or whitespace-only id - throws synchronously. -- Every failure, whether an HTTP status or a network error, rejects with a - typed `ArtifactStateError` (`status`, `code`, and, for a 422, `errors` keyed - by field id plus `formErrors`). The client never fabricates a success or - failure body. - -```typescript -try { - await client.submit(envelope) -} -catch (error) { - if (isArtifactStateError(error) && error.status === 422) { - // error.errors: Record<string, { code: string, message: string }[]> - } - throw error -} -``` - -Prefer `isArtifactStateError(error)` over `error instanceof -ArtifactStateError`. The class is built separately into every proxy entry -point and into the published `@wippy-fe/proxy` npm package, so an `instanceof` -check against a class imported from a different bundle's copy can silently -never match, even for an error that the same client threw. -`isArtifactStateError` checks a brand that is stable across realms. The class -also overrides `Symbol.hasInstance` to run the same check, so a plain -`instanceof` works too, but `isArtifactStateError` is the safer spelling. - -### `artifactState` and the deprecated `instance.form` - -`instance.form.get()` and `.submit(data)` are a thin backward-compatibility -shim over `artifactState(appConfig.context.resourceId)`. A 422 maps to the -legacy `{ success: false, errors }` shape. Every other failure (401, 404, 409, -5xx, network) rethrows the same error that `artifactState` would throw, and -the shim never returns a mock success or failure. New code should call -`instance.artifactState(artifactId)` directly and not this deprecated shim. - -## Styling API - -`<wippy-form>` follows the Session Forms styling contract. - -- Every visual value is a `--wippy-form-*` custom property with a semantic - theme-variable fallback, and never a raw hex as the primary fallback. -- Every restylable piece is exposed as a `::part()`. State is reflected as - both a `<part>-<state>` part and a `w-form__<part>--<state>` class. -- State that a stylesheet needs is a host attribute (`density`, `card-state`, - `collapsed`). - -The full token, part, and host-attribute tables, plus a restyle example, are -in the package's own README (`frontend/wippy-form/README.md` in the -`wippy/session` source). `<wippy-form-answers>` has no visible surface and -exposes no styling API, because hiding the record is its entire purpose. - -## Accessibility - -Each question has an accessible group label. A single-selection field is a -`role="radiogroup"` with `aria-required` when required, and a -multiple-selection field is a `role="group"`. A single-selection group is one -Tab stop, with a roving `tabindex` that arrow keys move between its rows (the -WAI-ARIA radio group pattern). A multiple-selection group leaves every row its -own Tab stop, because each row is an independent checkbox. - -A field-level error renders as a `role="alert"` element, linked to its group -or text box through `aria-describedby`, so a screen reader announces the error -text as soon as it appears. A single polite live region announces question and -review navigation (for example "Question 2 of 4" or "Review your answers"), -tick and untick changes, and submission-result and validation-summary text, -without moving focus. - -The [keyboard behavior](#behavior) covers answering, navigation, and notes -without a pointer. Escape in a note or the Other box only closes the editor, -and the typed draft stays saved with that answer. After a full submission is -accepted, focus moves to the read-only summary's status text, so it is not -lost when the card swaps from the active view to the answered one. - -## Known gaps - -- The tick boxes, radio marks, and input edges use the theme's existing - surface-300/700 border colors, which give roughly 1.3 to 1.4:1 contrast, - with no local override. The fix belongs in the theme and not in this - component. -- The two "Send" buttons and the two composer send buttons are unstyled - PrimeVue defaults. They follow the theme's own primary button color and not - `--wippy-form-accent`, so retinting `--wippy-form-accent` alone leaves them - on the old color while rows, the counter, key badges, and the focus ring - follow the new one. -- The Notes and Other text boxes use the theme's own `.p-textarea` colors. - No `--wippy-form-input-bg` or `--wippy-form-input-border` tokens exist yet. -- The following defaults may change in a later release: - - The answer shape of a note (`{value, note}` or a separate field). - - A newly opened card does not take keyboard focus on its own. - - Only backticks render as inline code, with no other Markdown-style - formatting. - - Only the first nine rows of a question get a number-key badge, and there - is no cap on how many options a question can have. - -## Diagnostics - -`<wippy-form>` reflects its own state as the `card-state` host attribute. The -attribute exists for styling, and it is also the fastest way to read what the -component is doing from the DOM or an end-to-end test: - -| `card-state` | Meaning | -| --- | --- | -| `loading` | Before the artifact's first `GET` resolves; `<wippy-loading>` shows instead of the card. | -| `active` | Answerable: a question, the review step, or briefly, the submitting state. | -| `review` | The review step of a several-question form, before "Send answers". | -| `answered` | The read-only summary of an accepted submission. | -| `unsupported` | An unrecognized `form-version` (from the prop or the loaded state), or a Web Host without the `artifactState` export. It takes priority over every other value, and the card is never interactive or submittable. | - -A missing or failed component bundle never reaches any `card-state` above. The -`wippy-form` script never registers, or registration times out, and the Host's -own component loader shows "This part of the page could not load. Reload to -try again." in its place. The real cause goes only to the browser console, as -one of two load-failure log lines: a script error ("script failed to load") or -a registration timeout ("failed to load in time"). Each is logged once per -failed tag and not once per card that tried to mount it. The way to recover is -to reload the page. The browser keeps a failed script load for the life of the -page, so the Host cannot fetch the same bundle URL again, and a retry in the -page does not help. Once the tag is defined, every card still waiting on it -updates without further action. - -The proxy's `@reconnect` event also triggers a reload. It fires with no -payload after the Host's WebSocket reconnects following a drop, so a form left -stale through a brief backend restart or network blip corrects itself once the -socket comes back, without a manual page reload. - -## See also - -- [Session Forms (framework)](../../framework/session-forms.md): the - `ask_user` and `read_form` tools, the trait, and how an answer is admitted - into the conversation -- [Chat Web Components](./chat-web-components.md): other host-provided, - auto-registered elements delivered the same way -- [Proxy API](./proxy-api.md): the rest of `@wippy-fe/proxy` and - `getWippyApi()` -- [Web Component Recipe](./web-component.md): building your own - `view.component`, for contrast with these host-provided ones +--- +title: "Session Forms" +description: "The wippy-form question card and the wippy-form-answers carrier element: what they render, how they load, and the artifact-state HTTP API behind them." +--- + +# Session Forms + +`wippy/session` ships two `view.component` web components that render a +Session `ask_user` form (see +[Session Forms (framework)](../../framework/session-forms.md) for the +`ask_user` tool and the answer contract). `<wippy-form>` is the interactive +question card. `<wippy-form-answers>` is an invisible carrier that keeps a +form's answer record reachable to the agent without showing it to the user +twice. Like the chat elements in +[Chat Web Components](./chat-web-components.md), both are host-provided +elements to consume, so an application that embeds a chat surface does not +author or bundle either one. + +## `<wippy-form>`: the question card + +For a version 1 definition the component renders a question card. + +| Prop (HTML attribute) | Type | Default | Description | +| --- | --- | --- | --- | +| `form-version` | `number` | `1` | Definition schema version. A value other than `1`, whether it comes from this prop or from the loaded state's own `form_version`, shows a compatibility notice and no submit control. | +| `definition` | `object` | `null` | The immutable form definition: `title`, optional `description`, optional `submit_label`, optional `answered_message` (never displayed), and `fields`. | +| `state` | `string` | `"active"` | Package-tag lifecycle: `"active"` (answerable) or `"idle"` (already answered, read-only). Changing it reloads canonical state from the Host. | +| `density` | `string` | `"compact"` | `"compact"` or `"comfortable"` sizing. Read purely through a `:host([density="comfortable"])` CSS selector. | + +The component owns its own data loading, submission, and offline detection. A +host only needs to mount the tag with these attributes. + +- It loads the state with a `GET` on mount, and reloads it on a visibility + change, a session-message event, an artifact-update event, the Host's + `@reconnect` event after a WebSocket reconnect, or the browser's `online` + event. The `@reconnect` reload corrects a form that a brief backend restart + or network drop left stale. +- It submits with a client-generated `request_id` that it reuses on a retry, + retries once automatically after a network failure with no response, and + handles a 422 field-error response and a 409 already-submitted response. + +### Behavior + +- The card shows one question at a time, with a `‹ n/total ›` counter on a + form that has several questions. Answering (a click or a number key) moves to + the next unseen question, and Previous and Next navigate back to change an + earlier answer. A form with several questions ends on a review that lists + every answer, with a single "Send answers" action. There is no per-question + submit once the review is reached. +- Every answer row has a note toggle, and the field's `allow_other` setting + controls the "Other" row. + - A note is the user's own text about that one chosen option. It changes the + answer's shape to `{ "value": "…", "note": "…" }` and does not add a + separate field. + - "Other" is a free-text input with its own send button, offered only when + the field's `allow_other` is set. +- Text in backticks in a question, an option or a description shows as inline + code, and no other formatting is applied. +- Once submitted, the card shows a read-only summary of exactly what was + accepted, including any notes and the submission time. The card has no close + or decline button, and it never takes focus on its own. + +The keyboard shortcuts are scoped to focus inside the card, so they never +intercept typing in the surrounding chat composer. + +| Key | Action | +| --- | --- | +| 1 to 9 | Answers or ticks the corresponding row. Only the first nine rows get a number, and a question can have more options than that | +| Shift+1 to 9, or N on a focused row | Opens that row's note | +| Enter | Sends from Other or a note, or saves a note and ticks its row on a several-answer question | +| Shift+Enter | Adds a line | +| Escape | Leaves a note or Other box and keeps the typed draft with that answer | +| Arrow keys | Move between rows and between questions | + +### Events + +| Event | Payload | When | +| --- | --- | --- | +| `answer-submitted` | `{ requestId, answerMessageId, late }` | After a submission is durably accepted, including an exact replay | +| `error` | `{ message, error }` | An unrecoverable component-level error | +| `invalid` | `{ message }` | Invalid props/config | + +## `<wippy-form-answers>`: the answer carrier + +The Session server writes this element into the user's chat message +immediately after they answer a form (see +[the record shape](../../framework/session-forms.md#record-shape)): + +```html +Answered questions about the delivery of your order. + +<wippy-form-answers record='{"form_id":"…","form_version":1,"title":"Order details","late":false,"answers":{...}}'> +</wippy-form-answers> +``` + +It renders nothing. It has no shadow-root content and no slot, and it sets +`display: none` on the host. Its only prop is `record`, and a read-only +`answerRecord` getter returns the parsed record, or `null` for a missing or +invalid attribute. It dispatches no events. + +### Why the record lives in an attribute + +The record is in an attribute and not in the element's text because an element +with no children renders nothing in every failure case. If the chat sanitizer +strips the unknown tag, or the component script has not loaded, text content +would show the raw JSON. + +## How the components load + +Both are `view.component` registry entries with `auto_register: true`, served +by the Session module at `/wippy-session-forms` (`wippy-form`) and +`/wippy-session-form-answers` (`wippy-form-answers`). The Web Host auto-loads +every `auto_register: true` component at boot and allows its tag, plus its +declared prop attribute names, through the chat message sanitizer. The names +are `definition`, `form-version`, `state` and `density` for `wippy-form`, and +`record` for `wippy-form-answers`. `record` is declared as a `wippy.props` +entry so that the sanitizer's allowed-attribute list includes it. Without that +declaration the attribute is stripped even when the tag itself is allowed +through. + +## Host requirement + +`<wippy-form>` submits through `artifactState`, a typed client that the Web +Host exports from every proxy realm (`$W.artifactState()` in an iframe, or the +named `artifactState` export from `@wippy-fe/proxy` in a host-mounted web +component). Web Host 1.0.61 or later exports it, and no earlier release does. +The matching npm release is `@wippy-fe/*` 0.0.61. + +The component checks these conditions in order, and the first match decides +what the card shows. + +| Condition | What the card shows | +| --- | --- | +| `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." The card reflects `card-state="unsupported"`. | +| The Host has no `artifactState` export (a Web Host before 1.0.61) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. Every option is unselected, because the saved answer cannot be read without the artifact-state API. The user's one-line answer message and the agent's reply stay readable in the chat, and the hidden answer record never appears. | +| The Host exports `artifactState`, but the element has no `data-wippy-artifact-id` attribute (the Host sets it on the artifact elements it mounts) | The questions rendered read-only, with "This form cannot be submitted here." | + +The older `instance.form` adapter that `artifactState` replaces is described +under [`artifactState` and the deprecated +`instance.form`](#artifactstate-and-the-deprecated-instanceform). + +## The artifact-state HTTP API + +`GET` and `POST /api/v1/artifact/{id}/state` read a form's canonical state and +accept its answer. The concrete path comes from the route table +(`artifacts.state`) and can be overridden per deployment through +`feature.apiRoutes`, like any other Wippy Web Host route. Every request checks +authentication, then that the artifact and its session belong to the caller, +then read (`GET`) or write (`POST`) permission on that session. + +### `GET /api/v1/artifact/{id}/state` + +```json +{ + "form_version": 1, + "artifact_id": "artifact-uuid", + "session_id": "session-uuid", + "status": "active", + "stale": false, + "late": false, + "content_version": 1, + "definition": { + "title": "Delivery preference", + "fields": [ + { + "id": "delivery", + "type": "choice", + "label": "How should the parcel be delivered?", + "required": true, + "options": [ + { "value": "Courier", "label": "Courier" }, + { "value": "Pickup point", "label": "Pickup point" } + ], + "multiple": false, + "allow_other": false + } + ] + }, + "data": null, + "submitted_at": null, + "answer_message_id": null, + "delivery": null +} +``` + +`status` is `"active"` (unanswered) or `"idle"` (answered). `stale` is computed +live and is meaningful only while `status` is `"active"`. It is `true` once a +different real user input was durably accepted after the form was created. +`data` holds the exact accepted answers once answered. `delivery` reports +`"pending"`, `"running"`, `"complete"`, or `"interrupted"` for an answered +form, and it is `null` for an unanswered one. It is derived from the message +history and not from a stored flag. Responses always carry +`Cache-Control: no-store`. + +### `POST /api/v1/artifact/{id}/state` + +```json +{ + "form_version": 1, + "request_id": "client-generated-uuid", + "expected_content_version": 1, + "answers": { "delivery": "Courier" } +} +``` + +`request_id` is a non-empty string of at most 128 characters. It should be +generated once, at the moment the user attempts submission, and reused +unchanged on any retry of that same attempt. The server recognizes a same-id, +same-answers retry as a replay (`replayed: true` in the response) and not as a +conflict. `answers` must be an object keyed by field id. +`expected_content_version` is optional. When it is present, it is checked +against the artifact's current revision, so a stale client cannot silently +overwrite a form's state. + +Success: + +```json +{ + "success": true, + "artifact_id": "artifact-uuid", + "request_id": "client-generated-uuid", + "answer_message_id": "message-uuid", + "content_version": 2, + "status": "idle", + "late": false, + "delivery": "pending", + "replayed": false +} +``` + +A `200` here means the answer and its user message are durably accepted. It +does not mean the agent has replied yet, so show something like "Submitted. +Waiting for the assistant." + +| Status | Meaning | +| --- | --- | +| 200 | Accepted (or an exact replay of an already-accepted submission, `replayed: true`) | +| 400 | Malformed JSON, missing/invalid envelope fields, a missing/invalid artifact id, or `not_a_form` for an artifact that exists but is not a session form | +| 401 | No authenticated actor | +| 403 | Authenticated, but no read/write permission on the form's session | +| 404 | Artifact or session not found, or not owned by the caller. All three cases return the same response, so the endpoint does not reveal that a foreign form exists | +| 409 `request_conflict` | Same `request_id`, different normalized answers than the first attempt with that id | +| 409 `already_submitted` | The form was already answered by a different request | +| 409 `version_conflict` | `expected_content_version` no longer matches the current revision | +| 413 | Request body over 64 KiB | +| 415 | `Content-Type` is not `application/json` | +| 422 | Field validation failed, with `errors` keyed by field id and a `form_errors` list | +| 500 | Internal error; no mutation was applied | + +Submissions are not rate-limited server-side, so the API never returns `429`. + +## The `artifactState` proxy client + +```typescript +const client = (await $W.artifactState())('artifact-uuid') +// or, inside a web component: import { artifactState } from '@wippy-fe/proxy' + +const state = await client.get() +const result = await client.submit({ + form_version: 1, + request_id: crypto.randomUUID(), + expected_content_version: state.content_version, + answers: { color: 'blue' }, +}) +``` + +- The route is re-resolved on every call. Nothing is cached when + `artifactState(artifactId)` is constructed, and no global config is mutated. +- `artifactId` is validated up front. An empty or whitespace-only id, or an id + with characters other than letters, digits, `_` and `-`, throws + synchronously. +- Every failure, whether an HTTP status or a network error, rejects with a + typed `ArtifactStateError` (`status`, `code`, and, for a 422, `errors` keyed + by field id plus `formErrors`). + +```typescript +try { + await client.submit(envelope) +} +catch (error) { + if (isArtifactStateError(error) && error.status === 422) { + // error.errors: Record<string, { code: string, message: string }[]> + } + throw error +} +``` + +Prefer `isArtifactStateError(error)` over `error instanceof +ArtifactStateError`. It is `$W.isArtifactStateError` in an iframe, and a named +export of `@wippy-fe/proxy` in a web component. Each proxy entry point and the +published `@wippy-fe/proxy` package bundles its own copy of the class, and +`isArtifactStateError` checks a brand that is the same in every copy. The class +overrides `Symbol.hasInstance` to run the same check, so `instanceof` also +matches an error that another copy threw. + +### `artifactState` and the deprecated `instance.form` + +`instance.form.get()` and `.submit(data)` are a thin backward-compatibility +shim over `artifactState(appConfig.context.resourceId)`. A 422 maps to the +legacy `{ success: false, errors }` shape. Every other failure (401, 404, 409, +5xx, network) rethrows the same error that `artifactState` would throw. New +code should call `instance.artifactState(artifactId)` directly and not this +deprecated shim. + +## Styling API + +`<wippy-form>` exposes `--wippy-form-*` custom properties, `::part()` +selectors and the host attributes `density`, `card-state` and `collapsed`. The +full token, part, and host-attribute tables, plus a restyle example, are in the +package's own README (`frontend/wippy-form/README.md` in the `wippy/session` +source). `<wippy-form-answers>` exposes no styling API because it renders +nothing. + +## Accessibility + +A single-selection question is a `role="radiogroup"` with `aria-required` when +required. It is one Tab stop, and arrow keys move between its rows. A +multiple-selection question is a `role="group"` where every row is its own Tab +stop, because each row is an independent checkbox. A field-level error is a +`role="alert"` element linked to its group or text box through +`aria-describedby`. One polite live region announces question and review +navigation, tick changes, and submission and validation results without moving +focus, and after a submission is accepted, focus moves to the read-only +summary's status text. + +## Known gaps + +- The tick boxes, radio marks, and input edges use the theme's existing + surface-300/700 border colors, which give roughly 1.3 to 1.4:1 contrast, + with no local override. The fix belongs in the theme and not in this + component. +- The two "Send" buttons and the two composer send buttons are unstyled + PrimeVue defaults. They follow the theme's own primary button color and not + `--wippy-form-accent`, so retinting `--wippy-form-accent` alone leaves them + on the old color while rows, the counter, key badges, and the focus ring + follow the new one. +- The Notes and Other text boxes use the theme's own `.p-textarea` colors, and + there are no `--wippy-form-input-bg` or `--wippy-form-input-border` tokens. + +## Diagnostics + +`<wippy-form>` sets a `card-state` attribute on itself. Use it for styling, or +to wait for a state in an end-to-end test. + +| `card-state` | Meaning | +| --- | --- | +| `loading` | Before the artifact's first `GET` resolves. `<wippy-loading>` shows instead of the card. | +| `active` | Answerable. A question, the review step, or briefly, the submitting state. | +| `review` | The review step of a several-question form, before "Send answers". | +| `answered` | The read-only summary of an accepted submission. | +| `unsupported` | An unrecognized `form-version` (from the prop or the loaded state), or a Web Host without the `artifactState` export. It takes priority over every other value, and the card is never interactive or submittable. | + +A missing or failed component bundle never reaches any `card-state` above. The +`wippy-form` script never registers, or registration times out, and the Host's +own component loader shows "This part of the page could not load. Reload to +try again." in its place. The cause goes only to the browser console, as +"Component tag script failed to load" for a script error or "Component tag +failed to load in time" for a registration timeout. Each is logged once per +failed tag and not once per card that tried to mount it. Reload the page to +recover. + +## See also + +- [Session Forms (framework)](../../framework/session-forms.md): the + `ask_user` and `read_form` tools, the trait, and how an answer is admitted + into the conversation +- [Chat Web Components](./chat-web-components.md): other host-provided, + auto-registered elements delivered the same way +- [Proxy API](./proxy-api.md): the rest of `@wippy-fe/proxy` and + `getWippyApi()` +- [Web Component Recipe](./web-component.md): building your own + `view.component`, for contrast with these host-provided ones From 49d439ebe130fc88e8d95c1490910226909d7893 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 1 Oct 2026 19:23:39 +0200 Subject: [PATCH 12/16] docs(session-forms): use isArtifactStateError, since instanceof fails across bundles The Web Host removed the Symbol.hasInstance override from ArtifactStateError. The frontend page now says to use isArtifactStateError(error), also $W.isArtifactStateError in an iframe page, because each proxy bundle carries its own copy of the class. It also notes that malformed 422 entries are left out of errors and formErrors, that a registration timeout is logged once per card while a script error is logged once per tag, and the submit example reads form_version from the loaded state. --- en/frontend/micro-frontends/session-forms.md | 24 ++++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index cc53de57..0c79af38 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -257,7 +257,7 @@ const client = (await $W.artifactState())('artifact-uuid') const state = await client.get() const result = await client.submit({ - form_version: 1, + form_version: state.form_version, request_id: crypto.randomUUID(), expected_content_version: state.content_version, answers: { color: 'blue' }, @@ -271,7 +271,8 @@ const result = await client.submit({ synchronously. - Every failure, whether an HTTP status or a network error, rejects with a typed `ArtifactStateError` (`status`, `code`, and, for a 422, `errors` keyed - by field id plus `formErrors`). + by field id plus `formErrors`). An entry in a 422 body that lacks a string + `code` or `message` is left out of `errors` and `formErrors`. ```typescript try { @@ -285,13 +286,12 @@ catch (error) { } ``` -Prefer `isArtifactStateError(error)` over `error instanceof -ArtifactStateError`. It is `$W.isArtifactStateError` in an iframe, and a named -export of `@wippy-fe/proxy` in a web component. Each proxy entry point and the -published `@wippy-fe/proxy` package bundles its own copy of the class, and -`isArtifactStateError` checks a brand that is the same in every copy. The class -overrides `Symbol.hasInstance` to run the same check, so `instanceof` also -matches an error that another copy threw. +Use `isArtifactStateError(error)` and not `error instanceof +ArtifactStateError`. It is `$W.isArtifactStateError` in an iframe page, and a +named export of `@wippy-fe/proxy` in a web component. Each proxy bundle carries +its own copy of the class, so `instanceof` can fail for an error that another +bundle threw, while `isArtifactStateError` checks a brand that is the same in +every copy. ### `artifactState` and the deprecated `instance.form` @@ -355,9 +355,9 @@ A missing or failed component bundle never reaches any `card-state` above. The own component loader shows "This part of the page could not load. Reload to try again." in its place. The cause goes only to the browser console, as "Component tag script failed to load" for a script error or "Component tag -failed to load in time" for a registration timeout. Each is logged once per -failed tag and not once per card that tried to mount it. Reload the page to -recover. +failed to load in time" for a registration timeout. A script error is logged +once per failed tag, and a registration timeout is logged once for each card +that tried to mount the tag. Reload the page to recover. ## See also From 39e87ee7cdecd79a36abd153aaa0b592fe3190eb Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 1 Oct 2026 20:10:04 +0200 Subject: [PATCH 13/16] docs: drop removed density prop and answer-submitted event from session forms The wippy-form component no longer has a density prop or host attribute and dispatches only the shared base events. List those, and point to card-state for reacting to a submission. --- en/frontend/micro-frontends/session-forms.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index 0c79af38..387f274b 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -25,7 +25,6 @@ For a version 1 definition the component renders a question card. | `form-version` | `number` | `1` | Definition schema version. A value other than `1`, whether it comes from this prop or from the loaded state's own `form_version`, shows a compatibility notice and no submit control. | | `definition` | `object` | `null` | The immutable form definition: `title`, optional `description`, optional `submit_label`, optional `answered_message` (never displayed), and `fields`. | | `state` | `string` | `"active"` | Package-tag lifecycle: `"active"` (answerable) or `"idle"` (already answered, read-only). Changing it reloads canonical state from the Host. | -| `density` | `string` | `"compact"` | `"compact"` or `"comfortable"` sizing. Read purely through a `:host([density="comfortable"])` CSS selector. | The component owns its own data loading, submission, and offline detection. A host only needs to mount the tag with these attributes. @@ -74,11 +73,18 @@ intercept typing in the surrounding chat composer. ### Events +The component adds no events of its own. These come from the shared web +component base, bubble, and cross the shadow boundary. + | Event | Payload | When | | --- | --- | --- | -| `answer-submitted` | `{ requestId, answerMessageId, late }` | After a submission is durably accepted, including an exact replay | -| `error` | `{ message, error }` | An unrecoverable component-level error | -| `invalid` | `{ message }` | Invalid props/config | +| `load` | none | The component finished mounting | +| `unload` | none | The element was removed from the page | +| `error` | `{ message, error }` | Mounting failed | +| `invalid` | `{ message }` | A prop failed validation | + +To react to a submission, watch the `card-state` attribute for `answered` (see +[Diagnostics](#diagnostics)). ## `<wippy-form-answers>`: the answer carrier @@ -112,7 +118,7 @@ by the Session module at `/wippy-session-forms` (`wippy-form`) and `/wippy-session-form-answers` (`wippy-form-answers`). The Web Host auto-loads every `auto_register: true` component at boot and allows its tag, plus its declared prop attribute names, through the chat message sanitizer. The names -are `definition`, `form-version`, `state` and `density` for `wippy-form`, and +are `definition`, `form-version` and `state` for `wippy-form`, and `record` for `wippy-form-answers`. `record` is declared as a `wippy.props` entry so that the sanitizer's allowed-attribute list includes it. Without that declaration the attribute is stripped even when the tag itself is allowed @@ -305,7 +311,7 @@ deprecated shim. ## Styling API `<wippy-form>` exposes `--wippy-form-*` custom properties, `::part()` -selectors and the host attributes `density`, `card-state` and `collapsed`. The +selectors and the host attributes `card-state` and `collapsed`. The full token, part, and host-attribute tables, plus a restyle example, are in the package's own README (`frontend/wippy-form/README.md` in the `wippy/session` source). `<wippy-form-answers>` exposes no styling API because it renders From 8039450fd6573928c4ef56c846e4ee3e467f98f9 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 15 Oct 2026 14:21:59 +0200 Subject: [PATCH 14/16] docs(session-forms): require Web Host 1.0.64 and @wippy-fe 0.0.64 Session Forms ship in Web Host 1.0.64; releases 1.0.61 to 1.0.63 do not export artifactState. --- en/frontend/micro-frontends/session-forms.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index 387f274b..0e065d03 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -129,8 +129,8 @@ through. `<wippy-form>` submits through `artifactState`, a typed client that the Web Host exports from every proxy realm (`$W.artifactState()` in an iframe, or the named `artifactState` export from `@wippy-fe/proxy` in a host-mounted web -component). Web Host 1.0.61 or later exports it, and no earlier release does. -The matching npm release is `@wippy-fe/*` 0.0.61. +component). Web Host 1.0.64 or later exports it, and no earlier release does. +The matching npm release is `@wippy-fe/*` 0.0.64. The component checks these conditions in order, and the first match decides what the card shows. @@ -138,7 +138,7 @@ what the card shows. | Condition | What the card shows | | --- | --- | | `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." The card reflects `card-state="unsupported"`. | -| The Host has no `artifactState` export (a Web Host before 1.0.61) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. Every option is unselected, because the saved answer cannot be read without the artifact-state API. The user's one-line answer message and the agent's reply stay readable in the chat, and the hidden answer record never appears. | +| The Host has no `artifactState` export (a Web Host before 1.0.64) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. Every option is unselected, because the saved answer cannot be read without the artifact-state API. The user's one-line answer message and the agent's reply stay readable in the chat, and the hidden answer record never appears. | | The Host exports `artifactState`, but the element has no `data-wippy-artifact-id` attribute (the Host sets it on the artifact elements it mounts) | The questions rendered read-only, with "This form cannot be submitted here." | The older `instance.form` adapter that `artifactState` replaces is described From e9d9cb8789167901cc158616fb6fb380fdd6ffa8 Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Mon, 19 Oct 2026 13:03:38 +0200 Subject: [PATCH 15/16] docs(session): fix Session Forms versions, upgrade notes and artifactState snippets --- en/framework/session-forms.md | 29 ++++++++++++++++++-- en/frontend/micro-frontends/session-forms.md | 28 +++++++++++++++---- 2 files changed, 49 insertions(+), 8 deletions(-) diff --git a/en/framework/session-forms.md b/en/framework/session-forms.md index da9328f7..13dd5cf6 100644 --- a/en/framework/session-forms.md +++ b/en/framework/session-forms.md @@ -42,9 +42,8 @@ Add `wippy.session.forms:ask_user` to an agent's `traits`: - id: wippy.session.forms:ask_user ``` -The trait needs a `wippy/session` release that ships Session Forms. With an -older release, an agent that references the trait fails to resolve at lint -time. +The trait ships in `wippy/session` 0.7.0, so the app needs that version or +newer. The trait contributes two tools and a block of prompt text. The prompt tells the model the following. @@ -248,6 +247,30 @@ JSON-escaped data inside the record, and the server escapes `'`, `<`, `>`, and add markup. The checks that the state endpoint applies to every request are listed in [The artifact-state HTTP API](../frontend/micro-frontends/session-forms.md#the-artifact-state-http-api). +## Upgrading + +`wippy/session` 0.7.0 adds Session Forms and has these breaking changes. + +- **New `ui_server` requirement.** The module serves the form components from + an HTTP server. The requirement `wippy.session.forms.ui:ui_server` defaults + to `app:gateway`. If your app's HTTP server has another name, set the + requirement to that name. If you do not, the static routes of the form + component break. +- **Minimum Web Host.** The question card needs Wippy Web Host 1.0.65 or + newer. See + [Host requirement](../frontend/micro-frontends/session-forms.md#host-requirement). +- **Foreign artifacts return 404.** Reading an artifact that belongs to + another user now returns 404, as for a missing artifact. It used to return + 403. +- **Stop settles the session idle.** When an enforced Stop ends a turn, the + session is stored idle and `can_send` is true. +- **A stored `running` status reads as idle.** If no session process is + alive, a session stored as `running` is reported as idle. +- **Dates are stored and returned in UTC.** +- **`reader:list_pending_inputs` is removed.** The `reader` library no longer + has this method. Code that calls it must use another way to read pending + inputs. + ## Disabling and rolling back To stop new forms, remove `wippy.session.forms:ask_user` from an agent's diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index 0e065d03..ca7c1269 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -129,8 +129,10 @@ through. `<wippy-form>` submits through `artifactState`, a typed client that the Web Host exports from every proxy realm (`$W.artifactState()` in an iframe, or the named `artifactState` export from `@wippy-fe/proxy` in a host-mounted web -component). Web Host 1.0.64 or later exports it, and no earlier release does. -The matching npm release is `@wippy-fe/*` 0.0.64. +component). Web Host 1.0.65 or later exports it, and no earlier release does. +The matching npm release is `@wippy-fe/*` 0.0.65. The `wippy/session` module +release that ships the forms is 0.7.0. +<!-- Confirm these version numbers when the Web Host tag is cut. This page merges after that tag. --> The component checks these conditions in order, and the first match decides what the card shows. @@ -138,7 +140,7 @@ what the card shows. | Condition | What the card shows | | --- | --- | | `form-version` prop or loaded state's `form_version` is not `1` | "This form needs a newer version of the app." The card reflects `card-state="unsupported"`. | -| The Host has no `artifactState` export (a Web Host before 1.0.64) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. Every option is unselected, because the saved answer cannot be read without the artifact-state API. The user's one-line answer message and the agent's reply stay readable in the chat, and the hidden answer record never appears. | +| The Host has no `artifactState` export (a Web Host before 1.0.65) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. Every option is unselected, because the saved answer cannot be read without the artifact-state API. The user's one-line answer message and the agent's reply stay readable in the chat, and the hidden answer record never appears. | | The Host exports `artifactState`, but the element has no `data-wippy-artifact-id` attribute (the Host sets it on the artifact elements it mounts) | The questions rendered read-only, with "This form cannot be submitted here." | The older `instance.form` adapter that `artifactState` replaces is described @@ -257,10 +259,26 @@ Submissions are not rate-limited server-side, so the API never returns `429`. ## The `artifactState` proxy client +In a host-mounted web component, `artifactState` is the factory itself: + ```typescript -const client = (await $W.artifactState())('artifact-uuid') -// or, inside a web component: import { artifactState } from '@wippy-fe/proxy' +import { artifactState } from '@wippy-fe/proxy' + +const client = artifactState(artifactId) +``` +In an iframe, `window.$W.artifactState()` (or `getWippyApi()`) returns a +promise for the factory: + +```typescript +const factory = await window.$W.artifactState() +const client = factory(artifactId) +// or: const { artifactState } = await window.getWippyApi() +``` + +Both forms give the same client: + +```typescript const state = await client.get() const result = await client.submit({ form_version: state.form_version, From 57cf60f9fdd6362d0c4a7ef9d8658ce981a59dfb Mon Sep 17 00:00:00 2001 From: Andrei Kirkouski <andrew@spiralscout.com> Date: Thu, 5 Nov 2026 20:10:49 +0100 Subject: [PATCH 16/16] docs(session-forms): drop Session version, add Stop cancel and form_version notes --- en/framework/session-forms.md | 10 ++++++---- en/frontend/micro-frontends/session-forms.md | 11 +++++++---- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/en/framework/session-forms.md b/en/framework/session-forms.md index 13dd5cf6..55f5f34c 100644 --- a/en/framework/session-forms.md +++ b/en/framework/session-forms.md @@ -42,8 +42,9 @@ Add `wippy.session.forms:ask_user` to an agent's `traits`: - id: wippy.session.forms:ask_user ``` -The trait ships in `wippy/session` 0.7.0, so the app needs that version or -newer. +The trait ships with Session Forms, so the app needs a `wippy/session` release +that includes them. +<!-- TODO: name the Session version here when the release PR exists. --> The trait contributes two tools and a block of prompt text. The prompt tells the model the following. @@ -230,7 +231,7 @@ setting. | --- | --- | | The session is idle | The answer is admitted at once, and a new turn starts | | A turn is running | The answer is pending, and `read_form` reports `answer_pending`. It is admitted when the turn ends, in acceptance order together with any typed input the session held during the turn | -| The user pressed Stop | The answer is admitted into the history and no turn starts. The same happens when the session plugin has to cancel or terminate a session that does not stop in time | +| The user pressed Stop | Stop cancels the turn's in-flight model and tool calls. The answer is admitted into the history and no turn starts. The same happens when the session plugin has to cancel or terminate a session that does not stop in time | | The session is finishing, or its process is not running | The answer stays pending until the process starts again. The session plugin starts stopped sessions that hold pending answers | Once admitted, the answer's message is dated at the moment of admission, so @@ -249,7 +250,8 @@ listed in [The artifact-state HTTP API](../frontend/micro-frontends/session-form ## Upgrading -`wippy/session` 0.7.0 adds Session Forms and has these breaking changes. +The `wippy/session` release that adds Session Forms has these breaking changes. +<!-- TODO: name the Session version here when the release PR exists. --> - **New `ui_server` requirement.** The module serves the form components from an HTTP server. The requirement `wippy.session.forms.ui:ui_server` defaults diff --git a/en/frontend/micro-frontends/session-forms.md b/en/frontend/micro-frontends/session-forms.md index ca7c1269..19c97795 100644 --- a/en/frontend/micro-frontends/session-forms.md +++ b/en/frontend/micro-frontends/session-forms.md @@ -131,8 +131,9 @@ Host exports from every proxy realm (`$W.artifactState()` in an iframe, or the named `artifactState` export from `@wippy-fe/proxy` in a host-mounted web component). Web Host 1.0.65 or later exports it, and no earlier release does. The matching npm release is `@wippy-fe/*` 0.0.65. The `wippy/session` module -release that ships the forms is 0.7.0. -<!-- Confirm these version numbers when the Web Host tag is cut. This page merges after that tag. --> +release that ships the forms is the one that adds Session Forms. +<!-- TODO: name the Session version here when the release PR exists. --> +<!-- Confirm the Web Host and npm version numbers when the Web Host tag is cut. This page merges after that tag. --> The component checks these conditions in order, and the first match decides what the card shows. @@ -143,8 +144,8 @@ what the card shows. | The Host has no `artifactState` export (a Web Host before 1.0.65) | The questions with their options disabled, no submit control, and `card-state="unsupported"`. The notice reads "This form needs a newer Web Host. If you already answered it, your answer is in the chat." When the Host passes `state="idle"` (the form was answered), it reads "This form was answered. Your answer is in the chat." instead. Every option is unselected, because the saved answer cannot be read without the artifact-state API. The user's one-line answer message and the agent's reply stay readable in the chat, and the hidden answer record never appears. | | The Host exports `artifactState`, but the element has no `data-wippy-artifact-id` attribute (the Host sets it on the artifact elements it mounts) | The questions rendered read-only, with "This form cannot be submitted here." | -The older `instance.form` adapter that `artifactState` replaces is described -under [`artifactState` and the deprecated +The older `instance.form` adapter that `artifactState` replaces always sends +`form_version: 1`, so forms use `artifactState`. It is described under [`artifactState` and the deprecated `instance.form`](#artifactstate-and-the-deprecated-instanceform). ## The artifact-state HTTP API @@ -326,6 +327,8 @@ legacy `{ success: false, errors }` shape. Every other failure (401, 404, 409, code should call `instance.artifactState(artifactId)` directly and not this deprecated shim. +The deprecated `instance.form.submit()` always sends `form_version: 1`, so forms use `artifactState(artifactId)`. + ## Styling API `<wippy-form>` exposes `--wippy-form-*` custom properties, `::part()`