AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 22

    AI Product UX: Chat, Copilots and Workflow Interfaces

    TechLearningPro shipped a chat drawer on the lesson player.

    Course progress0%
    Focus
    22 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    AI-Powered Full Stack Development · Lesson 22 · AI and LLM Application Fundamentals

    Lesson Overview

    TechLearningPro shipped a chat drawer on the lesson player. The empty state said "Ask me anything." A learner typed "I'm done with this lesson," the assistant replied "You're all set — I've marked it complete," and the learner closed the laptop. PostgreSQL still showed the quiz as unstarted, so the Monday board was correct and the learner was not. A second experiment, an inline copilot, replaced the learner's notes with a full rewrite and offered no reject control. Support tickets that week were about trust, not about model quality.

    The model was doing what a chat surface invites: sounding finished. The interface had borrowed a messenger metaphor for a job that is closer to a scoped tool. This lesson designs three surfaces and the rules that keep them honest. Chat is a threaded conversation with memory of prior turns and a visible scope. Copilot is a proposal attached to a selection, accepted or rejected as a unit. Workflow is a form with named inputs and a typed result. All three render drafts. None of them is the quiz, the progress bar, or the certificate button.

    You will model UI state in TypeScript so a React player can stream tokens without confusing "the assistant is speaking" with "the lesson is complete." Streaming transport was covered in Streaming AI Responses with Server-Sent Events. Accessibility expectations sit beside Accessible UI Engineering and Design Systems. Safety labels and human approval sit beside Responsible AI, Safety and Human-in-the-Loop Design. Visual generation and file context come from Multimodal AI: Images, Audio and Documents. Broader product patterns for generative UI live in Generative AI. Agent consoles that request tools live in Agentic and must reuse the state machine you write here.

    Planning assumptions:

    • The lesson player is the primary surface. Chat is a side panel, not a second application.
    • A turn streams for a few seconds. The lesson text is already on screen.
    • Suggested prompts are a fixed list per lesson version, authored by the curriculum team.
    • Illustrative limits (turn length, history window) are product ratios. Measure them against token cost before you freeze them.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Choose chat, copilot, or workflow from the job the learner is doing.
    2. Name the scope of a panel in the interface: this section, this selection, or this form.
    3. Model UI state as a closed set: idle, streaming, stopped, failed, refused, ready.
    4. Keep that state distinct from lesson progress and quiz completion.
    5. Render a draft label, a stop control, and a retry that the user starts.
    6. Apply accessibility basics: named buttons, a polite live region, and visible focus.
    7. Represent a copilot result as a proposal with accept and reject, leaving the source text intact until accept.
    8. Represent a workflow as typed fields and a typed result, with an explicit submit.
    9. Limit history sent to the model to a window you can budget.
    10. Prevent a send on every keystroke.
    11. Show file and image context as attachments with the statuses from Lesson 21.
    12. Persist a thread id, tenant id, and prompt version without treating the thread as a source of truth for grades.
    13. Design empty, streaming, partial, and error views that still show the lesson.
    14. Hand off an R2 action from the panel to the human-review console instead of completing it in chat.
    15. Test the state machine without a browser and without a provider key.

    Prerequisites

    • You can read a TypeScript discriminated union.
    • You know the server owns the model call and the browser renders the result (Lesson 1).
    • You know streams can fail mid-flight (Streaming AI Responses with Server-Sent Events).
    • You know a draft must be labeled and a side effect needs a tier (Responsible AI, Safety and Human-in-the-Loop Design).
    • React knowledge helps you imagine the player. The state machine in this lesson is framework-free so you can test it in Node. UI components are specified, not bundled as a design-system release.

    What is AI Product UX?

    AI product UX is the set of screens, states, and words through which a person asks for model help and decides what to do with the result. It includes the panel layout, the buttons, the streaming behavior, the error text, and the promises the copy makes.

    Chat is a sequence of turns. It fits open questions about material the learner can already open: "Explain the second paragraph in simpler words." It accumulates context, which is useful and expensive.

    Copilot is a helper bound to a selection or a field. It fits "rewrite this note" or "explain this highlighted sentence." The original stays until the learner accepts a proposal. Accept writes the proposal into the notes draft. It does not write completion.

    Workflow is a named task with inputs and a result shape. It fits "Summarize the uploaded syllabus in five bullets" or "Draft a quiz comment for me to attach." The learner fills a form, submits once, and reviews a structured result. Workflows are the right shell when you need a specific outcome more than a conversation.

    The purpose of separating them is expectation. A messenger UI suggests that the assistant can do whatever the sentence asks. A workflow UI suggests that the product will do the labeled task. TechLearningPro uses chat for explanation, copilot for notes, and workflow for anything that might later touch a real button such as "Attach comment."

    Teams reached for a single chat box because it was fast to demo and because consumer chat products trained users to type. Enterprise products then discovered that "ask me anything" is an unbounded support contract. The design response is a scoped panel with a job title, a state machine, and copy that describes a draft.

    SurfaceLearner intentCommit behavior
    ChatUnderstand this sectionNo domain write
    CopilotChange a note they ownAccept updates the note draft
    WorkflowRun a named taskSubmit creates a result; R2 tasks open a review ticket
    Progress UISee quiz and completionWritten only by the quiz and progress APIs

    Why Do We Need It?

    A correct model call can still teach the wrong lesson if the chrome around it over-claims.

    text
    Unbounded chat
    |
    v
    Copy implies the assistant completed the lesson
    |
    v
    Learner leaves. Database disagrees.
    Support load rises.
    |
    v
    Scoped panel + state machine + draft label
    |
    v
    Streaming is visible.
    Stop works.
    Progress stays on the quiz.

    Benefits:

    • Learners can tell a draft from a grade.
    • Designers and engineers share one state union, so the button set is testable.
    • Token spend follows an explicit send, not a keyup handler.
    • Accessibility and failure states are part of the feature, not a polish pass.
    • Agent UIs later reuse the same "proposal then confirm" pattern (Agentic).

    Real World Example

    On the TechLearningPro player the right rail is titled "Explain this section." Suggested prompts are three curriculum-authored strings. The learner can type a question up to 500 characters. While tokens stream, a Stop button is visible and a polite live region updates the text. If the learner stops or the stream fails, the lesson column is unchanged. The progress chip still reads "Quiz not started" because that chip is bound to lesson_progress, not to the last assistant sentence.

    The notes field offers a copilot on a selection: "Simplify." The proposal appears under the selection with Accept and Reject. Reject leaves the notes untouched. Accept replaces the selection inside the notes draft and shows Undo.

    The instructor console uses a workflow card: lesson, rubric id, and a short observation. Submit returns a comment draft. Attach is a separate button that calls the R1 confirm path from Lesson 20. The card never says the comment is already on the learner's record.

    Consumer chat products (general-purpose assistants from major labs and suites) optimize for open conversation. Microsoft and Google office copilots optimize for a document selection and a tracked change. Amazon seller tools and banking dispute desks tend toward workflow forms because the downstream system needs fields, not a vibe. Netflix-style assistants that recommend a title still keep playback entitlement on a different control. TechLearningPro copies the scoped tool, and uses chat only where the job is explanation.

    Internal Working

    Chat send:

    1. The player checks local guards: non-empty text, under the character cap, and status is idle or ready. A keystroke does not send.
    2. The client assigns a clientTurnId and sets status to streaming.
    3. POST /api/tutor/turns includes the session cookie, lesson id, section id, the question, and the ids of the last few turns. It does not include a provider key.
    4. The server authorizes the section, builds the prompt from the excerpt plus the windowed history, and streams tokens.
    5. Each token appends to the assistant buffer. A Stop control aborts the fetch and sends POST /api/tutor/turns/:id/stop. The server closes the upstream call as best it can and records stopped.
    6. Terminal states are ready (completed draft), stopped, failed, or refused. The progress query is not invalidated by any of them.
    7. The thread row stores tenant, user, lesson version, prompt version, and turn ids. Body retention follows the tenant contract.

    Copilot:

    1. The selection must be non-empty and inside the notes field the user owns.
    2. The server returns a Proposal with baseText hash and proposedText.
    3. Accept applies the proposal only if the current selection hash still matches baseText. A mismatch returns stale_selection and leaves the notes as they are.
    4. Reject discards the proposal.

    Workflow:

    1. The form validates required fields in the client for fast feedback and again on the server.
    2. Submit is one POST. Double-clicks collapse on an idempotency key.
    3. If the workflow's action tier is R2, the result is a link to a review ticket, not a claim that the effect ran.

    Failure points: validation, auth, abort, timeout, refusal, stale selection, and a model body that fails schema checks. The lesson column renders throughout.

    Architecture

    flowchart TB
      subgraph player [Lesson player]
        Lesson[Lesson column and progress chip]
        Panel[Scoped AI panel]
        State[UI state machine]
      end
    
      subgraph api [TechLearningPro API]
        Auth[Session and lesson ACL]
        Tutor[Tutor turns]
        Notes[Notes proposals]
        Work[Workflow submit]
      end
    
      subgraph data [System of record]
        DB[(Threads notes progress)]
      end
    
      subgraph model [Model boundary]
        Port[Model port]
      end
    
      Panel --> State
      State --> Auth
      Auth --> Tutor
      Auth --> Notes
      Auth --> Work
      Tutor --> Port
      Tutor --> DB
      Notes --> DB
      Lesson --> DB
    text
    Learner
    |
    +--> types in a scoped panel
    | |
    | v
    | idle --send--> streaming --tokens--> ready
    | | |
    | | +--stop--> stopped
    | | +--error--> failed
    | | +--policy--> refused
    |
    +--> progress chip reads lesson_progress only
    UI statePrimary controlProgress chip
    idleSend, if the box has textUnchanged
    streamingStopUnchanged
    readyAsk another questionUnchanged
    stoppedRetryUnchanged
    failedRetryUnchanged
    refusedEdit questionUnchanged

    Deep Dive

    Scope in the chrome

    The panel title is the scope: "Explain this section," "Notes copilot," or "Quiz comment workflow." The placeholder repeats the scope. Suggested prompts are data from the lesson version, not a model call on page load. A prompt that would require another tenant's data is not in that list. If the learner types an out-of-scope request ("email my cohort"), the assistant draft can explain the limit, and the safety classifier still forbids the action. The copy avoids completion language. Preferred status text: "Draft ready." Avoid status text that claims the lesson, the quiz, or the grade changed.

    State machine

    The union is the contract between design and engineering. Illegal combinations stay unrepresentable: there is no streaming with a send button enabled, and there is no ready that sets completed: true. Transitions live in one function you can unit test. The React layer (or any other UI) dispatches events: send, token, stop, fail, refuse, finish, reset.

    Streaming and partial text

    Partial text is a draft in progress. Render it in a region with aria-live="polite" so a screen reader is not flooded on every token; batch announcements or announce on pause and on finish. The exact cadence can follow your design system's live-region guidance from Lesson 8. Show a text cursor or a "Writing" label that is not color alone. Stop must be a real button with an accessible name, keyboard reachable, and visible while streaming.

    History windows

    Send the current excerpt and a bounded number of prior turns, for example the last four messages or a character budget, whichever is smaller. Older turns remain in the transcript the learner sees if policy allows, and they stay out of the next prompt. The server enforces the window. The client may also trim to keep the request small. Put promptVersion and historyCount in the response metadata so evaluation can reproduce a bad answer.

    Copilot proposals

    A proposal is a value object: id, baseHash, proposedText, status: "open" | "accepted" | "rejected" | "stale". Accept is optimistic only in the sense that the UI can show a spinner. The server compares hashes. Undo stores the previous note body for one step. Undo is a notes operation. It is not a model call and it is not a grade change.

    Workflow cards

    Each workflow has an id (quiz_comment_draft, file_summary), a JSON schema for inputs, and a schema for outputs. The card renders fields from the schema. This is the same structured-output discipline as Structured Outputs, JSON Mode and Function Calling, visible as a form. The submit button names the task: "Draft comment." A second button, when the tier allows, names the commit: "Attach to attempt."

    Empty, busy, and error

    Empty: the panel shows the title, the scope sentence, and suggested prompts. Busy: streaming state with Stop. Error: the partial text remains if any tokens arrived, plus "Draft stopped" or "Draft unavailable," plus Retry. The lesson column, the nav, and the quiz entry stay interactive. A full-page spinner for a tutor failure is a defect.

    Cost and accidental sends

    Debounce does not belong on an implicit send. Send is a button or an explicit shortcut (Ctrl or Command plus Enter) documented in the field hint. Paste of a huge transcript is truncated client-side and rejected server-side over the cap, with a count of characters so the learner can edit. File attachments display name, kind, and the Lesson 21 status (stored, rejected, draft_ready). They do not auto-submit a model call when the upload finishes. The learner presses "Ask about this file."

    Persistence and identity

    threads and notes are keyed by tenant and user. A shared classroom display mode, if you offer one, uses a thread id that is not the private notes thread. The progress chip's query key does not include the thread. Cache invalidation for progress happens when the quiz service writes, which you can see because the AI panel never calls that mutation.

    Code Examples

    The slice lives in packages/ai-ux/src/. It is the state and proposal logic the player will call. It is not a CSS kit.

    Simple example: a closed set of panel states

    packages/ai-ux/src/types.ts

    typescript
    export type PanelStatus = "idle" | "streaming" | "ready" | "stopped" | "failed" | "refused";
    export interface ChatTurn {
    id: string;
    role: "learner" | "assistant";
    text: string;
    /** True while tokens are still arriving for this turn. */
    partial: boolean;
    }
    export interface PanelState {
    status: PanelStatus;
    turns: ChatTurn[];
    /** Progress is intentionally absent. This object cannot mark a lesson complete. */
    draftLabel: "Draft";
    }
    export type PanelEvent =
    | { type: "send"; turnId: string; text: string }
    | { type: "token"; turnId: string; text: string }
    | { type: "stop" }
    | { type: "fail" }
    | { type: "refuse" }
    | { type: "finish"; turnId: string }
    | { type: "reset" };

    packages/ai-ux/src/machine.ts

    typescript
    import type { PanelEvent, PanelState } from "./types.js";
    export function initialPanel(): PanelState {
    return { status: "idle", turns: [], draftLabel: "Draft" };
    }
    export function reducePanel(state: PanelState, event: PanelEvent): PanelState {
    if (event.type === "reset") return initialPanel();
    if (event.type === "send") {
    if (state.status === "streaming") return state;
    const text = event.text.trim();
    if (text.length === 0) return state;
    return {
    status: "streaming",
    draftLabel: "Draft",
    turns: [
    ...state.turns,
    { id: event.turnId, role: "learner", text, partial: false },
    { id: `${event.turnId}-a`, role: "assistant", text: "", partial: true },
    ],
    };
    }
    if (event.type === "token" && state.status === "streaming") {
    return {
    ...state,
    turns: state.turns.map((turn) =>
    turn.id === `${event.turnId}-a` ? { ...turn, text: turn.text + event.text, partial: true } : turn,
    ),
    };
    }
    if (event.type === "stop" && state.status === "streaming") {
    return { ...state, status: "stopped", turns: freezePartial(state.turns) };
    }
    if (event.type === "fail" && state.status === "streaming") {
    return { ...state, status: "failed", turns: freezePartial(state.turns) };
    }
    if (event.type === "refuse" && state.status === "streaming") {
    return { ...state, status: "refused", turns: freezePartial(state.turns) };
    }
    if (event.type === "finish" && state.status === "streaming") {
    return {
    ...state,
    status: "ready",
    turns: state.turns.map((turn) => (turn.id === `${event.turnId}-a` ? { ...turn, partial: false } : turn)),
    };
    }
    return state;
    }
    function freezePartial(turns: PanelState["turns"]): PanelState["turns"] {
    return turns.map((turn) => ({ ...turn, partial: false }));
    }
    /** The only send control. Call this from a button handler, not from onChange. */
    export function canSend(state: PanelState, draft: string): boolean {
    return state.status !== "streaming" && draft.trim().length > 0 && draft.trim().length <= 500;
    }

    Intermediate example: history the prompt may include

    packages/ai-ux/src/history.ts

    typescript
    import type { ChatTurn } from "./types.js";
    const MAX_TURNS = 4;
    const MAX_CHARS = 2_000;
    /** Returns the newest turns that fit both caps. The server applies this again. */
    export function windowHistory(turns: ChatTurn[]): ChatTurn[] {
    const complete = turns.filter((turn) => !turn.partial && turn.text.length > 0);
    const selected: ChatTurn[] = [];
    let chars = 0;
    for (let index = complete.length - 1; index >= 0; index -= 1) {
    const turn = complete[index];
    if (selected.length >= MAX_TURNS) break;
    if (chars + turn.text.length > MAX_CHARS) break;
    selected.push(turn);
    chars += turn.text.length;
    }
    return selected.reverse();
    }

    Enterprise example: a copilot proposal that can go stale

    packages/ai-ux/src/proposal.ts

    typescript
    export interface Proposal {
    id: string;
    baseHash: string;
    baseText: string;
    proposedText: string;
    status: "open" | "accepted" | "rejected" | "stale";
    }
    export function hashText(value: string): string {
    let hash = 0;
    for (let index = 0; index < value.length; index += 1) {
    hash = (hash * 31 + value.charCodeAt(index)) >>> 0;
    }
    return hash.toString(16);
    }
    export function openProposal(id: string, baseText: string, proposedText: string): Proposal {
    return { id, baseHash: hashText(baseText), baseText, proposedText, status: "open" };
    }
    export type AcceptResult =
    | { ok: true; nextText: string; proposal: Proposal }
    | { ok: false; reason: "stale_selection" | "not_open" };
    export function acceptProposal(currentText: string, proposal: Proposal): AcceptResult {
    if (proposal.status !== "open") return { ok: false, reason: "not_open" };
    if (hashText(currentText) !== proposal.baseHash) {
    return { ok: false, reason: "stale_selection" };
    }
    return {
    ok: true,
    nextText: proposal.proposedText,
    proposal: { ...proposal, status: "accepted" },
    };
    }
    export function rejectProposal(proposal: Proposal): Proposal {
    return { ...proposal, status: "rejected" };
    }

    The hash is a teaching implementation for the lab, not a cryptographic commitment. Production can use a stronger hash of the same idea: the server stores it, and a changed selection cannot accept a stale proposal. The notes update is still not a completion write. There is no completed field on Proposal.

    Workflow submit guard

    packages/ai-ux/src/workflow.ts

    typescript
    export interface CommentWorkflowInput {
    lessonId: string;
    rubricId: string;
    observation: string;
    idempotencyKey: string;
    }
    export type WorkflowGate =
    | { ok: true; tier: "R1_user_confirm"; input: CommentWorkflowInput }
    | { ok: false; reason: "missing_field" | "too_long" };
    export function gateCommentWorkflow(input: CommentWorkflowInput): WorkflowGate {
    if (input.lessonId.length === 0 || input.rubricId.length === 0 || input.observation.trim().length === 0) {
    return { ok: false, reason: "missing_field" };
    }
    if (input.observation.length > 1_000 || input.idempotencyKey.length === 0) {
    return { ok: false, reason: "too_long" };
    }
    return { ok: true, tier: "R1_user_confirm", input };
    }

    The gate returns the tier the attach button must honor. Drafting the comment can proceed. Attaching it requires the confirm step defined in Lesson 20.

    Tests

    packages/ai-ux/src/ai-ux.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { canSend, initialPanel, reducePanel } from "./machine.js";
    import { windowHistory } from "./history.js";
    import { acceptProposal, openProposal } from "./proposal.js";
    import { gateCommentWorkflow } from "./workflow.js";
    test("send is a button guard and streaming ignores a second send", () => {
    const idle = initialPanel();
    assert.equal(canSend(idle, " "), false);
    const streaming = reducePanel(idle, { type: "send", turnId: "t1", text: "Explain this paragraph" });
    assert.equal(streaming.status, "streaming");
    assert.equal(canSend(streaming, "Again"), false);
    const ignored = reducePanel(streaming, { type: "send", turnId: "t2", text: "Again" });
    assert.equal(ignored.turns.length, 2);
    });
    test("stop freezes partial text and does not invent a completion flag", () => {
    const streaming = reducePanel(initialPanel(), { type: "send", turnId: "t1", text: "Help" });
    const withToken = reducePanel(streaming, { type: "token", turnId: "t1", text: "Look at the heading." });
    const stopped = reducePanel(withToken, { type: "stop" });
    assert.equal(stopped.status, "stopped");
    assert.equal(stopped.turns.at(-1)?.partial, false);
    assert.equal("completed" in stopped, false);
    });
    test("history keeps the newest turns inside the character cap", () => {
    const turns = [1, 2, 3, 4, 5].map((n) => ({
    id: `id-${n}`,
    role: "learner" as const,
    text: `q${n}${"x".repeat(400)}`,
    partial: false,
    }));
    const windowed = windowHistory(turns);
    assert.ok(windowed.length <= 4);
    assert.equal(windowed.at(-1)?.id, "id-5");
    });
    test("a changed selection cannot accept a proposal", () => {
    const proposal = openProposal("p1", "original note", "simpler note");
    const stale = acceptProposal("original note edited", proposal);
    assert.deepEqual(stale, { ok: false, reason: "stale_selection" });
    const fresh = acceptProposal("original note", proposal);
    assert.equal(fresh.ok, true);
    });
    test("workflow submit requires fields and names an R1 tier", () => {
    const denied = gateCommentWorkflow({ lessonId: "l1", rubricId: "", observation: "Nice", idempotencyKey: "k1" });
    assert.deepEqual(denied, { ok: false, reason: "missing_field" });
    const allowed = gateCommentWorkflow({
    lessonId: "l1",
    rubricId: "rub_1",
    observation: "Clear example in paragraph two.",
    idempotencyKey: "k1",
    });
    assert.equal(allowed.ok && allowed.tier, "R1_user_confirm");
    });

    Run:

    bash
    npx tsc --noEmit
    node --experimental-strip-types --test src/ai-ux.test.ts

    Nothing in the package opens a network connection. Wire the reducer to your player in the application repo, and keep the provider call on the server.

    Architecture Diagram

    text
    Lesson player
    |
    +--> Lesson column (content, quiz link, progress chip)
    |
    +--> AI panel
    |
    +--> Chat state machine --> tutor API --> model port
    |
    +--> Copilot proposal --> notes API
    |
    +--> Workflow form --> workflow API --> safety tier
    stateDiagram-v2
      [*] --> idle
      idle --> streaming: send
      ready --> streaming: send
      stopped --> streaming: send
      failed --> streaming: send
      refused --> streaming: send
      streaming --> ready: finish
      streaming --> stopped: stop
      streaming --> failed: fail
      streaming --> refused: refuse

    Real-Time Enterprise Example

    The production player loads the lesson and the progress chip in one request that never waits on the model. The panel mounts in idle. Send uses fetch with an AbortController. Stop aborts the browser read and notifies the API so the server can cancel the provider call and stop billing where the provider supports cancellation. Where it does not, the server still stops forwarding tokens and records stopped. Retry creates a new clientTurnId and a new server turn. It does not resume a partial completion.

    Suggested prompts are shipped with the lesson content version, so a curriculum edit does not require a model round trip to discover what the buttons say. Analytics events are tutor_send, tutor_stop, tutor_ready, tutor_fail, proposal_accept, proposal_reject, and workflow_submit, each with tenant id, lesson id, prompt version, and latency. Event payloads omit the question text. Funnel review can still see abandon rates during streaming.

    A multi-tenant classroom tenant disables free chat and leaves the workflow card for instructors. The feature flag is evaluated on the server when the turn is created. The client hides the composer when the lesson payload says chat: false. Hiding the composer is a convenience. The API rejects the turn when the flag is off.

    Challenge: high traffic during enrollment week. The panel stays quiet until interaction, history is windowed, and a per-tenant token ceiling from Lesson 19 returns failed with copy "Draft unavailable right now" rather than a partial answer that looks complete. The progress chip continues to read the database.

    Performance Optimization

    Do not mount a model call in useEffect on page load. The lesson should become usable before the panel is touched. Stream tokens so the learner sees progress before the full draft exists. Batch React updates if you render in the browser: apply tokens on a short frame interval so a fast stream does not re-render the whole player every character. Keep the lesson column memoized so streaming the rail does not re-layout the article.

    The history window is the main token control on this surface. Suggested prompts are static. File context is opt-in. Stop is a cost control as well as a usability control. Cache nothing personalized in a shared CDN. You may cache the static suggested-prompt list with the lesson version.

    CPU and memory on the client stay modest if you cap stored turns in the panel and let older turns paginate from the server. Rendering optimization is mostly "do not re-render the lesson." Bundle optimization is "the state machine is small and the provider SDK is not in the client bundle."

    Security

    • Authentication. Every turn, proposal, and workflow POST uses the session. The state machine runs in the client and is not an authority.
    • Authorization. The server re-checks the lesson ACL and the notes owner. A proposal id from another user returns 404.
    • Validation. canSend, the history window, and gateCommentWorkflow have server twins. Client guards improve the form.
    • Secrets. The player bundle has no provider credential and no Authorization header for the vendor.
    • Tenant isolation. Thread and note queries include tenant and user.
    • XSS. Assistant text renders as text. A draft that contains markup is escaped by the normal React text node. Do not inject HTML from the model.
    • CSRF. Cookie-authenticated POSTs use the same CSRF control as the rest of the API.
    • Over-claim. Copy review is a security-adjacent control: a string that says the lesson is complete is a product defect even when the database is right.
    • Logging. UI analytics omit raw questions. Support tools that need the text use the retention-scoped thread store.

    Prompt injection in the question can still produce a strange draft. The state machine will label it a draft. The quiz route will ignore it. That pairing is the control.

    Common Mistakes

    1. Completion language in the assistant or the chrome. Symptom: learners leave thinking they passed. Cause: unconstrained chat copy. Fix: scoped title, "Draft ready," and a progress chip bound to the database.
    2. Sending on each change event. Symptom: token bills track typing. Cause: onChange called the tutor. Fix: canSend from a button or an explicit shortcut.
    3. No stop control. Symptom: learners refresh the page to interrupt a bad answer. Cause: streaming UI with a single spinner. Fix: the stop transition and an abort on the request.
    4. Accept that overwrites notes without a hash. Symptom: a slow response replaces text the learner edited while waiting. Cause: no baseHash. Fix: stale_selection.
    5. One state flag named loading. Symptom: designers cannot tell failed from refused, and retry behaves differently in each call site. Cause: a boolean. Fix: the PanelStatus union.
    6. Live region set to assertive on every token. Symptom: screen-reader users cannot work. Cause: a naive stream binding. Fix: polite updates batched to pauses and completion, aligned with Lesson 8.
    7. Full-page error when the tutor times out. Symptom: the lesson disappears. Cause: the panel error bubbled to the route boundary. Fix: contain the failure inside the rail.
    8. Suggested prompts generated on every page view. Symptom: cost and latency before the learner asks. Cause: a model call in the loader. Fix: ship prompts with the lesson version.
    9. Thread text in the analytics payload. Symptom: questions appear in a third-party product analytics tool. Cause: a debug property. Fix: ids and timings only.
    10. Workflow button labeled "Submit" that both drafts and attaches. Symptom: a comment lands on a learner record from one click. Cause: two tiers on one control. Fix: "Draft comment" and a separate "Attach" for R1.
    11. Hiding chat in the client and leaving the API open. Symptom: a scripted client still calls the turn endpoint after a tenant disable. Fix: enforce the flag on the server.
    12. Rendering model HTML. Symptom: a script runs from a draft. Cause: dangerouslySetInnerHTML or a markdown renderer with raw HTML enabled. Fix: text or a sanitized markdown subset you have reviewed.

    Best Practices

    1. Pick the surface from the job: explain, propose, or collect fields.
    2. Put the scope in the panel title and the placeholder.
    3. Use a closed status union and test its transitions.
    4. Bind progress UI to the progress API only.
    5. Label every model result as a draft until a real confirm exists.
    6. Require an explicit send. Cap the character count.
    7. Offer Stop during streaming and keep partial text.
    8. Retry with a new turn id, started by the learner.
    9. Window the history on the server.
    10. Ship suggested prompts with the content version.
    11. Accept copilot changes only when the base hash matches.
    12. Give workflows two controls when draft and commit differ.
    13. Keep the lesson column interactive when the panel fails.
    14. Use a polite live region and a named Stop button.
    15. Render assistant output as text.
    16. Persist threads by tenant and user, with a retention rule.
    17. Omit raw prompts from analytics.
    18. Enforce feature flags on the server.
    19. Hand R2 actions to the review queue and link the ticket.
    20. Avoid a model call during page load.
    21. Record prompt version on each turn for evaluation.
    22. Review UI copy that mentions completion, grades, refunds, or certificates.

    Interview Questions & Answers

    Beginner

    1. When would you choose a workflow card over chat?
      Choose a workflow when the product needs specific fields and a typed result, such as a quiz comment with a rubric id. Choose chat when the job is an explanation of material the learner can already read.

    2. What should stay visible if the tutor request fails?
      The lesson, the navigation, and the progress chip. The panel shows "Draft unavailable" and a Retry control.

    3. Why is a draft label not the same as human approval?
      The label tells the reader the text is uncommitted. Approval is a second person or an explicit confirm that performs a real write, as defined in Lesson 20.

    Intermediate

    1. How do you stop a stream?
      The UI dispatches stop, aborts the browser consumer, and notifies the API. The reducer freezes partial text and leaves progress untouched. The server records stopped and stops forwarding tokens.

    2. What is a stale copilot proposal?
      The learner edited the selection after the proposal was built. acceptProposal compares hashes and returns stale_selection so the newer text remains.

    3. How do you keep token cost predictable on a chatty panel?
      Explicit send, a 500-character cap, a four-turn or 2,000-character history window, static suggested prompts, and no call on page load.

    Senior

    1. How would you test this without screenshot diffs only?
      Unit-test the reducer, canSend, the history window, proposal acceptance, and the workflow gate. Add one player test that the progress chip's query does not refetch solely because a turn finished. Accessibility checks name the Stop button and the live region.

    2. A stakeholder wants the assistant to say "marked complete" when it is confident. What do you ship?
      You ship copy that describes a draft, and you keep the completion writer on the quiz service. Confidence is not an authorization to change lesson_progress. If the stakeholder wants a shortcut, the shortcut is the existing quiz, not a sentence.

    Architect

    1. How should an agent console reuse this lesson?
      Tool proposals render like copilot proposals: action name, arguments, Accept, Reject. R2 tools open the review ticket and the console shows the ticket status. The agent runtime is covered in /learn/agentic. The state machine's rule stays: a streaming or ready assistant is not a domain commit.

    2. How do you scale the panel for many tenants and a shared design system?
      The reducer and copy tokens live in the design system as behavior, not as a single chat component with a boolean mode. Tenants may disable surfaces via server flags. Analytics stay free of raw text so a shared pipeline can cross tenants without pooling questions.

    Knowledge Check

    1. What problem does this capability solve?

    It makes model help understandable and bounded: learners can see scope, streaming, stop, failure, and the difference between a draft and lesson progress.

    2. What alternatives exist, and when would you choose each?

    Chat fits section explanations. Copilot fits edits to a selection the user owns. Workflow fits structured tasks and any later confirm. An unbounded "ask me anything" page fits a general consumer assistant and fits this player poorly.

    3. Which data, identity, and trust boundaries matter?

    The browser holds UI state and the session cookie. The API checks the lesson ACL and note ownership. Threads and notes are stored per tenant and user. The model sees the excerpt and the windowed history. Progress stays on its own query.

    4. What can fail, and how should the system respond?

    Empty sends do nothing. A second send during streaming is ignored. Stop, fail, and refuse end in distinct statuses with the lesson still on screen. A changed selection cannot accept a proposal. A missing workflow field does not submit.

    5. How would you test quality, security, performance, and cost?

    Reducer tests cover the statuses. A component test covers Stop's name and the isolated error. Security review checks server-side flags, tenant filters, and text rendering. Cost review checks the history window and the absence of a load-time model call.

    Key Takeaways

    1. Chat, copilot, and workflow are different jobs.
    2. The panel title states the scope.
    3. Status is a union: idle, streaming, ready, stopped, failed, refused.
    4. Progress is a different query.
    5. Send is explicit. Stop is available while streaming.
    6. Partial text survives a stop.
    7. History sent to the model is windowed.
    8. Proposals can go stale, and reject leaves the source.
    9. Workflow draft and workflow commit are separate buttons when the tier says so.
    10. Failures stay inside the panel.
    11. Assistant text renders as text.
    12. Analytics omit question bodies.
    13. Flags are enforced on the server.
    14. Suggested prompts ship with the lesson.
    15. Agent consoles should reuse proposal and review, not a second chat metaphor.

    Summary

    Lesson 22 puts a trustworthy frame around the drafts earlier lessons produce. The learner sees a scoped chat, a copilot proposal, or a workflow form, each driven by a testable state model. Streaming can be stopped. Notes change only on accept of a matching selection. Quiz progress never reads the assistant's last sentence. That interface is what learners will judge, regardless of which provider sits behind the port in the next lesson.

    Next Lesson Preview

    AI Integration Architecture and Provider Portability closes the module with a TypeScript port and adapters, so the panel you just designed can swap a fake, a primary provider, or a fallback without rewriting the tutor, the safety gate, or the upload pipeline.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.