13A.4 AI UX III: Failure States, Edge Cases and Inclusive Design
Every AI feature you will ever ship fails — constantly, in ways a CRUD app never does. The model hallucinates a policy that doesn't exist. The provider returns a perfectly valid HTTP 200 containing a refusal, a safety block, or an answer cut off mid-sentence. The stream dies after forty tokens. Retrieval finds nothing relevant and the model still produces a fluent, confident paragraph about it. A user on a flaky mobile connection watches a spinner while an agent quietly retries a tool call. Meanwhile a screen-reader user hears nothing at all, because the "typing" animation announces every token or, worse, announces nothing.
This lesson is about what the user experiences when any of that happens. It is the third lesson in the AI-UX sequence: 13A.2 owned how streamed output feels and renders, 13A.3 owned trust, disclosure, feedback and human-in-the-loop patterns, and this lesson owns failure states, edge cases and inclusive design. The through-line: an AI product is judged not by its happy path but by its failure paths, because failures are where probabilistic systems differ most from deterministic ones — and where users decide whether to trust you again.
What you'll learn
- A taxonomy of AI failure states as the user experiences them: confidently wrong, partially right, refusals, safety blocks, empty and irrelevant results, ambiguity, timeouts, rate limits, outages, mid-task tool failures, stale sources, truncated output, injection-affected output, cost caps, off-topic requests and long-conversation degradation
- How to turn an internal error, finish reason or policy signal into a typed, user-facing message — and why "the model said no" and "the API returned 500" must never reach the screen raw
- Copy craft for failure states: honest, specific, blameless messages; the bad-versus-good table; avoiding false apologies, false certainty and jargon
- Recovery paths: retry, rephrase, edit, switch mode, hand off to a human, save the draft — and how to preserve the user's work when a stream dies mid-answer
- Graceful degradation: fallbacks users can feel — cheaper model, cached answer, retrieval-only results, a form instead of a chat, a queue for later — and when you must tell the user a fallback happened
- Clarifying questions and ambiguity: when to ask versus guess, and the UI patterns (chips, inline forms, sensible defaults) that avoid interrogation loops
- Empty and cold-start states: suggested prompts, templates, capability tours — and what to do when retrieval finds nothing
- Rendering model output safely: Markdown/HTML sanitisation, link and image exfiltration channels, code blocks, tables, citations and streaming-partial markup
- Accessibility for AI interfaces: keyboard operation, focus management,
aria-livestrategy for streamed text, reduced motion, contrast and target sizes, captions for voice, and plain language for cognitive load — verified against WCAG 2.2 and the WAI-ARIA Authoring Practices Guide - Internationalisation and localisation: the multilingual token tax, right-to-left layouts, locale-aware formats, language detection and reply-language policy
- Real devices and networks: mobile, low bandwidth, flaky connections, offline and resume, battery and background tabs, large-file uploads
- UX research methods for AI features: think-aloud sessions, Wizard-of-Oz, diary studies, log review, red-team-style usability probes, and the metrics hand-off to 13A.6
What you don't need
- API keys. Every sample in this lesson is pure Python — the
ai_productpackage modules run on fixtures with the standard library only. Provider error shapes are reused from lesson 03.8 and lesson 03.3, which you can read without calling anything. - A design background. Wireframes here are ASCII and Mermaid, not a design system. The accessibility rules are stated as checkable requirements, not Figma craft.
- JavaScript. Browser behaviour is taught through the event contract from 13A.2 and
curl-style clients; the few lines of HTML/JS awareness notes are labelled as such.
Setup
This lesson adds four files to the ai_product package that 13A.1 started and 13A.2 and 13A.3 extended. It needs no third-party packages — everything is standard library:
ai_product/
failure_ui.py # this lesson: signal -> typed user-facing message
copy_catalog.py # this lesson: copy catalogue with i18n keys
markdown_safety.py # this lesson: stdlib rendering-safety sketch
a11y_lint.py # this lesson: accessibility checklist linter for UI specsCopy each file into your capstone or practice project as you reach its section; each one runs standalone. If you are working inside the module's shared project folder from earlier lessons, drop them next to events.py and smoother.py. No .env file is needed — there are no API calls in this lesson.
What you must be able to do after this lesson#
- Classify an AI failure state as the user sees it
- Map an error, finish reason or policy signal to a typed user-facing message with retryable set correctly
- Write honest, specific failure copy without false apology
- Offer recovery paths and keep the user's work when a stream dies
- Render model output safely and block Markdown image exfiltration
- Make an AI interface keyboard and screen-reader accessible
Why this matters for an AI engineer#
You'll hear colleagues and users say things like "the chatbot just said something weird" or "it gave up". After this lesson you'll be able to map every one of those vague complaints to a specific failure class, a specific message and a specific recovery path.
| You'll hear... | You'll understand it after... |
|---|---|
| "The model gave a 200 but the answer was a refusal." | Part 2: the taxonomy |
| "It just said 'something went wrong'." | Part 3: writing the message |
| "The stream broke halfway — do we retry?" | Part 4: recovery paths |
| "Why did the cheap model's answers feel off?" | Part 5: graceful degradation |
| "The bot kept asking me questions instead of answering." | Part 6: clarifying questions and empty states |
| "A user pasted a link that stole their session cookie." | Part 7: rendering safely |
| "The streamed answer is unusable with a screen reader." | Part 8: accessibility |
| "It costs several times more per answer in Tamil than in English." | Part 9: internationalisation |
| "It works on my Wi-Fi but not on the train." | Part 10: devices and networks |
| "How do we know the failure UX actually works?" | Part 11: UX research and testing |
Part 1: Failure is a designed state, not an exception#
1.1 The three vocabularies of AI failure#
A deterministic web app has one failure vocabulary: exceptions and HTTP status codes. An LLM feature has three, and confusing them is the root cause of most bad failure UX:
- Transport failures — the network or the provider's infrastructure failed. DNS, TLS, timeouts, connection resets, HTTP 429/500/529. These are owned by lesson 03.8:
Kindvalues likeTIMEOUT,RATE_LIMITED,OVERLOADED,CONNECTION,QUOTA,AUTH,BAD_REQUEST,CONTEXT_TOO_LONG, classified byllm_errors.pyand retried byreliable_call(). - Outcome failures — the HTTP call succeeded (usually a 200) but the content is unusable. Refusals, safety blocks, truncated output, empty output, "the context window filled mid-answer", errors inside a 200. Lesson 03.8, Part 10 turned these into
check_response(), which returns a typedOutcomewith aStatusfrom a closed enum:OK,TOOL_CALL,TRUNCATED,CONTEXT_FULL,REFUSED,BLOCKED,EMPTY,PAUSED,FAILED,INCOMPLETE. - Policy and product failures — nothing crashed, but the product decided the request shouldn't proceed or can't be served well: a cost cap was hit, a tenant's quota is exhausted, an injection attempt was suspected, the feature is in degraded mode, the request is off-topic, the conversation has degraded past a quality floor. These signals come from your code — budgets, guardrails, routers, evals — not from any provider.
The design consequence is the spine of this lesson: every user-facing failure state is a mapping from one of these three vocabularies to a message, a severity and a set of recovery actions. Your UI should never see a raw exception, a stop_reason, a finish_reason or an HTTP status — it should see a UserMessage your server constructed deliberately.
1.2 Why failure UX is different for AI#
Three properties of LLM systems make failure states harder than in a normal app:
- Failures are fluent. A wrong answer arrives in the same confident prose as a right one (02.10 calls this the core difficulty: failures are silent and fluent). The user can't tell "the model didn't know" from "the model made it up" without your help — citations, "show your work" (09.10, 2.6), confidence signals (13A.3) and honest abstention (07.4) are the tools.
- Failures are probabilistic, not binary. "Partially right" is a first-class outcome: three of five extracted invoice fields correct, an answer that's right but incomplete, a summary that missed the caveat. Deterministic systems rarely produce "sort of worked".
- The failure surface is unbounded. Lesson 11C.3's failure catalogue lists a dozen dependency failure modes, lesson 03.8's catalogue lists what a 200 can carry per provider, lesson 08A.14's taxonomy lists twelve agent failure families, and lesson 04.7's catalogue lists how long conversations decay. You cannot enumerate every failure; you can enumerate the families and design a message and a recovery for each family.
1.3 The failure gallery#
Before designing, learn to recognise. This table shows what each failure family looks like to the user when nobody designed for it — the "naive rendering" column is what ships when you forward provider events straight to the UI.
| Failure family | What the user sees (naive) | What it should look like (designed) |
|---|---|---|
| Confidently wrong | Fluent, confident, wrong answer; no signal anything is off | Citations to check, "show your work", calibrated-confidence hints (13A.3), feedback affordance |
| Partially right | Answer that stops mid-list, or misses the asked-for field | "Here's what I found — 3 of 5 fields" with the missing ones named; continue/edit actions |
| Refusal (model) | "I can't help with that" or a canned decline; sometimes nothing at all | Honest "I can't help with this one" + what would work + alternative path (rephrase, human) |
| Safety block | Empty response, finish_reason: content_filter rendered as blank space |
"This request was blocked by a safety filter" + rephrase suggestion; never blame the user |
| Empty / irrelevant result | "I don't have enough information to answer" boilerplate, or worse: a fluent non-answer | The 07.4 status (abstained, partial, needs_clarification) rendered as a specific, actionable message |
| Ambiguity | The model guesses silently and answers the wrong question | A clarifying question with chips/defaults — or a stated assumption ("I assumed you meant the March invoice") |
| Timeout | Infinite spinner, then a browser timeout page | Progress up to the deadline, then "still working / taking longer than usual" + keep-waiting vs stop choices |
| Rate limit (429) | "Error 429" or a retry storm that hammers the API | "You're doing that a lot — try again in ~30 s" with a countdown and queued-retry option |
| Provider outage | 503 page, or silent hang | "The AI service is having trouble" + degraded mode offer (cached answer, form, human) |
| Tool failure mid-task | Agent claims success it didn't achieve (false completion, 08A.14) | Step-level status that shows which step failed + what was completed + resume/retry from that step |
| Stale / conflicting sources | Two sources disagree; model picks one silently | "Sources disagree" callout showing both, dated; ask user which to trust |
| Truncated output | Answer ends mid-word or mid-JSON | Detected via finish_reason/stop_reason/incomplete — "this answer was cut off" + continue/regenerate |
| Injection-affected output | Model obeys hidden instructions; weird links, off-task text, exfil attempts | Sanitised rendering (Part 7), provenance labels, anomaly signals from 12.2 detection layers |
| Cost cap / quota hit | Feature silently stops working, or a raw billing error | "You've reached your usage limit" + reset time + upgrade path or degraded mode |
| Off-topic request | Model answers anyway, or refuses rudely | Scope statement + redirect suggestions ("I can help with X, Y, Z") |
| Long-conversation degradation | "It got weird after turn 30" — drift, compounding errors, forgotten instructions | Context-health signals (04.7), graceful summarisation notice, "start a new chat" suggestion |
1.4 What this means for you as an engineer#
Failure UX is not a "polish" layer added at the end — it is an interface contract. The same way 13A.2 made you design the event protocol before the pixels, this lesson makes you design the failure protocol before the copy: which signals exist, which produce which UserMessage, which are retryable, and what the client must render for each. Get that contract right and the copy, the wireframes and the accessibility all fall out of it. Get it wrong and every downstream fix is a patch on a leak.
flowchart LR
subgraph signals ["Three signal vocabularies"]
T["Transport Kind<br/>(03.8 llm_errors)"]
O["Outcome Status<br/>(check_response)"]
P["Policy signal<br/>(your code)"]
end
M["failure_ui.py<br/>from_outcome / from_transport / from_policy"]
U["UserMessage<br/>severity + copy_key + actions + retryable"]
C["copy_catalog.resolve<br/>(locale -> en -> key)"]
R["Client renders<br/>error card / banner / inline notice"]
T --> M
O --> M
P --> M
M --> U
U --> C
C --> RPart 2: The taxonomy of AI failure states#
The taxonomy below is organised by what the user experiences, not by what broke. Each family lists the internal signals that produce it (so your mapper can recognise it), what a naive UI shows, and the design obligations. This is the checklist you'll implement in failure_ui.py in Part 3.
2.1 Quality failures: the answer arrived but isn't good enough#
These are the hardest states to design because nothing raised an exception. The response is a fluent 200.
Confidently wrong (hallucination). The model asserts something false with full confidence — a policy that doesn't exist, a citation to a paper that was never written, a "fact" about your product invented on the spot. 02.10 is the deep dive on why this happens; 02.10, 14.4 covers mitigation. User-facing design: you cannot detect "wrong" reliably in real time (that's what Module 10A evals are for), so the design burden shifts to verifiability: citations that resolve (07.5), "show your work" surfaces (09.10, 2.6), editable outputs, and feedback affordances that turn a wrong answer into labelled eval data (13A.3).
Partially right. Structured output where three of five fields extracted correctly; an answer covering two of three asked questions; a summary that dropped the caveat. Signals: your own semantic validators (03.4, Part 6), coverage checks, status: "partial" from your pipeline. Design: name what's missing explicitly — "Found 3 of 5 line items; the totals row didn't parse" — and offer continue/edit/retry-scope actions. Never present partial as complete.
Refusals. Two distinct kinds, and conflating them is a classic bug:
- Model refusals — the model declines in content: Anthropic
stop_reason: "refusal"(withstop_details.categorylikecyber,bio,general_harms), OpenAI Responses refusal content parts, Chat Completionsmessage.refusal, or — the sneaky one — a plain-text "I can't help with that" under a normalend_turn/STOP. 03.8, 10.1 documents every shape, including the warning that "a refusal in plain words is invisible to all of these checks". - Policy refusals — your guardrails, classifiers or scope rules decline: a blocked topic, a tenant not allowed this feature, a request outside the product's remit.
Design: a refusal is not an error — it's an answer. Say what you can't do, say what you can do, offer the alternative (rephrase, different mode, human). For policy refusals you may additionally need the compliance-approved wording (12.9).
Safety blocks. The provider's safety systems stopped the prompt or the answer: Gemini prompt_feedback.block_reason (SAFETY, BLOCKLIST, PROHIBITED_CONTENT, IMAGE_SAFETY, OTHER...), Gemini finish reasons SAFETY/PROHIBITED_CONTENT/BLOCKLIST/SPII/RECITATION/LANGUAGE/IMAGE_*, OpenAI incomplete reason content_filter / Chat Completions finish_reason: "content_filter" (OpenRouter preserves the original in native_finish_reason), Anthropic has no equivalent stop reason (its safety surface is refusals plus the fallbacks beta's recommended_model hint). Design: "This request was blocked by a safety filter" is honest; blaming the user ("your request was inappropriate") is not always true — the block may be a false positive on legitimate content (medical FAQ, security research, a novel). Offer rephrase and escalation; log the block reason for your safety review (12.5, 12.8).
Empty and irrelevant results. Status.EMPTY from check_response(): a 200 with no text — often a reasoning model that spent its whole max_tokens budget thinking (reasoning tokens count as output, 02.8), or Gemini's "no candidates". Design: distinguish "the model had nothing to say" from "retrieval found nothing" — the latter is 07.4's abstention territory, where status: "abstained" means your pipeline decided the corpus can't answer. Empty output is a bug-shaped failure: retry once with a higher cap, then say so honestly.
Truncated output. Status.TRUNCATED: OpenAI status: "incomplete" + incomplete_details.reason: "max_output_tokens", Chat Completions finish_reason: "length", Anthropic stop_reason: "max_tokens", Gemini MAX_TOKENS, Interactions status: "incomplete". Two traps from 03.8, 10.1: truncation with no visible text means the budget went to reasoning (retry with more headroom), and length on a structured output means invalid JSON — 03.4, 6.3 covers the partial-JSON problem. Design: never render a truncated answer as if complete. "This answer was cut off at the length limit" + Continue (the 03.3, 7.5 continuation request) or Regenerate with a bigger cap.
Stale or conflicting sources. Retrieval returned passages that disagree, or passages older than the question requires ("what's the refund policy now" answered from last year's handbook). Signals: metadata dates in your hits (07.4, 2.1), contradiction detection in your pipeline, freshness fields. Design: show the disagreement — "Two sources disagree: handbook v3 (2025) says 30 days, v4 (2026) says 14" — with dates, and let the user pick. Silently picking one is how you get confidently wrong with citations.
Long-conversation degradation. After dozens of turns the "bot gets weird": instruction drift, compounding errors, forgotten constraints, rising cost. 04.7, 1.2 is the mechanism catalogue; 04.7 owns the engineering fixes (summarisation, state extraction, compaction). User-facing design: this is an edge case the user causes by using the product. The honest signals are subtle — degraded relevance, a summarisation marker ("Earlier messages were summarised"), or your own context-health metric crossing a threshold. Design the notice ("This conversation is getting long — answers may get less precise. Start a new chat?") and the graceful off-ramp, not a sudden failure.
2.2 Availability failures: the service didn't answer#
These come from transport and infrastructure, and 03.8 + 11C.3 own the engineering. Your job is the message.
Timeouts. Your deadline fired before the provider answered, or the provider's own timeout fired first. Distinguish read timeouts (silence mid-stream — 03.3, 8.1) from total timeouts, and distinguish "slow" from "dead": a 30-second thinking gap on a reasoning model is normal, a 30-second silence on a chat model is a problem. Design: keep-waiting vs stop, elapsed-time honesty ("taking longer than usual — 45 s so far"), and never an infinite spinner.
Rate limits (429). Two different 429s, per 03.8, 4.2: slow down (transient capacity — honour Retry-After, back off) versus out of money (quota/billing — retrying is pointless and burns budget). Design: "You're sending requests too quickly — try again in ~30 seconds" with an actual countdown beats "Error 429" every time. For the out-of-money kind, it's the quota-exceeded state below.
Provider outage / overload. 5xx clusters, Anthropic 529 OverloadedError (which is not an InternalServerError — 03.8, 3.3), OpenAI 503 server_is_overloaded, Gemini UNAVAILABLE, OpenRouter provider_unavailable/provider_overloaded error types inside a 200. 11C.3, 1.2 tracks these per-route. Design: the outage message is also your degraded-mode offer — "The AI service is having trouble. You can try again, or use the quick-search fallback." (Part 5.)
Quota and cost caps. Your tenant/user hit a spend cap, daily quota, or plan limit — and the provider-side variants (OpenAI spend limits, Anthropic workspace limits, OpenRouter credit exhaustion 402/payment_required — its budget 403s carry limit_source, limit_usd and resets_at in metadata, per 03.8, 3.5). Signals: your own budget counters (11B.1), QUOTA/PERMISSION Kinds from llm_errors.py, 403s with quota codes. Design: this is a product failure, not an error — "You've used your 500 free answers this month; resets Nov 1" with the upgrade path or the degraded mode. Cost caps are a feature (13A.6 owns the economics); the UX must make the cap feel like a plan, not a bug.
Mid-stream failures. The stream started, text arrived, then it died: provider error events (03.3, 7.2), a clean connection close with no terminal event ("nothing is raised by most helpers" — 03.3, 7.3), a client disconnect, your own proxy's idle timeout. 03.3, 7.5 owns the recovery decision (resume / restart-silently / restart-and-reset / continue); your UX owns what the user sees during and after: the partial answer preserved, a clear "connection lost — retrying" state, and the reset event rendered as a visible clear rather than silent duplication.
Tool failure mid-task. The agent was three steps in when a tool call failed: lookup_order returned "not found", a write tool got a 403, an MCP server timed out. The dangerous UX is 08A.14's false completion: the agent narrates success it didn't achieve. Design: step-level status (Part of 13A.2's progress contract) must show which step failed, what completed, and offer resume-from-step or hand-to-human. The trace ID from 08A.14, 6.4 goes in the message so support can find it.
2.3 Content-safety failures: the output itself is the problem#
Injection-affected output. The model obeyed instructions hidden in retrieved documents, tool output, or user content (12.2 is the full treatment — the kill chain, exfil channels, defences). User-facing design has two jobs: render safely (Part 7 — the Markdown image/link channels are how injected output steals data or phishes users) and signal honestly when detected — if your detection layers (12.2, Part 7) or sanitiser fired, the user sees a warning state ("This answer referenced an external link we couldn't verify — we've removed it"), not silent cleanup and not alarm.
Off-topic / out-of-scope requests. The user asks the support bot to write a poem, or the docs assistant to do their taxes. Signals: your router's scope classifier, an explicit off_topic policy verdict, or the model's own scope-refusal. Design: scope statements that redirect, not walls — "I can help with billing, orders and returns. For everything else, here's the support form." The 13A.1 feature brief's "non-goals" field is where this policy gets written down.
2.4 Interaction failures: the conversation itself breaks down#
Ambiguity requiring clarification. "Book it" — book what, for whom, when? The model either guesses (risky) or asks (annoying if it asks too much). Covered in depth in Part 6.
The user abandons mid-answer. They close the tab, hit Stop, or navigate away while a stream runs. Not a failure to them — but it is a failure to you: usage is billed-or-unknown (03.3, 7.6), side effects may have fired, and the conversation state must be consistent when they return. 03.3, 8.5 covers what Stop means; your UX covers what "resume this conversation" looks like.
What this means for you as an engineer. The taxonomy is a routing table, not a list to memorise: each family maps to (a) a detection signal your server computes, (b) a UserMessage variant with severity and actions, (c) a recovery path, and (d) a log/metric label. When a new failure appears in production — and one will — the question is never "what do we show?" in the abstract; it's "which family does this belong to, and does our designed state for that family cover it?"
Part 3: Writing the message — copy craft#
3.1 The anatomy of a failure message#
Every failure state renders the same five parts, and skipping any one is a design bug waiting for a user:
| Part | Question it answers | Example (rate limit) |
|---|---|---|
| What happened | What did the system do, in plain words? | "You're sending requests too quickly." |
| Why (when honest) | Is it my fault, the service's, or nobody's? | "The AI service asked us to slow down." |
| What you can do | Concrete next actions, in order of likelihood | "Wait ~30 s, or switch to quick search." |
| What we preserved | Your work isn't lost | "Your draft is saved." (when true) |
| Where to get help | A human or a reference, for the failures that need one | Trace ID + "contact support" |
3.2 Bad copy versus good copy#
The table below is the single most reusable artefact in this lesson. Every row is a real failure class; the "bad" column is what production UIs actually ship.
| Failure | Bad copy | Good copy | Why the good one wins |
|---|---|---|---|
| Rate limit | "Error 429: Too Many Requests" | "You're doing that a lot — try again in ~30 s." | Names the cause in user terms, gives a number they can wait out |
| Timeout | "Request timed out" | "The model is taking longer than usual — still working? [Keep waiting] [Stop]" | Distinguishes slow from dead; offers control |
| Provider outage | "500 Internal Server Error" | "The AI service is having trouble. You can try the quick-search fallback while we retry." | Offers the degraded path instead of a dead end |
| Safety block | "Your request violates our content policy" | "This request was blocked by a safety filter. Try rephrasing, or talk to a person if you think it's a mistake." | Doesn't assume guilt; acknowledges false positives exist |
| Model refusal | "I cannot fulfil this request" | "I can't help write that, but I can help you outline the topic, find sources, or draft something else." | A refusal is an answer, not an error — redirect, don't wall |
| Truncated answer | (answer just ends) | "This answer was cut off at the length limit. [Continue] [Regenerate]" | The user knows the ending is missing, not that they imagined it |
| Empty result | "No results found" | "I searched the handbook and found nothing on 'wifi password'. Try 'network' or 'guest access'." | Says what was searched and offers rephrasing — the 07.4 abstention contract rendered honestly |
| Quota hit | "Quota exceeded" | "You've used your 500 free answers this month — resets Nov 1. [See plans] [Use quick search]" | Frames the cap as a plan boundary, gives the reset date and a degraded path |
| Ambiguous request | (model guesses silently) | "Did you mean the March invoice or the April one? [March] [April] [Neither — let me explain]" | One question, tappable options, an escape hatch |
| Long conversation | (answers slowly degrade) | "This chat is getting long — answers may get less precise. [Start a new chat] [Keep going]" | Warns before the cliff; the user chooses |
| Injection-suspect link | (malicious link renders live) | "We removed a link we couldn't verify." | Tells the user something was cleaned without alarm or detail an attacker could probe |
| Confidently wrong | (fluent wrong answer) | (No message — instead: citations, "show your work", a feedback button) | You can't detect wrongness in real time; you make it checkable instead |
The patterns across every good row:
- Specific, not generic. "Try again in ~30 s" beats "something went wrong" because it tells the user what to expect. Google's PAIR guidebook chapter Errors + Graceful Failures makes the same point: error messages should help users diagnose and manage errors "from AI systems and context of use" — i.e., tell them what happened in their situation.
- No blame, no jargon, no theatre. "The AI service is busy" not "upstream provider returned 503". Not "We're sorry, an unexpected error occurred!!!" — over-apologising reads as either insincere or hiding something worse. Apple's generative-AI HIG points the same way (page read 12 November 2026): keep people in control, let them dismiss content they do not want and revert or retry transformations, and communicate where your app uses AI.
- Never false certainty. Don't say "don't worry, it'll work next time" for a failure you can't predict. Don't say "100% accurate" anywhere. Hedged honesty ("may", "usually") is a feature.
- Offer the way out before the diagnosis. Actions come first or alongside the explanation: [Retry] is more useful than a paragraph about retries.
- WCAG 3.3.1 and 3.3.3 are the formal version of this table. Error Identification (level A) requires an automatically detected error to be described in text and the item in error identified; Error Suggestion (AA) requires the correction to be suggested when it's known — unless doing so would jeopardise security or the content's purpose. Every good row above is a 3.3.1/3.3.3-compliant message; every bad row fails both.
3.3 failure_ui.py: the signal → message mapper#
This is the module's core code. It takes the three signal vocabularies from Part 1 and produces a typed UserMessage — severity, copy-catalogue key, ordered actions, retryability, degraded flag, trace ID. Your server calls it at the boundary where a failure becomes a UI event; the client renders whatever comes back without knowing what broke.
"""ai_product/failure_ui.py — map internal failure signals to typed user messages.
Lesson 13A.4. Stdlib only. The point: the UI never sees an exception, a
stop_reason or an HTTP status. It sees a UserMessage your server built.
Signal sources (all optional — pass whichever you have):
- 03.8 check_response().status -> one of the Status names below
- 03.8 llm_errors Kind names -> TIMEOUT, RATE_LIMITED, OVERLOADED, ...
- your own policy verdicts -> cost_cap, quota, degraded_mode, ...
"""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
class Severity(str, Enum):
INFO = "info" # FYI, work continues (degraded mode banner)
WARNING = "warning" # something is off; the result may be partial
ERROR = "error" # the request failed; recovery is offered
BLOCKED = "blocked" # refused/blocked; explain, don't retry blindly
class ActionKind(str, Enum):
RETRY = "retry"
CONTINUE = "continue" # continue a truncated answer (03.3 §7.5)
REGENERATE = "regenerate"
REPHRASE = "rephrase" # suggest a safer/simpler phrasing
EDIT = "edit" # let the user fix their input
SWITCH_MODE = "switch_mode" # e.g. chat -> form, agent -> search
HUMAN = "human" # hand off to a person (13A.3 approval queue)
NEW_CHAT = "new_chat" # start a fresh conversation
SAVE_DRAFT = "save_draft" # preserve partial work
UPGRADE = "upgrade" # quota/cost-cap path
DISMISS = "dismiss"
CONTACT_SUPPORT = "contact_support"
@dataclass(frozen=True)
class Action:
kind: ActionKind
label_key: str # key into the copy catalogue
payload: dict = field(default_factory=dict)
@dataclass(frozen=True)
class UserMessage:
"""What the client renders for one failure state."""
severity: Severity
copy_key: str # catalogue key, e.g. "error.rate_limited"
actions: tuple[Action, ...] = ()
retryable: bool = False
retry_after_s: int | None = None
degraded: bool = False # a fallback/cached path served this
trace_id: str | None = None # for "contact support" and logs
params: dict = field(default_factory=dict) # {detail}, {missing_fields}...
# severity, copy_key, action kinds, retryable — the whole policy per signal.
_OUTCOME_MAP: dict[str, tuple[Severity, str, tuple[ActionKind, ...], bool]] = {
# check_response() Status names (03.8 §10.2). OK/TOOL_CALL never reach here.
"TRUNCATED": (Severity.WARNING, "warn.truncated", (ActionKind.CONTINUE, ActionKind.REGENERATE), False),
"CONTEXT_FULL": (Severity.ERROR, "error.context_full", (ActionKind.EDIT, ActionKind.NEW_CHAT), False),
"REFUSED": (Severity.BLOCKED, "blocked.refused", (ActionKind.REPHRASE, ActionKind.HUMAN, ActionKind.DISMISS), False),
"BLOCKED": (Severity.BLOCKED, "blocked.safety", (ActionKind.REPHRASE, ActionKind.HUMAN, ActionKind.DISMISS), False),
"EMPTY": (Severity.WARNING, "warn.empty", (ActionKind.RETRY,), True),
"PAUSED": (Severity.INFO, "info.paused", (ActionKind.CONTINUE,), False),
"FAILED": (Severity.ERROR, "error.provider_failed",(ActionKind.RETRY, ActionKind.CONTACT_SUPPORT), True),
"INCOMPLETE": (Severity.WARNING, "warn.incomplete", (ActionKind.RETRY, ActionKind.DISMISS), True),
}
_TRANSPORT_MAP: dict[str, tuple[Severity, str, tuple[ActionKind, ...], bool]] = {
# 03.8 llm_errors Kind names.
"TIMEOUT": (Severity.ERROR, "error.timeout", (ActionKind.RETRY, ActionKind.SWITCH_MODE), True),
"RATE_LIMITED": (Severity.WARNING, "warn.rate_limited", (ActionKind.RETRY,), True),
"OVERLOADED": (Severity.WARNING, "warn.overloaded", (ActionKind.RETRY, ActionKind.SWITCH_MODE), True),
"SERVER_ERROR": (Severity.ERROR, "error.provider_failed", (ActionKind.RETRY,), True),
"CONNECTION": (Severity.ERROR, "error.connection", (ActionKind.RETRY,), True),
"CONFLICT": (Severity.ERROR, "error.conflict", (ActionKind.RETRY,), True),
"QUOTA": (Severity.BLOCKED, "blocked.quota", (ActionKind.UPGRADE, ActionKind.SWITCH_MODE), False),
"AUTH": (Severity.ERROR, "error.config", (ActionKind.CONTACT_SUPPORT,), False),
"PERMISSION": (Severity.BLOCKED, "blocked.permission", (ActionKind.HUMAN,), False),
"BAD_REQUEST": (Severity.WARNING, "warn.bad_request", (ActionKind.EDIT,), False),
"CONTEXT_TOO_LONG": (Severity.WARNING, "warn.context_full", (ActionKind.EDIT, ActionKind.NEW_CHAT), False),
"TOO_LARGE": (Severity.WARNING, "warn.too_large", (ActionKind.EDIT,), False),
"UNKNOWN": (Severity.ERROR, "error.unknown", (ActionKind.RETRY, ActionKind.CONTACT_SUPPORT), True),
}
_POLICY_MAP: dict[str, tuple[Severity, str, tuple[ActionKind, ...], bool]] = {
# Your own product/policy signals — the provider never emits these.
"cost_cap": (Severity.BLOCKED, "blocked.cost_cap", (ActionKind.UPGRADE, ActionKind.SWITCH_MODE), False),
"quota_exceeded": (Severity.BLOCKED, "blocked.quota", (ActionKind.UPGRADE, ActionKind.SWITCH_MODE), False),
"degraded_mode": (Severity.INFO, "info.degraded", (ActionKind.DISMISS,), False),
"fallback_served": (Severity.INFO, "info.degraded", (ActionKind.DISMISS,), False),
"injection_suspect": (Severity.WARNING, "warn.injection", (ActionKind.DISMISS, ActionKind.CONTACT_SUPPORT), False),
"off_topic": (Severity.INFO, "info.off_topic", (ActionKind.SWITCH_MODE, ActionKind.DISMISS), False),
"scope_refusal": (Severity.BLOCKED, "blocked.scope", (ActionKind.SWITCH_MODE, ActionKind.HUMAN), False),
"ambiguous": (Severity.INFO, "info.ambiguous", (), False), # options ride in params
"nothing_found": (Severity.INFO, "info.nothing_found", (ActionKind.REPHRASE, ActionKind.HUMAN), False),
"partial": (Severity.WARNING, "warn.partial", (ActionKind.EDIT, ActionKind.CONTINUE), False),
"stale_sources": (Severity.WARNING, "warn.stale_sources", (ActionKind.DISMISS,), False),
"conflicting_sources": (Severity.WARNING, "warn.conflicting_sources", (ActionKind.DISMISS,), False),
"context_degraded": (Severity.WARNING, "warn.context_degraded", (ActionKind.NEW_CHAT,), False),
"client_disconnected": (Severity.INFO, "info.disconnected", (), False),
}
_DEGRADED_SIGNALS = {"degraded_mode", "fallback_served"}
def _to_message(severity: Severity, copy_key: str, kinds: tuple[ActionKind, ...],
retryable: bool, degraded: bool = False, **kw) -> UserMessage:
return UserMessage(
severity=severity,
copy_key=copy_key,
actions=tuple(Action(kind=k, label_key=f"action.{k.value}") for k in kinds),
retryable=retryable,
degraded=degraded,
**kw,
)
def _lookup(table: dict, key: str, **kw) -> UserMessage:
sev, copy_key, kinds, retryable = table.get(
key, (Severity.ERROR, "error.unknown", (ActionKind.RETRY, ActionKind.CONTACT_SUPPORT), True))
return _to_message(sev, copy_key, kinds, retryable, **kw)
def from_outcome(status: str, detail: str | None = None,
retry_after_s: int | None = None, trace_id: str | None = None,
params: dict | None = None) -> UserMessage:
"""Map a check_response() Status name (or Outcome.status.value) to a message."""
merged = dict(params or {})
if detail:
merged.setdefault("detail", detail)
return _lookup(_OUTCOME_MAP, status.upper(),
retry_after_s=retry_after_s, trace_id=trace_id, params=merged)
def from_transport(kind: str, retry_after_s: int | None = None,
trace_id: str | None = None) -> UserMessage:
"""Map a 03.8 llm_errors Kind (e.g. 'RATE_LIMITED') to a message."""
return _lookup(_TRANSPORT_MAP, kind.upper(),
retry_after_s=retry_after_s, trace_id=trace_id)
def from_policy(signal: str, **kw) -> UserMessage:
"""Map one of your own product/policy signals to a message."""
kw.setdefault("degraded", signal in _DEGRADED_SIGNALS)
return _lookup(_POLICY_MAP, signal, **kw)
def signal_key(exc_or_status: object) -> str:
"""Normalise an Outcome.status, a Kind string, or an exception carrying a
`.status`/`.kind` attribute into the canonical upper-case key. (Named
`signal_key`, not `classify`, because 03.8's llm_errors already exports a
`classify(exc) -> Failure` with a different contract.)"""
for attr in ("status", "kind"):
v = getattr(exc_or_status, attr, None)
if v is not None:
return str(getattr(v, "value", v)).upper()
return str(exc_or_status).upper()Design choices worth copying:
- Three entry points, one output type.
from_outcometakes thecheck_response()vocabulary,from_transporttakes thellm_errorsKindvocabulary,from_policytakes your own signals. They converge onUserMessage, so the client renders one shape regardless of which layer failed. Unknown signals fall through toerror.unknown— fail-visible, never silently dropped. - Severity drives presentation, not the copy.
INFOrenders as a banner that doesn't interrupt;WARNINGas an inline notice attached to the partial result;ERRORas a blocking card with actions;BLOCKEDas a refusal-style card where retry is not the primary action (retrying a refusal or a quota hit just fails again — that's why those rows setretryable=False). retryableis a policy decision, not a transport fact. A 503 is retryable; a refusal isn't, even though both "failed". Keeping the flag on the message lets the client show [Retry] only when it can actually succeed.degraded=Truemarks fallback-served content. 11C.3, 6.3 is blunt about this: "the cardinal sin is silent degradation". The flag is how the banner in Part 5 knows to render.paramscarries the specifics —{retry_after_s: 30},{missing_fields: [...]},{reset_date: "Nov 1"}— so copy can interpolate without the mapper knowing grammar.
Save this next to the ai_product/ folder as demo_failure_ui.py and run uv run python demo_failure_ui.py against representative signals (real output — pure stdlib):
# demo_failure_ui.py — one signal from each of the three vocabularies.
from ai_product.failure_ui import from_outcome, from_policy, from_transport
print("=== failure_ui: signals -> UserMessage ===")
cases = [
("outcome TRUNCATED", from_outcome("TRUNCATED")),
("outcome REFUSED", from_outcome("REFUSED")),
("transport RATE_LIMITED", from_transport("RATE_LIMITED", retry_after_s=30)),
("policy cost_cap", from_policy("cost_cap")),
("policy fallback_served", from_policy("fallback_served")),
]
for label, m in cases:
print(f"{label:<26} sev={m.severity.value:<8} key={m.copy_key:<28} "
f"retryable={m.retryable} degraded={m.degraded} "
f"actions={[a.kind.value for a in m.actions]}")=== failure_ui: signals -> UserMessage ===
outcome TRUNCATED sev=warning key=warn.truncated retryable=False degraded=False actions=['continue', 'regenerate']
outcome REFUSED sev=blocked key=blocked.refused retryable=False degraded=False actions=['rephrase', 'human', 'dismiss']
transport RATE_LIMITED sev=warning key=warn.rate_limited retryable=True degraded=False actions=['retry']
policy cost_cap sev=blocked key=blocked.cost_cap retryable=False degraded=False actions=['upgrade', 'switch_mode']
policy fallback_served sev=info key=info.degraded retryable=False degraded=True actions=['dismiss']Note the REFUSED row: retryable=False — clicking "Try again" on a refusal just produces the same refusal. And fallback_served flips degraded=True, which is what triggers the Part 5 banner.
3.4 copy_catalog.py: copy as data#
Copy belongs in a catalogue, not scattered through components, for three reasons: translators work on strings not code; product can A/B test tone without a deploy; and a linter can verify every copy_key the mapper emits actually exists. Here is the file (English complete; Hindi partial on purpose to show the fallback chain):
"""ai_product/copy_catalog.py — user-facing copy for failure states, with i18n keys.
Lesson 13A.4. Stdlib only. Copy lives in ONE place, keyed by a stable id, so
translators work on strings — never on code — and so a/b testing tone is a
data change, not a deploy. `resolve()` falls back locale -> en -> the key
itself (so a missing translation degrades visibly, never crashes).
"""
from __future__ import annotations
COPY: dict[str, dict[str, str]] = {
# ---- English (the fallback locale; keep it complete) -------------------
"en": {
# outcomes (check_response Status names)
"warn.truncated": "This answer was cut off at the length limit.",
"error.context_full": "This conversation is too long for the model to read at once.",
"blocked.refused": "I can't help with this one, but here's what I can do instead.",
"blocked.safety": "This request was blocked by a safety filter.",
"warn.empty": "The model returned an empty answer.",
"info.paused": "The model paused — continue to keep going.",
"error.provider_failed": "The AI service hit an error.",
"warn.incomplete": "The answer didn't finish properly.",
# transport (03.8 Kind names)
"error.timeout": "The request timed out before the model answered.",
"warn.rate_limited": "Too many requests — try again in a moment.",
"warn.overloaded": "The AI service is busy right now.",
"error.connection": "We lost the connection to the AI service.",
"error.conflict": "That conflicted with a change already in progress — try again.",
"blocked.quota": "You've reached your usage limit for this period.",
"error.config": "Something is misconfigured on our side — we've been alerted.",
"blocked.permission": "You don't have permission to do that.",
"warn.bad_request": "The request couldn't be understood.",
"warn.context_full": "That's too much text for one request — try a shorter version.",
"warn.too_large": "The file is too large for this feature.",
"error.unknown": "Something went wrong on our side.",
# policy signals (our own code)
"blocked.cost_cap": "This workspace has reached its AI spend cap for the month.",
"info.degraded": "You're seeing a simplified answer while we fix a problem.",
"warn.injection": "We removed a link or instruction we couldn't verify.",
"info.off_topic": "That's outside what I can help with here.",
"blocked.scope": "This feature isn't available for your account.",
"info.ambiguous": "I want to make sure I answer the right question.",
"info.nothing_found": "I couldn't find anything relevant in the sources I searched.",
"warn.partial": "I found part of what you asked for.",
"warn.stale_sources": "Some sources may be out of date.",
"warn.conflicting_sources": "The sources disagree — check both before relying on either.",
"warn.context_degraded": "This conversation is getting long — answers may get less precise.",
"info.disconnected": "Connection lost — your partial answer is saved.",
# action labels
"action.retry": "Try again",
"action.continue": "Continue",
"action.regenerate": "Regenerate",
"action.rephrase": "Try a different phrasing",
"action.edit": "Edit your request",
"action.switch_mode": "Use a simpler mode",
"action.human": "Talk to a person",
"action.new_chat": "Start a new chat",
"action.save_draft": "Save draft",
"action.upgrade": "See plans",
"action.dismiss": "Dismiss",
"action.contact_support": "Contact support",
# bodies (optional second line under the title)
"body.rate_limited": "Retrying automatically in {retry_after_s} seconds.",
"body.quota": "Your limit resets on {reset_date}.",
"body.degraded": "Answers may be less detailed than usual.",
},
# ---- Hindi (partial on purpose: shows the fallback chain) --------------
"hi": {
"warn.truncated": "यह उत्तर लंबाई की सीमा पर कट गया।",
"error.timeout": "मॉडल के जवाब देने से पहले अनुरोध का समय समाप्त हो गया।",
"blocked.safety": "इस अनुरोध को सुरक्षा फ़िल्टर द्वारा ब्लॉक कर दिया गया।",
"action.retry": "फिर से कोशिश करें",
"action.human": "किसी व्यक्ति से बात करें",
# deliberately missing most keys -> resolve() falls back to "en"
},
}
DEFAULT_LOCALE = "en"
def resolve(locale: str, key: str, **params) -> str:
"""Look up copy for `key` in `locale`, falling back to DEFAULT_LOCALE,
then to the key itself (a missing translation shows up in review, not
as a crash). `{name}` placeholders are filled from **params."""
text = COPY.get(locale, {}).get(key) or COPY[DEFAULT_LOCALE].get(key) or key
try:
return text.format(**params)
except (KeyError, IndexError):
return text
def catalogue_keys() -> list[str]:
"""Every key the English catalogue defines — handy for linting a11y_lint
coverage or for translator hand-off."""
return sorted(COPY[DEFAULT_LOCALE])Save this as demo_copy_catalog.py next to the ai_product/ folder and run it (real output, stdlib only):
# demo_copy_catalog.py — the fallback chain: locale, then English, then the key.
from ai_product.copy_catalog import catalogue_keys, resolve
print("=== copy_catalog: resolve ===")
for locale, key, params in [
("en", "body.rate_limited", {"retry_after_s": 30}),
("en", "warn.truncated", {}),
("hi", "warn.truncated", {}),
("hi", "blocked.quota", {}), # not translated: falls back to English
("xx", "no.such.key", {}), # no such locale or key: the key itself
]:
print(f"{locale} {key:<18}: {resolve(locale, key, **params)}")
print(f"{'keys in catalogue':<21}: {len(catalogue_keys())}")=== copy_catalog: resolve ===
en body.rate_limited : Retrying automatically in 30 seconds.
en warn.truncated : This answer was cut off at the length limit.
hi warn.truncated : यह उत्तर लंबाई की सीमा पर कट गया।
hi blocked.quota : You've reached your usage limit for this period.
xx no.such.key : no.such.key
keys in catalogue : 47The hi blocked.quota line is the English fallback (no Hindi string exists), and the xx line shows the key itself — visible in review, not a crash.
The fallback chain is the i18n lesson in miniature: a missing Hindi string shows the English one (usable, slightly off-language) rather than crashing or showing hi.blocked.quota. In production you'd ship complete locales and let the fallback counter in your analytics tell you which keys still need translation — a missing-translation metric is itself a product metric (13A.6).
3.5 Wiring it into the event contract#
UserMessage is designed to ride inside the 13A.2 event contract: your server emits a warning or error event carrying the serialised message, and the client renders it without interpreting anything. The mapping happens once, server-side:
# In your FastAPI stream endpoint (shape from 03.3 §11.4 + 13A.2 events).
# `check_response` is 03.8's check_response.py (keep it beside this file);
# `sse_event` stands for whatever helper your endpoint uses to yield one
# contract event (13A.2 §6.2's SSEEncoder, or FastAPI's ServerSentEvent);
# `trace` is your request's tracing span (11A.1).
import dataclasses
from check_response import check_response
from ai_product.copy_catalog import resolve
from ai_product.failure_ui import from_outcome, from_transport, from_policy
# ... inside the stream loop, when check_response() returns a non-usable outcome:
outcome = check_response(final_message)
if not outcome.usable:
msg = from_outcome(outcome.status.value, detail=outcome.detail,
trace_id=trace.trace_id)
# 13A.2's ErrorEvent/WarningEvent require `message`, so keep a plain-text
# fallback beside the structured fields (severity, copy_key, actions...).
payload = {**dataclasses.asdict(msg), "message": resolve("en", msg.copy_key),
"code": msg.copy_key}
yield sse_event("error" if msg.severity.value == "error" else "warning", payload)
returnThe extra fields are an additive extension of the 13A.2 contract (13A.2, 6.3): a client that knows only message, retryable and code still renders the English fallback, and a client that knows copy_key and actions renders the designed state in its own locale. The client never learns that TRUNCATED meant finish_reason: "length" — it learns copy_key: "warn.truncated" with actions [continue, regenerate]. Swap the provider, rename the enum, change the copy — the wire contract doesn't move.
What this means for you as an engineer. The mapper is the cheapest insurance in the whole lesson: one file, no dependencies, and it converts an unbounded set of internal failures into a bounded set of designed states. The expensive part isn't the code — it's the policy encoded in the three maps: which signals exist, which are retryable, which actions each deserves. Review those tables like you review an API contract, because they are one.
Part 4: Recovery paths and preserving user work#
4.1 The recovery-path menu#
Every UserMessage carries actions because "something went wrong" is never the whole answer. The menu, mapped to the failure families that need it:
| Action | What it does | When it's the right primary action |
|---|---|---|
| Retry | Re-issue the same request | Transient transport failures only (timeout, 429-slow-down, 503, dropped stream before content). Never for refusals, blocks, quota or bad requests — retrying those just fails again, sometimes billed |
| Continue | Resume a truncated/paused answer from where it stopped | TRUNCATED, PAUSED, mid-stream failures after content — via the 03.3 §7.5 continuation request |
| Regenerate | Fresh generation of the same prompt | Confidently-wrong suspicion, bland output, truncation where continue isn't supported. Note: a new sample — output may differ, for better or worse |
| Rephrase | Offer a suggested safer/simpler phrasing of the user's input | Refusals, safety blocks, context-too-long, bad requests — the model's own recommended_model hint (03.8, 10.4) is the provider-side version of this |
| Edit | Put the cursor back in the input with the offending part selected | Bad requests, context-too-long, ambiguous inputs the user can fix themselves |
| Switch mode | Offer a different feature shape: form instead of chat, quick search instead of agent, cached answer instead of live | Outages, quota caps, degraded mode — the graceful-degradation paths of Part 5 |
| Human | Hand off to a person with context | Repeated failures, high-stakes domains, agent escalations (08A.14, 6.4 — carry the trace ID so the human sees the trajectory) |
| New chat | Start a fresh conversation | Context-full, long-conversation degradation — the honest off-ramp when history itself is the problem |
| Save draft | Preserve whatever partial output exists | Mid-stream failures, truncation — the user's work product shouldn't die with the connection |
| Upgrade | Route to plans/pricing | Quota and cost-cap states — a plan boundary, not an error |
| Dismiss | Close the notice, keep what rendered | INFO-severity states (degraded banner, injection cleanup notice) — always available, never the only option |
Ordering matters: put the most likely to succeed action first, and the least committal last. For a refusal that's [rephrase, human, dismiss] — never [retry] first, because retry can't work.
4.2 Preserving user work when things break#
The cardinal rule: a failure must never destroy work the user already did. Concretely:
- Drafts and inputs. The user's prompt, attachments and any edits survive every failure state — the input box is never cleared by an error. Autosave conversation state server-side (the 13A.2 contract's job IDs make this natural) so a refresh or reconnect restores position.
- Partial answers. When a stream dies mid-answer, the partial text stays on screen labelled as partial — "Connection lost — your partial answer is saved" (
info.disconnectedin the catalogue) — with Continue/Retry/Regenerate offered. 03.3, 7.5 is explicit that "seen" includes reasoning panels and tool badges, not just answer text: aresetevent must clear everything shown, or the retry visibly duplicates. - Generated artifacts. In document-intelligence flows (the 13B.3 shape), a partially extracted document keeps its completed fields; failed fields are marked, not blanked. "3 of 5 fields extracted — the totals row failed" beats a blank form.
- Side effects. If a tool call already fired (a ticket was created, a refund requested), the failure message must not imply it didn't happen — and must not imply it did. "The refund request was submitted but confirmation timed out — check your tickets before retrying" is the honest version; idempotency keys (03.8, Part 11) are what make the retry safe.
4.3 The retry honesty rules#
Retries are where failure UX becomes a billing and trust problem:
- Retry what can succeed. Transient
Kinds only — theretryableflag onUserMessageencodes this. A retry loop on a refusal, a quota cap or a bad request burns money and patience. - Back off visibly. For rate limits, show the countdown from
retry_after_s/Retry-After(03.8, 7.2) — "retrying in 23… 22…" beats a spinner that might be stuck. Cap auto-retries (two or three) then offer manual retry; infinite auto-retry is a battery and bill killer on mobile. - Don't retry silently past a point the user can see. 03.3, 7.5: before any content was shown, a silent restart is invisible and fine; after content, the user must see something happen (a
reset, a "retrying" state) or they'll think the answer is still growing. - A retry is a new generation. Regenerate produces different text — say so when it matters ("this may read differently") and never present a retry as "the same answer, fixed".
4.4 What this means for you as an engineer#
Design recovery paths with the failure states, not after them. The exercise that proves it: for every row of the failure gallery, write the primary action and check it against the retry-honesty rules. If your answer for "provider outage" is "show an error and a retry button", you've designed a dead end — the degraded mode (Part 5) is the answer that keeps the user served.
Part 5: Graceful degradation — fallbacks users can feel#
Deep-dive
5.1 The degradation ladder, from the user's side#
11C.3, 6.3 defined the engineering ladder: fallback model → smaller model → cached answer → retrieval-only → queued → honest failure. This part is the UX of each rung — what the user sees and whether they can tell it happened.
| Rung | What serves the request | What the user should see | When it's acceptable |
|---|---|---|---|
| 1. Fallback model/provider | A different model answers | Normal answer + a subtle degraded indicator if quality might differ | Transient failure; the fallback passed your evals (11C.3, 6.5) |
| 2. Smaller/cheaper model | A lighter model answers | Same as above, plus honest expectations for hard tasks | Cost/latency emergency; quality dip acceptable for this task tier |
| 3. Cached/stale answer | A stored answer for this query | The answer with a freshness note — "Answered from a cached result (2 h old)" | FAQ-style, low-stakes, TTL-bounded queries only |
| 4. Retrieval-only | The sources, no synthesis | "The AI summary is unavailable — here are the 4 sources it would have used" | Synthesis is what's failing; the user can read sources themselves |
| 5. Queued | "We'll get back to you" | Job accepted, ETA honest or absent, notification on completion (11C.1 async patterns; 13A.2 long-running UX) | Non-interactive work: document batches, reports, voice-note processing |
| 6. Honest failure | Nothing served | The Part 3 error card with recovery actions | Interactive work with no degraded path |
5.2 When to tell the user a fallback happened#
The disclosure dial has three positions, and the right one depends on how different the answer could be:
- Always disclose when the degraded answer could mislead: cached answers (staleness matters), retrieval-only (the shape changed — no synthesis), a fallback model on a high-stakes or regulated feature (12.9 may require it), or any answer where the user will act on it (a refund decision, a medical-style FAQ, a legal summary). 11C.3, 6.5: "for a support bot, a slightly different tone is fine; for a medical-style FAQ or a legal document summary, the degradation may need to be explicit."
- Disclose subtly when quality is probably fine but provenance matters: a same-tier fallback model on a low-stakes chat. A small "answered by backup" badge or nothing at all — your eval data decides. What you must never do is let the degraded answer be indistinguishable in a way that breaches data policy: a fallback to a provider you haven't cleared is a compliance breach, not resilience (11C.3, 6.4).
- Don't disclose the machinery when it doesn't change anything the user cares about: internal retries, breaker state, which zone served. The user cares about the answer's quality and provenance, not your circuit breakers.
The degraded-mode banner itself should be dismissible but persistent-enough: "You're seeing simplified answers while we fix a problem with the AI service. [Dismiss]" — INFO severity, info.degraded copy, one action. It appears once per session (or once per degradation episode), not on every message, or it becomes noise users learn to ignore — which is how real warnings die.
5.3 Partial results as a degradation rung#
The most elegant degradation is often showing what you have. 11B.1 noted that "progress and partial results fill the pre-TTFT gap"; the same principle applies to failure: when full synthesis fails, partial structured output, the retrieved sources, or completed tool steps are still valuable. The design rules:
- Label partial explicitly (
warn.partial,severity=WARNING) and name what's missing. - Keep completed work interactive — extracted fields editable, sources clickable (through the Part 7 sanitiser), steps resumable.
- Never pad a partial result to look complete. "Found 3 of 5" is honest; five greyed-out boxes is confusing.
5.4 Designing degraded mode at design time#
11C.4 states the rule: "decide degraded modes at design time, not during the incident." Concretely, for each feature in your 13A.1 feature brief:
- Name the degraded path before launch (cheaper model? cached FAQ? retrieval-only? form? queue?).
- Write its
UserMessage(info.degradedor a feature-specific key) and its disclosure level (5.2). - Put it on the readiness checklist — 11C.4's checklist already gates "Degraded-mode UX defined and labelled" and "Degraded modes implemented and documented".
- Rehearse it: kill the primary in staging, watch the degraded path serve, verify the label shows. A degraded mode you've never run is a hypothesis, not a feature.
What this means for you as an engineer. Degradation is a product feature with an SLA of its own. The engineering (fallback chains, breakers, caches) is 11C.3's; your job is the contract: which rung serves which failure, what the user sees, and how they know. Write the rung table into your feature brief — it's the difference between "the AI was down for an hour" and "the AI was down for an hour and users barely noticed because the fallback was labelled and worked".
Part 6: Clarifying questions, ambiguity, and empty states#
Deep-dive
6.1 Ask versus guess: the decision table#
The model can always try to answer, but sometimes the honest move is a question. The cost asymmetry decides:
| Situation | Guess cost | Ask cost | Right move |
|---|---|---|---|
| Low stakes, obvious default exists | Wrong answer annoys mildly | Interrupts flow | Guess with a stated assumption — "I'll assume you mean the March invoice; say so if not" |
| High stakes, irreversible action (refund, send, delete) | Wrong action is a real incident | One extra click | Always ask — and for agents, the 13A.3 approval gate owns the confirm UI |
| Ambiguity is structural (two plausible referents) | 50/50 wrong | One tap to resolve | Ask with options as chips — never open text |
| User is mid-flow, latency-sensitive | A wrong guess wastes the whole turn | A quick clarify is cheaper than a wrong long answer | Ask only if cheap — one question, tappable answers |
| The model genuinely can't know (missing data only the user has) | Confident fabrication — the worst outcome | Necessary | Ask, and say why you need it |
The conversational-budget rule: one clarifying question per turn, maximum. An interrogation loop — "which did you mean?" → "and which date?" → "and which account?" — is worse than a stated assumption the user can correct. If you need three facts, ask for them in one structured form (chips + fields), not three sequential chat messages.
6.2 Clarifying-question UI patterns#
- Chips / suggestion pills. The ambiguity answer as tappable options: "March invoice [March] [April] [Neither]". Zero typing, one tap, unambiguous signal. This is the default pattern for 2–4 discrete options.
- Inline forms inside chat. When the missing info is structured (date range, amount, order ID), render a mini-form in the message — the 13A.2 event contract's
suggestion/form events carry it. Forms beat chat for data collection every time: validation is instant, no misparse. - Sensible defaults with visible assumption. "I'll proceed with the standard 30-day refund window unless you say otherwise" — the user can ignore it and stay in flow, or correct it. Pair with the assumption being stated, never silent (08A.14's false-completion lesson applies: state what you're doing).
- The escape hatch. Every clarifying question needs "None of these" / "Let me explain" — a forced choice with no right answer is a trap that produces garbage input.
6.3 Empty and cold-start states#
The first-run and nothing-found states are where retention is won. The toolkit:
- Suggested prompts / examples. 3–6 concrete, capability-revealing prompts ("Summarise this quarter's refunds", "Draft a reply to an angry customer") — not generic "Ask me anything". Each should demonstrate a different thing the product does. Rotate them; stale suggestions teach users the product doesn't learn.
- Templates. For generation features (emails, reports, tickets), offer fill-in templates — they teach the input format and produce better first outputs than a blank box.
- Capability tours. A dismissible, once-per-user tour or "what can I do" panel — honest about limits (link the 11C.4 limitation notices discipline: say what it can't do too).
- Recent items. Returning users get their history, drafts and favourites — the fastest path back into value.
- Progressive disclosure. Don't front-load every feature; reveal complexity as the user demonstrates readiness (the 13A.1 taxonomy's product shapes each have a natural onboarding depth).
6.4 When retrieval finds nothing#
07.4's abstention is the engineering contract: status: "abstained" means your pipeline decided the corpus can't answer, distinct from the model refusing. The UX renders the three abstention gates differently:
- Nothing retrieved / below score floor → "I searched the handbook and found nothing on X" + rephrase suggestions + human/escalation option. The message names what was searched — "the employee handbook (v2026.3)" — because "I don't know" without scope sounds like the product is broken, not the corpus.
- Context plausibly relevant but insufficient →
partialorneeds_clarification: show what was found and what's missing ("I found the general policy but not the 2026 exception — here's what applies generally"). - Answerable but low coverage → answer with the caveat attached, not silence.
The 07.4 calibrating-abstain-rate trade-off — selective accuracy vs coverage — is a product dial: a support bot abstains more (safer), a docs search abstains less (coverage matters). Your abstention rate is a metric (13A.6), and the UX must make the dial's consequences visible to the people tuning it.
What this means for you as an engineer. Ask-versus-guess is a policy table, not a vibe. Write it into the feature brief (13A.1): for each action the product can take, what's the cost of guessing wrong? The clarifying-question UI is the cheapest reliability feature you'll ever ship — a well-formed question prevents an entire class of confidently-wrong answers.
Part 7: Rendering safely#
7.1 Model output is untrusted input — including its formatting#
Everything in 12.2 and 12.5 applies with full force here: the model's Markdown is data that becomes markup. The specific channels:
| Channel | Attack | Defence |
|---|---|---|
Markdown image  |
Reader's browser auto-fetches; data exfiltrates in the query string (Bing Chat 2023, EchoLeak 2025 — 12.2, 3.2) | Strip images by default, or allow-list hosts; alt text survives as plain text |
Markdown link, reference-style [t][ref] + [ref]: url |
Bypasses filters that only match inline links (EchoLeak's CSP bypass) | Sanitise all three link forms + bare URLs; flatten unsafe links to text |
Raw HTML <img onerror=…>, <script> |
XSS in the renderer | Allow-list sanitiser on the output HTML — nh3 (v0.3.7, MIT, verified on PyPI Nov 2026); not bleach (final release 6.4.0, June 2026, unmaintained) |
javascript:/data: URLs |
Script execution on click/render | Scheme allow-list: https, http, mailto only |
| Open redirect / phishing link | [verify](https://paypa1.com) |
Host allow-list for known-good domains; show the real URL on hover/preview |
| Invisible text / bidi tricks | Hidden instructions or misleading display | 12.5, 2.1 covers invisible-character detection on input; apply the same hygiene to output rendering |
7.2 markdown_safety.py: the sketch#
This stdlib sketch shows the policy decisions — what to mask, strip, defang, keep — in a short module, but it is a sketch and it says what it does not catch (see its docstring). For production, swap the internals for nh3.clean() or use the llm_guard_kit sanitiser from 12.2, §10.4, which also handles bare URLs, shortcut references, raw-HTML attributes and repeated passes, and has tests for hostile 100 kB inputs. The policy is what matters:
"""ai_product/markdown_safety.py — a stdlib sketch of safe rendering for model output.
Lesson 13A.4. This is a SKETCH, not a sanitiser: it shows the policy decisions
(what to strip, what to neutralise, what to keep) in stdlib so you can see the
shape. For production use `nh3` (Python bindings to the Rust
ammonia HTML sanitiser, MIT, v0.3.7 as of November 2026 — verified on PyPI) or
the `llm_guard_kit` Markdown exfil sanitiser from lesson 12.2 §10.4, which
already implements this policy with reference-style links, code-span masking
and raw-HTML handling. Do NOT use `bleach`: its final release was 6.4.0
(June 2026) and the project is unmaintained.
What it does not catch (use 12.2's version, which has tests for these and for
hostile 100 kB inputs): bare URLs and `www.` addresses, which a renderer may
autolink and which stay as typed; shortcut links `[label]` that resolve against
a definition (the definition is removed, so they go dead, but nothing reports
it); an `<a href>` or `<img src>` in raw HTML is escaped to visible text rather
than judged against the allow-list; and it makes one pass, not a repeat until
the text stops changing. It does keep every scan bounded (each pattern stops at
the next `[`, `]` or `<`), so it is linear on `[` or `<` floods, and its code
mask follows CommonMark: an escaped backtick opens no code span.
"""
from __future__ import annotations
import re
from urllib.parse import urlparse
# Every scan below stops at the next "[", "]" or "<". A pattern that may run on to
# the end of the text from each of 50,000 starting points takes minutes on a
# 100 kB reply, which is a denial of service you wrote yourself.
# Tags that fetch or execute on render — removed with their content.
_DANGEROUS_HTML = re.compile(
r"<(script|style|iframe|object|embed|form|meta|link|base|svg|math)\b[^<>]*>"
r"(?:(?!<\1\b)[\s\S]){0,5000}?</\1\s*>|<(script|style|iframe|object|embed|"
r"form|meta|link|base|svg|math)\b[^<>]*/?>", re.I)
_HTML_TAG = re.compile(r"</?[A-Za-z][^<>\n]*>")
# A destination is <angle bracketed> or bare. A bare one may hold balanced "(...)"
# and an IPv6 literal "[2001:db8::1]", but no other "[", "(" or whitespace.
_DEST = (r"(?:<([^<>\n]+)>|((?:[^()\s<>\[]|\[[0-9A-Fa-f:.]{1,45}\]|"
r"\([^()\s<>\[]*\))+))(?:\s+[\"'][^\"']*[\"'])?\s*")
# Link text may hold one level of nested brackets: [a [b]](url) is a link.
_TEXT = r"((?:[^\[\]]|\[[^\[\]]*\])*)"
# Markdown image:  — the classic exfil channel (12.2 §3.2).
_IMAGE = re.compile(r"!\[" + _TEXT + r"\]\(\s*" + _DEST + r"\)")
# Inline link: [text](dest); also matches images (handled above first).
_LINK = re.compile(r"\[" + _TEXT + r"\]\(\s*" + _DEST + r"\)")
# Reference-style definitions: [ref]: url (the EchoLeak bypass, 12.2 §3.2)
_REF_DEF = re.compile(r"^[ \t]{0,3}\[[^\[\]\n]+\]:[ \t]*\S+.*$", re.M)
_REF_USE = re.compile(r"!?\[([^\[\]]+)\]\[([^\[\]]*)\]")
# Code never autolinks, so mask it before rewriting — but only what a renderer
# really treats as code (these two patterns and _mask_code are 12.2's). A fence
# starts a line and is closed by a line of the same character, at least as long.
# A span opens with a run of n backticks and closes with a run of exactly n; a
# run right after a backslash opens nothing, so \`\` is NOT code.
_FENCE_OPEN = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
_CODE_SPAN = re.compile(r"(?<![`\\])(`+)(?!`)[^\n]+?(?<!`)\1(?!`)")
_MASK = "\x00PROTECTED%d\x00"
_ALLOWED_SCHEMES = {"http", "https", "mailto"}
def _host_ok(url: str, allow_hosts: frozenset[str] | None) -> bool:
if allow_hosts is None:
return False
try:
return (urlparse(url).hostname or "").lower() in allow_hosts
except ValueError:
return False
def _safe_dest(dest: str, allow_hosts: frozenset[str] | None) -> str | None:
"""Return the destination if it may be rendered as a link, else None."""
try:
p = urlparse(dest)
except ValueError:
return None
if p.scheme.lower() not in _ALLOWED_SCHEMES:
return None # javascript:, data:, vbscript: -> dead
if p.scheme in ("http", "https") and not _host_ok(dest, allow_hosts):
return None # host not allow-listed -> dead
return dest
def _mask_code(text: str, stash: list[str]) -> str:
"""Swap every fenced block and code span for a placeholder; the originals go
in `stash`. Same rules as 12.2's `_mask_code`: an unclosed fence is not code,
so what follows it is still sanitised."""
def put(code: str) -> str:
stash.append(code)
return _MASK % (len(stash) - 1)
lines = text.split("\n")
out: list[str] = []
no_closer: dict[str, int] = {} # fence char -> shortest length with no closer
i = 0
while i < len(lines):
opener = _FENCE_OPEN.match(lines[i].rstrip("\r"))
# An info string after a backtick fence cannot contain a backtick.
if opener and not (opener.group(1)[0] == "`" and "`" in opener.group(2)):
char, size = opener.group(1)[0], len(opener.group(1))
if size < no_closer.get(char, size + 1):
closer = re.compile(rf"^ {{0,3}}{char}{{{size},}}[ \t]*$")
j = i + 1
while j < len(lines) and not closer.match(lines[j].rstrip("\r")):
j += 1
if j < len(lines): # closed: this is code
out.append(put("\n".join(lines[i:j + 1])))
i = j + 1
continue
no_closer[char] = size # unclosed: plain text
out.append(_CODE_SPAN.sub(lambda m: put(m.group(0)), lines[i]))
i += 1
return "\n".join(out)
def clean_markdown(text: str, *, allow_hosts: frozenset[str] | None = frozenset(),
allow_images: bool = False) -> str:
"""Neutralise the constructs that can auto-fetch, link or execute on render.
Policy (matches lesson 12.2 §10.4): images are OFF by default — an <img>
or Markdown image makes the *reader's* browser fetch an attacker URL.
Links survive only with an allowed scheme AND (for web URLs) an
allow-listed host; anything else flattens to its visible text.
"""
# 1. Drop NULs (our placeholders use them, so input must not forge one),
# then mask real code so we don't rewrite inside it.
stash: list[str] = []
text = _mask_code(text.replace("\x00", ""), stash)
# 2. Images: alt text survives as plain text; the fetch never happens.
def _img(m: re.Match) -> str:
alt, dest = m.group(1), next(g for g in m.groups()[1:] if g)
if allow_images and _safe_dest(dest, allow_hosts):
return m.group(0)
return alt if alt else "[image removed]"
text = _IMAGE.sub(_img, text)
# 3. Links: keep the text; keep the href only if the destination is safe.
def _link(m: re.Match) -> str:
label = m.group(1)
dest = next(g for g in m.groups()[1:] if g)
return f"[{label}]({dest})" if _safe_dest(dest, allow_hosts) else label
text = _LINK.sub(_link, text)
# 4. Reference-style: remove the definitions; collapse the uses to text.
text = _REF_DEF.sub("", text)
text = _REF_USE.sub(lambda m: m.group(1), text)
# 5. Raw HTML last, so tags that links or images leave glued together are
# still caught: drop dangerous tags, escape any surviving tag to text.
text = _DANGEROUS_HTML.sub("", text)
text = _HTML_TAG.sub(lambda m: m.group(0).replace("<", "<").replace(">", ">"), text)
# 6. Unmask code untouched (one pass, so cost stays linear in the text).
text = re.sub(r"\x00PROTECTED(\d+)\x00", lambda m: stash[int(m.group(1))], text)
return text
if __name__ == "__main__":
demo = (
"Here is the answer.\n\n"
"Check  and "
"[the docs](https://docs.example.com/refunds) or "
"[this](javascript:alert(1)).\n\n"
"```python\nprint(\"[not a link](https://evil.example.com)\")\n```\n\n"
"<script>alert(1)</script>Done."
)
print(clean_markdown(demo, allow_hosts=frozenset({"docs.example.com"})))Real output (stdlib only — the payload is benign stand-in text). The output itself contains code fences, so it is wrapped in a four-backtick fence to keep them literal:
Here is the answer.
Check chart and [the docs](https://docs.example.com/refunds) or this.
```python
print("[not a link](https://evil.example.com)")
```
Done.Read it as a policy demonstration: the image became its alt text "chart" (the fetch never happens), the javascript: link flattened to the word "this" (the destination pattern accepts the balanced parentheses in javascript:alert(1), so no stray ) is left behind), the allow-listed docs link survived, the code span kept its literal [not a link](https://evil.example.com) untouched (code never autolinks), and the <script> vanished. One honest artefact of the sketch: a flattened link leaves no trace that a link existed. It is also a sketch in the sense of the docstring's list of what it does not catch (bare URLs, shortcut references, raw-HTML attributes judged against the allow-list, repeated passes), so production wants nh3 for HTML and the llm_guard_kit sanitiser for the full Markdown policy.
Two properties were checked with stdlib tests, because a demo never shows them. First, hostile input stays cheap: 100,000 [ characters, 20,000 repeats of . Second, escaping is respected: \`\` is not code to a renderer (the backslash makes the first backtick literal), so the image inside it is stripped like any other, while the same image inside a real code span or fence is left alone.
7.3 The other rendering rules#
Beyond links and HTML, the renderer has obligations for every construct the model can emit:
- Code blocks. Syntax label (from the fence info string, sanitised — it's model-controlled text), a copy button, horizontal scroll not page scroll, and never auto-executed. "Copy" is the safe action; "Run" belongs to a sandboxed playground (12.6 owns code-execution safety).
- Tables. Render as real tables when the model emits them; fall back to a code block when the Markdown table is malformed mid-stream (streaming partial markup — 13A.2 owns the incremental-rendering strategy; your job is the fallback: half-rendered tables look broken, code blocks look intentional).
- Math. LaTeX delimiters render through a sanitised math renderer; unknown or malformed math degrades to inline code, never to a page-breaking error.
- Citations. Citation markers
[1]or【3†source】resolve to a source list your pipeline built (07.5) — the model's claim of a citation is unverified until your code checks it (03.4's lesson: schema-valid ≠ trustworthy). - User vs model content separation. Visually and structurally distinct: user messages in one style, model output in another, tool output and retrieved documents in a third (quoted/collapsed, provenance-labelled per 12.2's provenance rules). When the model quotes a document, the user must see it's a quote — not the model's own words. This separation is also the injection defence: content the model read looks different from content the model said.
- Streaming-partial markup. While tokens arrive, half-formed Markdown (an unclosed
**, a table mid-row) must render gracefully — buffer at block boundaries, show plain text for incomplete constructs. The smoother from 13A.2 paces the tokens; the renderer's job is to never show a broken table or a literal![for more than a frame.
What this means for you as an engineer. Rendering safety is a pipeline stage, not a component: input → model → structured validation → sanitise → render → (if exported: sanitise again for the export format). Put clean_markdown (or nh3/llm_guard_kit in production) at every boundary where model text becomes markup, and log when it fires — a sanitiser that rewrites a lot is a signal your retrieval corpus or prompt is letting injection-shaped content through (12.2, Part 7).
Part 8: Accessibility for AI interfaces#
8.1 The frame: WCAG 2.2 applies fully#
AI interfaces are web/mobile interfaces first. WCAG 2.2 (W3C Recommendation, 12 December 2024) applies in full — there is no "AI exemption". Accessibility is also increasingly a legal duty, not only good practice. In the EU, the European Accessibility Act (Directive (EU) 2019/882) has applied since 28 June 2025 to a range of consumer-facing products and services, such as online shops, ticketing platforms and banking services. Its harmonised standard EN 301 549 points to WCAG 2.1 Level AA for web content, and many teams already target 2.2 AA. Service providers that are microenterprises (fewer than 10 employees and turnover or balance sheet of at most EUR 2 million) are exempt, and the Directive's Article 32 sets transitional periods (for example, until 28 June 2030 for products that a service provider already used lawfully before the application date). The official Your Europe page on accessibility (read 12 November 2026) confirms the application date, the example services and the microenterprise exemption; read the Directive's text on EUR-Lex for the exact conditions. Scope and exemptions depend on your product and country, so treat this as orientation, not legal advice, and ask counsel which harmonised standard you are measured against. The criteria that bite hardest for AI UX, verified against the spec:
| WCAG 2.2 criterion | Level | What it means for an AI feature |
|---|---|---|
| 1.4.3 Contrast (Minimum) | AA | 4.5:1 text contrast — including the de-emphasised text people use for AI disclaimers and citations (the smallest text is where contrast fails first) |
| 1.4.11 Non-text Contrast | AA | 3:1 for UI components and meaningful graphics — focus rings, chart marks, the "AI" badge boundary |
| 2.1.1 Keyboard | A | Every action — send, stop, retry, approve, feedback — operable without a mouse. The streamed-answer Stop button must be keyboard-reachable while streaming |
| 2.1.2 No Keyboard Trap | A | Focus can always leave the chat input / modal / approval dialog |
| 2.4.3 Focus Order | A | Focus moves logically when new content arrives — into the new message, not lost to the top of the page |
| 2.4.7 Focus Visible | AA | A visible focus indicator on every stop — including custom-styled chat controls |
| 2.4.11 Focus Not Obscured (Minimum) | AA (new in 2.2) | The focused element isn't entirely hidden by sticky headers, the composer bar, or a notification toast |
| 2.4.13 Focus Appearance | AAA (new in 2.2) | The focus indicator needs ≥3:1 contrast against its surroundings and adequate area — the stricter sibling of 2.4.7's "visible" |
| 2.5.7 Dragging Movements | AA (new in 2.2) | Anything operated by dragging — sliders, autonomy dials, reorderable lists — must also work with a single pointer tap/keys, unless dragging is essential |
| 2.5.8 Target Size (Minimum) | AA (new in 2.2) | 24×24 CSS px minimum for pointer targets — thumbs-up/down buttons, chips, citation links |
| 2.2.1 Timing Adjustable | A | Session timeouts, "typing" indicators that imply urgency, auto-advancing carousels of suggestions — all need a way to extend/disable |
| 2.2.2 Pause, Stop, Hide | A | Moving/blinking content (streaming animations, skeleton shimmer) must be pausable |
| 2.3.3 Animation from Interactions | AAA | Motion triggered by interaction can be disabled — prefers-reduced-motion is the mechanism |
| 3.2.6 Consistent Help | A (new in 2.2) | Help mechanisms (contact support, the "?" for "what can you do") appear in the same place across pages |
| 3.3.1 Error Identification | A | An automatically detected error must identify the item in error and describe it in text — the five-part message anatomy in Part 3.1 is this criterion applied to AI failures |
| 3.3.3 Error Suggestion | AA | When the correction is known, suggest it — "try again in ~30 s", "use a shorter version" are error suggestions; a bare "error" is not |
| 3.3.7 Redundant Entry | A (new in 2.2) | Don't make users re-enter information the system already has — autofill the clarifying form from context |
| 4.1.2 Name, Role, Value | A | Every control exposes its name/role/state to assistive tech — aria-label on icon-only buttons (the thumbs, the stop square) |
| 4.1.3 Status Messages | AA (new in 2.1) | Status updates ("answer complete", "3 sources found", error cards) are announced via role="status"/aria-live without moving focus |
8.2 The AI-specific accessibility problems#
WCAG gives you the rules; AI UX gives you the new failure modes:
Streamed text and screen readers. The naive approach — aria-live on the streaming container — makes a screen reader announce every token, which is unusable (hundreds of interruptions per answer). The correct pattern, per the WAI-ARIA Authoring Practices Guide (the alert pattern's implicit aria-live="assertive" is the model for errors, not for streams):
- Stream into a container that is not a live region during generation.
- Announce completion once: when
donearrives, set a visually-hiddenrole="status"/aria-live="polite"element to "Answer complete" (or focus moves to the answer's heading if the user asked for it). - Offer a "read aloud" / TTS path for users who want the content read — but never auto-play audio (WCAG 1.4.2 Audio Control).
- Reasoning/thinking panels: collapsed by default, announced as "reasoning available" not read verbatim.
Focus management when content arrives. New messages, error cards and approval dialogs must move focus deliberately: an error that appears should receive focus or be announced (4.1.3); a new assistant message should not steal focus mid-typing (the user is still composing their next message). The rule: announce, don't hijack — aria-live for things the user didn't ask for, focus management only for things they did (a dialog they opened, an error blocking their action).
Reduced motion. The typing-caret blink, the smooth-scroll-to-bottom, the skeleton shimmer, the "thinking" pulse — all must respect prefers-reduced-motion. A streaming answer that types character-by-character for effect is decoration, not information; under reduced-motion it should appear at a readable cadence or instantly. (The smoothing algorithms in 13A.2 are a pacing choice, not an animation — but any visual tweening on top of them is motion.)
Colour and contrast. Don't encode state in colour alone (1.4.1 Use of Color): the "AI" badge, error severity, citation presence and degraded-mode banner each need an icon or text label too. The confidence/quality indicators from 13A.3 must be perceivable without colour vision.
Cognitive load and plain language. AI features attract exactly the users who struggle with dense UI: older adults, cognitive disabilities, second-language speakers, stressed users. Plain-language principles apply double here because the content itself is probabilistic — jargon in the copy ("the model's confidence is low") should be "I'm not sure about this answer". WCAG 3.1.5 Reading Level (AAA) is the formal version; the practical rule is: write failure copy at an eighth-grade reading level and test it.
Voice features. Every audio output needs a text equivalent — captions for voice agents, transcripts for TTS readouts (09.10, 2.4 states it flatly: "every media artefact needs a text equivalent, and every audio output needs a text equivalent"; 09.5, 13.3 makes the TTS side concrete — "always ship captions/transcripts alongside, you have the text — it's free"). Live captions come free-ish from the streaming STT pipeline (09.4, Part 10); expose them. And speech input is itself an accessibility feature — dictation users, motor-impaired users — so a mic button that fails silently is an accessibility bug, not a nice-to-have.
8.3 a11y_lint.py: the checklist as code#
Accessibility checklists fail the same way security checklists fail — they're documents nobody runs. This linter applies the Part 8 rules to a UI spec (a JSON description of your components and their promised behaviours), the same discipline as 11C.4's readiness.py:
"""ai_product/a11y_lint.py — lint a UI spec JSON against the lesson-13.4 checklist.
Lesson 13A.4. Stdlib only. The input is a *spec*, not pixels: a list of
component dicts describing what each interactive element promises
(keyboard path, focus handling, live-region politeness, labels, motion,
media equivalents). lint_spec() returns violations a reviewer can act on —
the same discipline as 11C.4's readiness.py, applied to accessibility.
"""
from __future__ import annotations
import json
import sys
# rule id -> (what to check, how to fix). Each component dict may set these
# boolean/string fields; anything absent is treated as NOT DONE (fail-closed
# for gate items, matching the readiness checklist's philosophy).
_RULES = {
"KB-01": ("keyboard", "every interactive element is reachable and operable by keyboard"),
"FOCUS-01": ("focus_visible", "a visible focus indicator exists (:focus-visible)"),
"FOCUS-02": ("focus_not_obscured", "new content does not cover the focused element (WCAG 2.4.11)"),
"LIVE-01": ("live_region", "dynamic updates use an aria-live region with a sane politeness"),
"LIVE-02": ("live_politeness", "politeness is 'polite' for streamed text, 'assertive' only for errors"),
"NAME-01": ("accessible_name", "every control has an accessible name (aria-label/labelledby/text)"),
"CONTRAST-01": ("contrast_checked", "text/background pairs meet 4.5:1 (WCAG 1.4.3)"),
"TARGET-01": ("target_size_ok", "interactive targets >= 24x24 CSS px (WCAG 2.5.8)"),
"MOTION-01": ("reduced_motion", "animations respect prefers-reduced-motion (WCAG 2.3.3)"),
"MEDIA-01": ("text_equivalent", "audio/video outputs have a text equivalent (captions/transcript)"),
"TIME-01": ("no_timing_trap", "no essential task requires a timed response without a way to extend"),
"LANG-01": ("language_declared", "page language is declared; parts in other languages are marked"),
}
# Components that stream or update text must announce politely, not assertively.
_STREAM_KINDS = {"streaming_text", "chat", "live_caption", "progress"}
_ERROR_KINDS = {"error_banner", "alert"}
def lint_spec(spec: dict) -> list[dict]:
"""spec = {"components": [ {"id": ..., "kind": ..., ...fields...}, ... ]}
Returns a list of {"component", "rule", "problem", "fix"} dicts."""
violations: list[dict] = []
components = spec.get("components", [])
if not components:
return [{"component": "<spec>", "rule": "SPEC-01",
"problem": "no components declared", "fix": "add a components list"}]
# Components whose content changes without user action need live regions.
_DYNAMIC_KINDS = {"streaming_text", "chat", "live_caption", "progress",
"status_message", "result_list", "toast"}
for c in components:
cid = c.get("id", "<unnamed>")
kind = c.get("kind", "")
interactive = c.get("interactive", True)
dynamic = kind in _DYNAMIC_KINDS or c.get("emits_updates", False)
for rule_id, (field_name, fix) in _RULES.items():
if rule_id in ("LIVE-01", "LIVE-02", "MEDIA-01"):
continue # handled below with kind-aware logic
if not interactive and rule_id in ("KB-01", "FOCUS-01", "FOCUS-02",
"TARGET-01", "NAME-01"):
continue
if not c.get(field_name):
violations.append({"component": cid, "rule": rule_id,
"problem": f"missing/false '{field_name}'",
"fix": fix})
# kind-aware rules
if dynamic and not c.get("live_region"):
violations.append({"component": cid, "rule": "LIVE-01",
"problem": "dynamic content has no aria-live region",
"fix": "wrap updates in a region with aria-live"})
elif dynamic and kind not in _ERROR_KINDS \
and c.get("live_politeness") != "polite":
violations.append({"component": cid, "rule": "LIVE-02",
"problem": "streamed text must announce politely, not per-token",
"fix": "aria-live='polite'; announce completion, not every delta"})
if kind in _ERROR_KINDS and c.get("live_politeness") not in ("assertive", "polite"):
violations.append({"component": cid, "rule": "LIVE-02",
"problem": "error states need assertive or polite announcement",
"fix": "role='alert' or aria-live='assertive' for errors"})
if kind in {"audio", "video", "voice_output"} and not c.get("text_equivalent"):
violations.append({"component": cid, "rule": "MEDIA-01",
"problem": "audio/video has no text equivalent",
"fix": "ship captions + a transcript (09.4/09.5 outputs)"})
return violations
def main(path: str) -> int:
spec = json.loads(open(path).read())
violations = lint_spec(spec)
print(f"{len(spec.get('components', []))} components, {len(violations)} violations")
for v in violations:
print(f" [{v['rule']}] {v['component']}: {v['problem']} -> {v['fix']}")
return 1 if violations else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "ui_spec.json"))The spec it lints is a plain JSON file — here is the deliberately flawed three-component spec (chat stream, send button, voice note) that produced the output below:
{
"components": [
{"id": "chat-stream", "kind": "streaming_text", "keyboard": true,
"focus_visible": true, "focus_not_obscured": true, "live_region": true,
"live_politeness": "assertive", "accessible_name": true,
"contrast_checked": true, "target_size_ok": true, "reduced_motion": true},
{"id": "send-btn", "kind": "button", "keyboard": true,
"focus_visible": true, "accessible_name": true},
{"id": "voice-note", "kind": "audio", "text_equivalent": false}
]
}Read the spec as the checklist made concrete: chat-stream declares almost everything but announces with aria-live="assertive" (per-token interruptions — the LIVE-02 violation) and omits the timing/language fields; send-btn declares only the basics; voice-note is audio with no text equivalent. Real output (uv run python a11y_lint.py ui_spec.json; it exits 1 when violations exist, so it can gate CI):
3 components, 19 violations
[TIME-01] chat-stream: missing/false 'no_timing_trap' -> no essential task requires a timed response without a way to extend
[LANG-01] chat-stream: missing/false 'language_declared' -> page language is declared; parts in other languages are marked
[LIVE-02] chat-stream: streamed text must announce politely, not per-token -> aria-live='polite'; announce completion, not every delta
[FOCUS-02] send-btn: missing/false 'focus_not_obscured' -> new content does not cover the focused element (WCAG 2.4.11)
[CONTRAST-01] send-btn: missing/false 'contrast_checked' -> text/background pairs meet 4.5:1 (WCAG 1.4.3)
[TARGET-01] send-btn: missing/false 'target_size_ok' -> interactive targets >= 24x24 CSS px (WCAG 2.5.8)
[MOTION-01] send-btn: missing/false 'reduced_motion' -> animations respect prefers-reduced-motion (WCAG 2.3.3)
[TIME-01] send-btn: missing/false 'no_timing_trap' -> no essential task requires a timed response without a way to extend
[LANG-01] send-btn: missing/false 'language_declared' -> page language is declared; parts in other languages are marked
[KB-01] voice-note: missing/false 'keyboard' -> every interactive element is reachable and operable by keyboard
[FOCUS-01] voice-note: missing/false 'focus_visible' -> a visible focus indicator exists (:focus-visible)
[FOCUS-02] voice-note: missing/false 'focus_not_obscured' -> new content does not cover the focused element (WCAG 2.4.11)
[NAME-01] voice-note: missing/false 'accessible_name' -> every control has an accessible name (aria-label/labelledby/text)
[CONTRAST-01] voice-note: missing/false 'contrast_checked' -> text/background pairs meet 4.5:1 (WCAG 1.4.3)
[TARGET-01] voice-note: missing/false 'target_size_ok' -> interactive targets >= 24x24 CSS px (WCAG 2.5.8)
[MOTION-01] voice-note: missing/false 'reduced_motion' -> animations respect prefers-reduced-motion (WCAG 2.3.3)
[TIME-01] voice-note: missing/false 'no_timing_trap' -> no essential task requires a timed response without a way to extend
[LANG-01] voice-note: missing/false 'language_declared' -> page language is declared; parts in other languages are marked
[MEDIA-01] voice-note: audio/video has no text equivalent -> ship captions + a transcript (09.4/09.5 outputs)The spec-driven approach has a honest limit: it lints declared intent, not rendered reality — a component can claim contrast_checked: true and still fail. Pair it with real audits (keyboard-only traversal, a screen-reader pass, axe/Lighthouse runs) — the linter catches the omissions, the audit catches the lies.
What this means for you as an engineer. Accessibility for AI features is 80% the same discipline as for any web app (WCAG 2.2, semantic HTML, keyboard paths) and 20% genuinely new (streamed-text announcement strategy, focus-vs-announce decisions, media equivalents). The new 20% is where AI products fail audits — because nobody thought about what a screen reader should hear while tokens stream. Design the announcement strategy with the event contract, not after.
Part 9: Internationalisation and localisation#
Deep-dive
9.1 The multilingual quality gap is a UX problem#
AI features fail users differently across languages, and the failures are invisible to English-only testing:
- The token tax. 02.2, Part 8 measured it on real tokenizers: the same sentence cost 0.7–1.6× the English tokens on
o200k_baseacross ten languages (Tamil worst at 1.6×, Chinese cheapest at 0.7×), but on older or smaller-vocabulary tokenizers the tax is severe — Tamil cost 12.9× on GPT-2 and 6.3× oncl100k_base, Hindi 3.2× oncl100k_base. Consequences users feel: slower answers (decode is per-token), earlier truncation (max_tokensfills faster), higher cost per answer, and smaller effective context windows. A Hindi user's "long conversation degrades sooner" isn't a bug — it's arithmetic. And 02.2's caveat applies doubly here: treat any single sentence as an illustration, not a benchmark — measure on your own users' text before budgeting. - Quality asymmetry. Models are strongest in English and the languages of their training mix. Safety refusals, instruction-following and nuance degrade unevenly — a feature that works in English may refuse or confabulate more in Tamil or Arabic. Test the failure states per language, not just happy-path answers (02.2, 8.4).
- Code-switching. Real users mix languages mid-sentence (Hinglish, Singlish, Spanglish). Models tuned for monolingual input degrade quietly; the UI should expect it, not assume clean input.
9.2 The localisation checklist#
| Area | What breaks | What to do |
|---|---|---|
| Text expansion | Translated strings typically run ~30% longer on average, and much more for short UI strings — buttons overflow, chips wrap | Design for expansion; test the longest locale, not English; truncation is a failure state too |
| RTL / bidirectional | Arabic, Hebrew, Urdu flip layout; mixed-direction text (English product names inside RTL sentences) breaks naive rendering | Use logical CSS properties (margin-inline-start, not margin-left); dir="auto" on user/model content; test with actual RTL strings, not just dir="rtl" on the page |
| Locale formats | Dates, times, numbers, currency, units differ — "03/04" means March 4 or April 3 | Intl.* APIs / locale-aware formatting everywhere; never hand-format; the model's output also needs locale-aware formatting instructions in the prompt |
| Language detection & reply policy | User writes in Hindi; model replies in English (or vice versa) | Detect input language (cheap classifier or the model's own signal); reply in the user's language; state the policy once ("I reply in the language you write in") — 09.10, 2.5 covers the per-language nuance |
| UI copy vs model output | Two different translation problems: your strings (catalogue — Part 3) vs generated text (the model's answer language) | Translate the catalogue; steer the model via prompt + output-language instruction; never machine-translate a live answer through a second pipeline (compounds errors, leaks content to a third service) |
| Register / formality | Formality levels differ — a casual "Hey!" register that works in English reads rude in Japanese or German | Per-language register review; 09.10, 2.5 |
| Cultural assumptions | Examples, colours, gestures, holidays, names carry different meanings | Localise examples and imagery; brand-safety review per locale (09.10, 2.5); don't assume Western defaults in prompts either |
| Fonts & scripts | Non-Latin scripts need font coverage; emoji and combining marks break naive truncation | Font stack with script coverage; grapheme-cluster-safe truncation (never cut mid-emoji or mid-combining-sequence); 02.2's byte-level tokenisation explains why Indic scripts cost more |
9.3 The failure-state angle#
Internationalisation changes which failures users hit: the rate-limit countdown copy must format numbers per locale; "try again in 30 s" in a locale with different plural rules needs real pluralisation (not s/no-s); RTL layouts flip where the error card's action buttons sit; and the degraded-mode banner in an unsupported language is worse than no banner — ship the banner in the locales you support, and don't offer the feature in locales you don't (a half-localised AI feature fails users twice: wrong language, then wrong behaviour).
What this means for you as an engineer. i18n for AI features is three layers: the catalogue (Part 3's copy_catalog.py — complete per locale or honest fallback), the formats (Intl everywhere, RTL-aware layout), and the model layer (per-language quality testing, reply-language policy, token-cost awareness). The failure modes of layer 3 are the ones nobody tests until a user in Lagos or Lahore hits them — so test them before launch, in the languages your users actually write.
Part 10: Real devices and networks#
Reference
10.1 The constraint stack#
AI features run on devices and networks that deterministic apps never worried about, because AI features are heavy: large uploads, long streams, battery-hungry rendering, background-tab throttling.
| Constraint | What the user experiences | Design response |
|---|---|---|
| Mobile | Small screens, thumb reach, on-screen keyboard covering half the viewport, interruptions (calls, app-switch) | Composer stays pinned above keyboard; messages reflow; actions reachable one-handed; state survives interruption (09.10, 2.3) |
| Low bandwidth | A 12 MP photo is 3–8 MB; on 3G that dominates everything | Client-side resize/compress before upload (03.6, 6.1); "low quality" path; text-first fallbacks for media |
| Flaky connections | Stream drops mid-answer; upload stalls at 80% | Resumable uploads (multipart); stream resume/continue (03.3, 7.5); offline queue with honest "will send when back" |
| Offline / resume | Train tunnel, dead zone, closed laptop | Detect navigator.onLine + actual reachability (it's a hint, not truth); queue submissions; show "offline — will retry" not a spinner; 03.3, 8.2 owns the retry semantics |
| Battery / background tabs | Browser throttles timers in background tabs; stream pauses; media drains battery | visibilitychange handling — pause non-essential work, resume cleanly; don't assume a stream survives backgrounding; warn before starting battery-heavy features (long TTS, video gen) |
| Large-file upload | A 200-page PDF, a 2-hour recording | Chunked/resumable upload with per-chunk progress ("uploading… 43%"); validate before upload (09.10's media_probe.py](../09-voice-and-multimodal/10-building-multimodal-products.md#13-validate-before-you-send)); size caps with a clear "too large — try X instead" ([warn.too_large`) |
10.2 Perceived performance under constraint#
The same latency-engineering from 13A.2 applies, but the budget shrinks: on a slow connection, streaming hurts if chunks arrive in bursts with long gaps — a buffered-then-dumped answer feels worse than a spinner with honest progress. The rules:
- Show progress that reflects reality: "uploading…", "analysing…", "writing…" — stage labels from the 13A.2 progress contract, not a generic spinner.
- Adapt to measured bandwidth: if the stream is delivering <1 token/2s, switch to a "still working" state rather than a stuttering trickle (13A.2's perceived-speed thresholds).
- Graceful text degradation: on very poor connections, offer the non-streamed answer or a summary first — perceived speed beats technical purity.
10.3 What this means for you as an engineer#
Device/network constraints are assumptions to encode in the feature brief, not edge cases to discover in support tickets. For each feature: what's the largest upload, the longest stream, the worst network you promise to support? Write the degraded-network behaviour next to the degraded-mode table from Part 5 — "on a flaky connection, the answer streams when it can and offers a text summary when it can't" is a designed state, not an apology.
Part 11: UX research and testing for AI features#
Deep-dive
11.1 The methods, mapped to what they find#
| Method | What it finds | Cost | When |
|---|---|---|---|
| Think-aloud usability sessions | Where users misunderstand failure states, abandon, or misread copy | Medium — recruit 5–8 per round | Before launch, on the failure-state prototypes |
| Wizard-of-Oz | Whether the concept works before you build the backend — a human plays the model | Low-medium — no model needed, just a chat UI + a person | Early; perfect for this lesson's failure states (you can be every failure on demand) |
| Diary studies | Long-conversation degradation, trust erosion over weeks, how failures compound in real use | High — weeks of participant time | For agent/long-running features post-launch |
| Log review / session replay | What failures actually happen at scale, which states users hit, where they drop | Low — you have the data | Continuously; 12.4's privacy rules govern what you may record |
| Red-team-style usability probes | Adversarial inputs that break the UX — injection-shaped prompts, boundary-pushing requests, malformed uploads | Medium — reuse 12.8's test-case matrix for UI probes | Pre-launch and on model/prompt changes |
| A/B / experiment | Whether a copy or recovery change moves task success | Medium — needs traffic | Post-launch, via 13A.6 |
11.2 What to measure (and what to hand to 13A.6)#
This lesson designs the states; 13A.6 owns the metrics. The ones that belong to failure UX:
- Task success rate — did the user complete their goal, including via a recovery path? A user who hits a rate limit, waits, retries and succeeds is a success — count it.
- Recovery rate — of users who saw a failure state, what fraction completed anyway (via retry, degraded mode, human handoff)? This is the metric that says whether your failure UX works.
- Time-to-recovery — from failure shown to task resumed/completed.
- Abandonment-at-failure — the dark metric: users who saw a failure state and left. Segment by failure family — a spike in
blocked.safetyabandonment may mean your safety copy is too alarming or your false-positive rate is too high. - Edit/acceptance rates — for generative features: how often users accept vs edit vs regenerate vs abandon output — the accept/edit/regenerate funnel 13A.6 aggregates into acceptance rate.
- Time saved per task — the effort or handle-time delta versus the human/baseline process the feature replaces; the metric that justifies the feature's existence (13A.6 owns the economics).
- Clarifying-question cost — questions asked per task, and the task-success delta vs guessing. Too many questions = interrogation-loop regression.
11.3 The honest-sample rules#
- Five users find most of the problems — Nielsen and Landauer's 1993 model, which averages about 31% of problems found per user and so reaches roughly 85% at five users, when users and tasks are similar. Treat it as a rule of thumb (it is contested for varied user groups and complex products), but the practical advice stands: for qualitative problem discovery, several small rounds beat one big study. For quantitative claims ("recovery rate is 40%"), you need hundreds of sessions — don't claim percentages from five people.
- Recruit for the failure, not the happy path. Your participants should include the users most likely to hit failures: non-native speakers, low-bandwidth users, screen-reader users, elderly users. A usability study of English-fluent desktop users on fibre tells you almost nothing about your failure states.
- Consent and PII in research sessions. Recorded sessions, screen captures and think-aloud audio are personal data — 12.4 governs: consent before recording, redact PII in clips used for stakeholders, retention limits on session recordings, and never feed raw session recordings into eval sets without scrubbing (12.4, Part 8).
- Synthetic and canary data only for adversarial probes — 12.8's rule: never probe the UX with real user data; use canaries and
example.comfixtures.
What this means for you as an engineer. Failure UX is testable the same way everything else is: prototype the states (Wizard-of-Oz makes this trivial — you are the failure), watch real users hit them, instrument recovery in production, and feed every observed failure back as an eval case (08A.14's regression-from-production-failures loop). The failure states you didn't test are the ones that become your support tickets.
11.4 Where you'll use this#
- 13B.1 Capstone planning: the failure-state map is the first artefact your feature brief needs — write the sixteen families into the risk register before any code.
- 13B.2 Support copilot:
from_outcome/from_transport/from_policywired into the stream endpoint, the copy catalogue per locale,markdown_safetyon every rendered answer. - 13B.3 Document intelligence: partial-extraction states ("3 of 5 fields — the totals row failed"), the review queue's failure copy, sanitised citations.
- 13B.5 Voice agent: spoken failure states need the same taxonomy — a refusal read aloud is still a refusal; captions/transcripts are the accessibility contract.
- 13B.6 Shipping: the pre-launch checklist below is a launch gate;
a11y_lintruns against the UI spec in CI. - 13A.6 Metrics: recovery rate, abandonment-at-failure and time-saved feed the north-star and guardrail metrics.
What this means for you as an engineer: failure states aren't a polish pass at the end — they're an interface contract you design before the pixels. The mapper, the catalogue, the sanitiser and the linter are small files; the discipline is writing the failure families into the brief on day one.
Pre-launch failure-UX checklist#
Copy this into your PRD or launch review. Every item traces to a part of this lesson — a feature that can't tick them all isn't ready to ship its failure states.
- Failure map written — every family in the Part 1 gallery has a detection signal, a
UserMessageand a recovery path for this feature (Parts 1–2). - Mapper coverage —
failure_ui.py's three maps cover every signal your server can emit; unknown signals fall through toerror.unknown, never silently (Part 3). - Copy reviewed — every
copy_keyresolves in every shipped locale; failure copy passes the bad-vs-good table (specific, blameless, no jargon, actions first, WCAG 3.3.1/3.3.3) (Parts 3, 9). - No internals on screen — no provider names, stack traces, prompt fragments or model IDs in user-facing messages; a trace ID appears only as a short, copyable support reference (Part 3 warning).
- Retry honesty —
retryable=Trueonly where retry can succeed; refusals, blocks and quota never offer blind retry; rate limits show theRetry-Aftercountdown (Part 4). - Work preserved — drafts, inputs and partial answers survive every failure; a
resetclears everything shown before a retry (Part 4). - Degradation labelled and rehearsed — every fallback rung has a
degraded=Truebanner at the right disclosure level, and you've killed the primary in staging to watch it serve (Part 5). - Clarify cheaply — at most one clarifying question per turn, chips or a form rather than open text, an escape hatch on every question (Part 6).
- Empty states designed — suggested prompts, templates or recent items for first run; "searched X, found nothing" for empty retrieval (Part 6).
- Output sanitised — model text passes
nh3/llm_guard_kit(notbleach) at every boundary where it becomes markup; the sanitiser's fire-rate is logged (Part 7). - Accessibility spec lints clean —
a11y_lint.pypasses on the UI spec; a keyboard-only and one screen-reader pass are done; streamed text announces completion, not tokens (Part 8). - Locales tested — failure states exercised in each shipped language; RTL layout checked; catalogue fallback counter watched (Part 9).
- Worst-case network specified — largest upload, longest stream and flaky-connection behaviour written next to the degraded-mode table (Part 10).
- Recovery instrumented — recovery rate, time-to-recovery and abandonment-at-failure segmented by failure family are in the metrics plan (Part 11).
Common misconceptions#
| Misconception | Reality |
|---|---|
| "The model returned an error, so I show an error page." | Most AI failures arrive as fluent HTTP 200s — refusals, blocks, truncation, empty output. check_response() exists precisely because the transport layer lies about content failures. Design for outcome signals, not just exceptions. |
| "A refusal is a bug — retry it." | A refusal is an answer. Retrying produces the same refusal (and burns tokens). retryable=False on the message is a policy decision, not an oversight. |
| "Say 'sorry' and apologise profusely." | Over-apologising reads as insincere or as hiding something worse. Honest, specific, blameless copy beats theatre every time. |
| "If the fallback model answers, the user doesn't need to know." | Silent degradation is the cardinal sin — the user can't calibrate trust in an answer they can't tell apart. Label degraded paths where the user might notice. |
| "Ask the user to clarify whenever anything is ambiguous." | Clarifying has a cost — interrogation loops are worse than stated assumptions. One question per turn, tappable options, always an escape hatch. |
| "Sanitise the HTML once, at the API boundary." | Model text crosses multiple renderer boundaries (your app, a CMS, a mail client, a PDF export). Sanitise at each boundary where your code hands text to someone else's parser. |
| "Streaming text into an aria-live region makes it accessible." | It makes it unusable — a screen reader announcing every token is hundreds of interruptions. Announce completion once; stream into a non-live container. |
| "Accessibility is a nice-to-have for AI features." | WCAG 2.2 applies in full — and the AI-specific parts (streamed announcements, focus-vs-announce) are where products actually fail audits. It's a feature requirement, like 09.10, 2.4 says. |
| "English testing covers the failure states." | The token tax, RTL layouts, pluralisation rules, register differences and per-language safety behaviour all change which failures users hit. Test failure states in the languages your users write. |
Key takeaways#
- Failure is a designed state, not an exception. Every user-facing failure maps one of three signal vocabularies — transport errors (03.8), outcome statuses (
check_response()), and your own policy signals — to a typedUserMessagewith severity, copy key, actions and retryability. The UI never sees a raw exception,stop_reasonor HTTP status. - The taxonomy is a routing table. Confidently-wrong, partially-right, refusal, safety-block, empty, ambiguous, timeout, rate-limit, outage, tool-failure, stale-source, truncated, injection-affected, quota, off-topic and context-degraded each have a designed state — detection signal, message, recovery path, metric label.
- Copy craft is the deliverable. Specific over generic, no blame, no jargon, no false apologies or certainty, actions before diagnosis, and "what we preserved" stated honestly. The bad-vs-good table in Part 3 is the reusable artefact.
- Recovery paths are policy, not plumbing. Retry only what can succeed; Continue/Regenerate for truncated or unsatisfying answers; Rephrase for refusals and blocks; Switch-mode for outages and caps; Human for the failures that need one. Preserve user work — drafts, partial answers, completed steps — through every failure.
- Degradation must be labelled. The 11C.3 ladder from fallback model to honest failure only works if the user can tell which rung served them. Silent degradation is worse than failing.
- Clarify cheaply, guess honestly. One question per turn, chips over open text, stated assumptions over silent guesses, and an escape hatch on every question.
- Model output is untrusted markup. Images, links (all three syntaxes), raw HTML,
javascript:URLs and reference-style definitions are exfiltration and XSS channels — sanitise at every render boundary. Production:nh3(v0.3.7, verified Nov 2026), notbleach(unmaintained). - Accessibility is a contract. WCAG 2.2 (W3C Rec, Dec 2024) applies fully; the AI-specific work is the streamed-text announcement strategy (announce completion, not tokens), deliberate focus management, reduced-motion respect, and text equivalents for every audio/video output.
- i18n is three layers. The copy catalogue (complete per locale or honest fallback), locale-aware formats and RTL layout, and per-language model quality testing — the failure modes hide in layer 3.
- Devices and networks are assumptions, not edge cases. Encode the worst network, largest upload and background-tab behaviour into the feature brief alongside the degraded-mode table.
- Test the failure states, not just the happy path. Wizard-of-Oz makes every failure free to prototype; log review and red-team-style probes find the ones you didn't imagine; recovery rate is the metric that says whether it worked.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Failure state | Any designed UI condition produced when an AI feature cannot serve the request as normal; rendered from a UserMessage. |
| Signal vocabulary | One of the three input languages to the failure mapper: transport Kinds, check_response() Status names, or product policy signals. |
| Severity | The UserMessage field (info/warning/error/blocked) that drives presentation, separate from the copy. |
| Degradation ladder | The ordered fallbacks from 11C.3: fallback model → smaller model → cached → retrieval-only → queued → honest failure. |
| Silent degradation | Serving a fallback/cached answer indistinguishable from a primary one; the cardinal sin. |
| Clarifying question | A single, structured ask for missing information, rendered as chips/form/options rather than open chat. |
| Abstention | The pipeline's decision that the corpus cannot answer (07.4); distinct from a model refusal. |
| Copy catalogue | The locale-keyed string table (copy_catalog.py) that all user-facing failure copy resolves through. |
| Live region | An aria-live container that announces dynamic updates to screen readers; for streams, announce completion not tokens. |
| Token tax | The extra tokens (cost, latency, context) non-English text costs on a given tokenizer (02.2, Part 8). |
Exercises#
Exercise 1: Write copy for ten failure states#
Using the bad-vs-good table in Part 3 as your model, write the full five-part message (what happened / why / what you can do / what we preserved / where to get help) for these ten states: timeout mid-stream, rate limit with Retry-After: 45, provider 503, safety block on a false positive, truncated structured output, empty retrieval result, ambiguous "book it" request, quota exhausted, injection-suspect link removed, long-conversation degradation warning. For each, state the severity and whether retryable should be true. Then swap in your copy_catalog.py keys and check every copy_key resolves.
Exercise 2: Map twelve provider errors from 03.8#
Take the twelve provider error shapes catalogued in 03.8, 10.1 (OpenAI incomplete/content_filter, Anthropic refusal/max_tokens, Gemini prompt_feedback.block_reason/SAFETY finish, OpenRouter provider_overloaded/native_finish_reason, etc.). For each, write the check_response() or from_transport/from_policy call that maps it to a UserMessage, and justify the severity and actions. Which two are the easiest to get wrong, and why?
Exercise 3: Design a degraded mode#
Pick one feature from your 13A.1 feature brief (or invent one: a docs assistant, an invoice extractor, a voice-note summariser). Design its degraded mode end-to-end: which rung of the 11C.3 ladder serves each failure family, what the user sees at each rung, the disclosure level (always/subtle/none per Part 5.2), and the UserMessage keys. Write the degraded-mode row into a mock readiness checklist item.
Exercise 4: Audit a wireframe against WCAG#
Take any AI-feature wireframe (yours or a competitor's — a chat UI, a voice agent, a document review screen). Walk the Part 8.1 WCAG 2.2 table criterion by criterion and mark pass/fail/unknown for each. Then run the a11y_lint.py rules mentally against each component: which components would fail LIVE-02 (streamed text announced per-token)? Which lack a text equivalent for audio? Write the three worst violations as a bug list with the WCAG criterion and the fix.
Exercise 5: Run and break the mapper#
Run failure_ui.py against a status you invent (from_outcome("MYSTERY")) and against from_transport("RATE_LIMITED", retry_after_s=45). Then add a new policy signal "tenant_suspended" to _POLICY_MAP, add its copy key to copy_catalog.py, and write a three-line test that fails if any copy_key in the three maps is missing from the English catalogue.
Hints and model answers for the exercises
- Use the five parts as a template. Example for the rate limit with
Retry-After: 45: what happened ("Too many requests"), why ("The AI service asked us to slow down"), what you can do ("Retrying automatically in 45 seconds, or wait and press Try again"), what we preserved ("Your message is saved"), help (none needed). Severitywarning,retryable=True. Safety block on a false positive: severityblocked,retryable=False, actions rephrase and human. Truncated structured output: severitywarning,retryable=Falsefor the blind retry (offer Continue or Regenerate with a bigger cap, because the JSON is invalid until completed). Empty retrieval:info,retryable=False, with rephrase. Quota exhausted:blocked,retryable=False, upgrade or degraded mode. For the final check, loop overcatalogue_keys()and everycopy_key. - Easiest to get wrong: (a) the plain-words refusal under a normal
end_turnorSTOP, which no status check sees (only your own classifier or a refusal-phrase check can catch it, so expect false negatives), and (b) truncation with no visible text, which looks likeEMPTYbut is the reasoning budget being spent, so the right action is retry with more headroom rather than "the model had nothing to say". Others that trip people: OpenRouter errors that arrive inside a 200, and GeminiSAFETYas a finish reason versus a prompt block. - A good answer names a rung per family (outage: rung 3 or 4; quota: rung 5 or 6; timeout on interactive chat: rung 1 then 6), gives the banner text, sets disclosure to "always" for cached or retrieval-only answers, and writes a checklist line such as "Degraded mode for each failure family defined, labelled
degraded=True, and rehearsed in staging". - Typical findings: streamed text in an assertive live region (LIVE-02), icon-only buttons without accessible names (4.1.2), thumbs and chips under 24 px (2.5.8), status conveyed by colour only (1.4.1), no captions on voice output (MEDIA-01). A bug entry reads: criterion, component, what fails, the fix, and who verifies.
from_outcome("MYSTERY")falls through toerror.unknown(fail-visible).from_transport("RATE_LIMITED", retry_after_s=45)carriesretry_after_s=45on the message while the copy key stayswarn.rate_limited; the client passes it to the catalogue (resolve("en", "body.rate_limited", retry_after_s=45)) to fill the body line. A test:from ai_product.failure_ui import _OUTCOME_MAP, _TRANSPORT_MAP, _POLICY_MAP,from ai_product.copy_catalog import COPY, then assert everycopy_key(the second element of each map value) is inCOPY["en"]; it will catch a forgottentenant_suspendedstring.
Check yourself#
- Name the three signal vocabularies that feed a failure state, and give one example of each.
Transport errors (e.g.,
Kind.TIMEOUTfromllm_errors.py), outcome statuses (e.g.,Status.TRUNCATEDfromcheck_response()), and product policy signals (e.g.,cost_cap,degraded_mode,injection_suspectfrom your own code). - Why is a model refusal
retryable=Falsewhile a provider 503 isretryable=True?Retrying a refusal produces the same refusal — the model's answer won't change on a re-roll, and it burns tokens. A 503 is transient infrastructure failure where a retry can succeed.
retryableis a policy decision about whether retry can help, not a transport fact. - What's the difference between
severity=WARNINGandseverity=BLOCKEDin presentation?WARNING renders inline attached to partial/incomplete work (the user can still use what rendered); BLOCKED renders as a card explaining the refusal/block where retry isn't the primary action — it's an answer or a policy boundary, not an error to fix.
- When must you disclose that a fallback model served an answer?
When the degraded answer could mislead: cached/stale answers (freshness matters), retrieval-only (shape changed), high-stakes or regulated features, or any answer the user will act on. Same-tier fallback on low-stakes chat may be subtle — but never indistinguishable in a way that breaches data policy.
- What's the "one question per turn" rule and when do you break it?
Clarifying questions cost a turn of latency and attention — never chain them. Break it only when the missing information is structured enough to collect in a single form (chips + fields), which is one turn anyway. If you need three facts, ask once, not three times.
- Why are Markdown images the most dangerous output construct?
An image makes the reader's browser auto-fetch a URL — no click needed — and the URL can carry exfiltrated data in its query string (the Bing Chat/EchoLeak pattern). Links at least need a click; images fire on render. Strip by default or allow-list hosts.
- What's wrong with putting
aria-liveon the streaming container?A screen reader announces every DOM mutation — hundreds of token-level interruptions per answer, making the feature unusable. Stream into a normal container; announce completion once via a separate polite live region.
- Name two WCAG 2.2 criteria that are new in 2.2 and matter for AI UX.
2.4.11 Focus Not Obscured (Minimum) — the focused element can't be hidden by sticky composer/headers/toasts; 2.5.8 Target Size (Minimum) — 24×24 CSS px for thumbs-up/down, chips, citation links; also 2.4.13 Focus Appearance, 2.5.7 Dragging Movements, 3.2.6 Consistent Help and 3.3.7 Redundant Entry.
- How does the token tax change which failure states non-English users hit?
Non-English text costs more tokens per word on older/smaller-vocabulary tokenizers — answers truncate earlier (
max_tokensfills faster), streams decode slower, context windows effectively shrink, and per-language quality/refusal rates differ. A Hindi user's "long conversation degrades sooner" is arithmetic, not a bug. - What's the honest version of "the stream died at token 40"?
"Connection lost — your partial answer is saved" (
info.disconnected), with Continue/Retry/Regenerate offered, the partial text preserved and labelled, and — if content was shown — a visibleresetor "retrying" state so the retry doesn't silently duplicate (03.3, 7.5). - Why is "something went wrong, please try again" the worst possible failure message?
It's generic (doesn't say what happened or what to expect), offers no recovery path (is retry even likely to work?), implies nothing was preserved, and gives no way to escalate. Every good row in the bad-vs-good table is specific, honest, and actionable.
- What's the difference between abstention and refusal?
Abstention is your pipeline's decision that the corpus can't answer (07.4 — retrieval found nothing relevant); refusal is the model's decision not to answer (policy/safety). Different signals, different copy ("I searched X and found nothing" vs "I can't help with this"), different recovery paths.
- When should a clarifying question render as chips versus a form versus a stated assumption?
Chips for 2–4 discrete options; inline form for structured missing data (dates, IDs, amounts); stated assumption for low-stakes cases with an obvious default where a wrong guess is cheap to correct. Never open-ended "what did you mean?" when options exist.
- What does
degraded=Trueon aUserMessagetrigger in the UI?The degraded-mode banner/label — INFO severity, dismissible, once-per-episode — telling the user the answer came from a fallback/cached/retrieval-only path so they can calibrate trust. It's the mechanism that prevents silent degradation.
- Name three things a UX researcher should measure for failure states that aren't just "did it work."
Recovery rate (of users who saw a failure, how many completed anyway), time-to-recovery, and abandonment-at-failure segmented by failure family — plus edit/acceptance/regenerate rates on generative output and clarifying-question cost per task.
Further resources#
- Lesson 03.3: Streaming — the event contract, mid-stream errors, restart/continue/resume semantics this lesson's failure states ride on.
- Lesson 03.8: Errors and Retries — the provider error taxonomy,
check_response()outcome statuses, retry policy. - Lesson 04.7: Managing Context Over Time — long-conversation degradation mechanisms and fixes.
- Lesson 07.4: Grounded Generation — abstention, "I don't know", the retrieval-emptiness contract.
- Lesson 08A.14: Reliable and Safe Agents — agent failure taxonomy, human handoff, false-completion detection.
- Lesson 11C.3: Fallbacks, Gateways and Reliability — the degradation ladder, fallback provenance, data-policy constraints.
- Lesson 11C.4: Operating LLM Systems — degraded-mode design-time rule, readiness checklist, limitation notices.
- Lesson 12.2: Prompt Injection — the Markdown exfil channels,
llm_guard_kitsanitiser, detection layers. - Lesson 12.5: Guardrails and Output Validation —
nh3recommendation, output validation layers. - Lesson 12.8: Red Teaming — the test-case matrix for adversarial usability probes.
- Lesson 13A.2: AI UX I — Streaming, Latency and Perceived Speed — the event contract and progress states failure messages ride inside.
- Lesson 13A.3: AI UX II — Trust, Transparency and Control — confidence signals, feedback loops, approval queues the recovery paths link to.
- Lesson 13A.6: Metrics, Experiments and Unit Economics — the metrics this lesson's states feed.
- WCAG 2.2 — https://www.w3.org/TR/WCAG22/ (W3C Recommendation, 12 Dec 2024).
- WAI-ARIA Authoring Practices Guide — https://www.w3.org/WAI/ARIA/apg/ (live regions, alert patterns, focus management).
- Microsoft HAX Toolkit — https://www.microsoft.com/en-us/haxtoolkit/ai-guidelines/ (18 Human-AI Interaction guidelines, Amershi et al., CHI 2019).
- Google PAIR Guidebook — https://pair.withgoogle.com/guidebook (the Errors + Graceful Failures chapter; the chapter index is rendered by JavaScript, so read it in a browser, and check which edition you are reading).
- Apple HIG: Generative AI — https://developer.apple.com/design/human-interface-guidelines/generative-ai/.
nh3on PyPI — https://pypi.org/project/nh3/ (v0.3.7, MIT; ammonia bindings).- OWASP Top 10 for LLM Applications — https://genai.owasp.org/llm-top-10/ (the 2026 edition was published in August 2026; check the project page for the exact date and the current list).
The ai_product package so far#
Files introduced across the capstone to date (this lesson adds the last four; the consolidated tree lands in 13B.1):
ai_product/
feature_brief.py # 13A.1 — product discovery artefact
events.py # 13A.2 — the stream event contract
smoother.py # 13A.2 — perceived-speed token pacing
progress.py # 13A.2 — stage/progress states
approval.py # 13A.3 — human-in-the-loop approval gate
review_queue.py # 13A.3 — reviewer inbox
feedback.py # 13A.3 — feedback capture -> eval pipeline
failure_ui.py # 13A.4 — THIS LESSON: signal -> typed UserMessage
copy_catalog.py # 13A.4 — THIS LESSON: i18n copy catalogue
markdown_safety.py # 13A.4 — THIS LESSON: rendering-safety sketch
a11y_lint.py # 13A.4 — THIS LESSON: WCAG checklist linter← 13A.3 — AI UX II: Trust, Transparency, Feedback and Human-in-the-Loop | Module 13A overview | 13A.5 — Architecture Patterns for AI Applications →