diff --git a/en/framework/session-forms.md b/en/framework/session-forms.md new file mode 100644 index 00000000..55f5f34c --- /dev/null +++ b/en/framework/session-forms.md @@ -0,0 +1,309 @@ +--- +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. 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. + +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. + +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 + +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 ships with Session Forms, so the app needs a `wippy/session` release +that includes them. + + +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 + `` 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 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 that describes what to fix, nothing is stored, 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 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. 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 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 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. +``` + +### 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` 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 +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. 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. + +<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, which is the `answered_message` the agent +supplied when it called `ask_user` (or the `Answered “<title>”.` fallback). +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 + +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`: + +| Answer shape | When | +| --- | --- | +| `{"value": "courier", "label": "Courier"}` | A chosen option | +| `{"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) | + +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. + +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. The flag 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, 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. The result depends on the form's state: + +| `status` | Result | +| --- | --- | +| `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 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): +- 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 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. + +## How answers are admitted + +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. + +| 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 | 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 +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 + +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). + +## Upgrading + +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 + 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 +`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 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 + +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. 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 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 + +- [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 new file mode 100644 index 00000000..19c97795 --- /dev/null +++ b/en/frontend/micro-frontends/session-forms.md @@ -0,0 +1,399 @@ +--- +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. | + +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 + +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 | +| --- | --- | --- | +| `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 + +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` 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 +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.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 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. + +| 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.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 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 + +`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 + +In a host-mounted web component, `artifactState` is the factory itself: + +```typescript +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, + 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`). An entry in a 422 body that lacks a string + `code` or `message` is left out of `errors` and `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 +} +``` + +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` + +`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. + +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()` +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 +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. 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 + +- [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 diff --git a/en/manifest.json b/en/manifest.json index 1e240739..c789c378 100644 --- a/en/manifest.json +++ b/en/manifest.json @@ -161,7 +161,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"} ] }, { @@ -207,6 +208,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": "Attention Context", "path": "frontend/micro-frontends/attention-context"}, {"title": "Surface Portability", "path": "frontend/micro-frontends/surface-portability"},