Built as working context, not shelfware.
This resource is meant to be useful inside the tools where product work now happens: your codebase, your notes, and your AI-assisted workflow.
01
Paste the markdown into Claude, ChatGPT, Cursor, Codex, Gemini, or another AI agent as reusable project context.
02
Use it before a planning, implementation, review, or audit session so the agent has constraints, criteria, and working structure up front.
03
Adapt the sections to your product, team, or repo before asking the agent to execute against it.
Markdown previewai-interface-state-contract.md
# AI Interface State Contract
Use this before designing or implementing an AI-powered interface. It turns model and tool behavior into explicit product states that design, frontend, backend, analytics, accessibility, and QA can review together.
The contract is intentionally model-agnostic. Adapt the names to your product, but keep the distinctions. A single `loading` boolean is not enough for an experience that can stream, call tools, ask for input, return partial work, lose connection, or require review.
## 1. Product Context
```md
Feature:
Primary user job:
User decision supported:
Model or provider:
Tools the model can call:
Data the feature can access:
Actions the feature can take:
Highest-consequence outcome:
Manual path when AI is unavailable:
Owner:
Last reviewed:
```
## 2. State Inventory
Complete one row for every state the product supports. Delete states that truly do not apply; do not silently merge them into a generic error.
| State | What the system knows | What the user sees | Available control | Exit condition |
| --- | --- | --- | --- | --- |
| Idle | No request is active | Clear starting point and example input | Start, edit context | Valid request submitted |
| Validating | Input and permissions are being checked | Immediate local feedback | Edit, cancel | Input accepted or rejected |
| Queued | Work is accepted but not started | Queue or wait expectation | Cancel | Processing starts or times out |
| Generating | Model is working without visible tokens | Specific progress language | Cancel | First output, tool call, or failure |
| Streaming | Partial output is arriving | Stable, readable incremental content | Stop, pause, continue manually | Stream completes or breaks |
| Tool use | External data or action is in progress | Tool name and useful status | Cancel when safe | Tool returns, asks for auth, or fails |
| Needs input | The system cannot continue responsibly | Missing decision or context | Answer, edit, skip | Required input supplied |
| Partial | Some useful work completed | Completed and missing parts separated | Retry missing part, keep result | User accepts or retry completes |
| Low confidence | Output exists but evidence is weak | Uncertainty and reason near the claim | Review source, edit, regenerate | Human accepts, corrects, or rejects |
| Review required | Output cannot be applied automatically | Proposed change and consequence | Approve, edit, reject | Qualified reviewer decides |
| Complete | The requested result is ready | Result, provenance, and next action | Accept, edit, undo, start over | User continues or dismisses |
| Rate limited | Provider will not process now | Honest retry timing | Retry later, continue manually | Window resets or manual path used |
| Provider error | Upstream system failed | Preserved work and scoped explanation | Retry, switch path, report | Retry succeeds or user exits |
| Safety blocked | Policy or risk boundary stopped work | Boundary without unsafe detail | Edit request, appeal, use manual path | Request changes or review resolves |
| Offline | Network is unavailable | Local state and sync expectation | Retry, copy input, work manually | Connection returns |
## 3. Transition Map
Fill in the actual path. Keep failure and recovery transitions visible.
```text
idle
-> validating
-> queued -> generating -> streaming -> complete
-> needs_input -> validating
-> safety_blocked -> idle
generating
-> tool_use -> generating
-> partial -> review_required
-> provider_error -> retry -> generating
-> cancelled -> idle
complete
-> accepted
-> edited
-> rejected -> idle
-> undone -> idle
```
Review the map for loops. Every loop needs a limit, a visible explanation, or a human exit. An automatic retry that can run forever is not recovery.
## 4. Output Contract
Define the frontend payload independently from provider-specific response shapes.
```ts
type AiInteraction = {
requestId: string;
state:
| "idle"
| "validating"
| "queued"
| "generating"
| "streaming"
| "tool_use"
| "needs_input"
| "partial"
| "low_confidence"
| "review_required"
| "complete"
| "rate_limited"
| "provider_error"
| "safety_blocked"
| "offline";
output?: unknown;
preservedInput?: unknown;
progress?: { label: string; current?: number; total?: number };
tool?: { name: string; status: "pending" | "success" | "failed" };
confidence?: { level: "low" | "medium" | "high"; reason: string };
provenance?: Array<{ label: string; href?: string; retrievedAt?: string }>;
recovery?: Array<"retry" | "edit" | "copy" | "manual" | "contact_support">;
review?: { required: boolean; reason?: string; reviewerRole?: string };
error?: { code: string; safeMessage: string; retryable: boolean };
};
```
## 5. Copy Contract
Write the words before implementation for the states most likely to erode trust.
```md
Generating label:
Tool-use label:
Long-wait expectation:
Partial-result explanation:
Low-confidence explanation:
Review-required reason:
Provider-error message:
Preserved-work reassurance:
Manual-path label:
Safety-boundary message:
```
Avoid magical language such as "thinking" when the system is waiting on a queue or tool. Name the operation users can understand.
## 6. User Controls
- [ ] Input remains editable before the request begins.
- [ ] Cancel stops work or clearly explains why it cannot.
- [ ] Stop generation preserves the useful partial output.
- [ ] Retry states what will repeat and whether side effects can duplicate.
- [ ] Regenerate does not erase the accepted version without warning.
- [ ] Edit and accept are available near the generated result.
- [ ] Undo exists for consequential applied changes.
- [ ] The manual path remains available.
- [ ] Review status and reviewer role are visible when required.
## 7. Accessibility Contract
- [ ] State changes use an appropriate live region without announcing every token.
- [ ] Streaming output does not repeatedly steal focus.
- [ ] Stop, retry, approve, reject, and edit are keyboard reachable.
- [ ] Progress is communicated without color or animation alone.
- [ ] Reduced-motion settings disable decorative streaming effects.
- [ ] Tool calls and provenance have meaningful text labels.
- [ ] Error recovery is adjacent to the error and described programmatically.
- [ ] Focus moves only when the user's next action would otherwise be unclear.
## 8. Analytics Contract
Use product-language events. Do not log prompts, generated content, personal data, or tool payloads by default.
| Event | When it fires | Safe properties |
| --- | --- | --- |
| `ai_request_started` | Valid request accepted | feature, entry point, model class |
| `ai_state_changed` | Meaningful state transition | from, to, duration bucket |
| `ai_tool_called` | Tool work begins | tool class, permission mode |
| `ai_recovery_used` | User uses recovery | state, action, attempt count |
| `ai_review_decided` | Human approves or rejects | reviewer role, decision, edited |
| `ai_result_applied` | Result changes product state | action class, undo available |
| `ai_feedback_submitted` | User rates or labels result | label, workflow stage |
## 9. QA Scenarios
- [ ] Typical request reaches complete state.
- [ ] Slow first token shows a useful generating state.
- [ ] Stream stops halfway and partial work remains readable.
- [ ] Tool call requires new authentication.
- [ ] Tool succeeds but model follow-up fails.
- [ ] User cancels before and during a tool call.
- [ ] Retry cannot duplicate a consequential action.
- [ ] Low-confidence output exposes its reason.
- [ ] Review-required output cannot apply itself.
- [ ] Provider rate limit shows a realistic next step.
- [ ] Network disappears during streaming.
- [ ] Keyboard and screen-reader users can complete recovery.
- [ ] Long content and narrow screens do not hide controls.
## Worked Example: Support Reply Copilot
```md
Primary job: Draft a reply using the ticket and approved help-center content.
Highest consequence: Sending incorrect account or billing instructions.
Tool use: Search approved help-center articles.
Low confidence: No approved source supports the proposed answer.
Review required: Every reply before send.
Manual path: Write the reply without AI.
Preserved work: Agent notes and edited draft remain after provider failure.
Proof: Reviewer can identify sources, edit the draft, and send only after approval.
```
## Prompt For An AI Agent
```md
Use this AI Interface State Contract to review the feature described below.
1. Map the complete state machine.
2. Identify states currently collapsed into loading or error.
3. Define the user control and recovery path for each state.
4. Flag unsafe retries, hidden tool calls, and missing review boundaries.
5. Propose a frontend payload independent of the model provider.
6. Write acceptance criteria and QA scenarios.
7. Do not invent permissions, data access, or automatic actions.
Feature context:
[PASTE CONTEXT]
```