AI-Assisted Development of a Chat Web App: From Requirements Documentation to Optimization and Iteration
Building a conversational web page is a practical way to test an LLM's end-to-end coding ability, since it involves message lists, streaming output, session management, and settings panels. This article lays out a reusable workflow: how to break vague product requirements into model-executable tasks, how to design two-stage prompts, how to verify the generated output, and how to make evidence-based improvements on top of a replicated baseline. It also covers key implementation points such as the message data model, streaming rendering with AbortController, credential security, session persistence, and layered testing. (Note: the original text ends mid-example at the input-experience optimization section.)
Background: Why a Chat Web Page Is a Good Test of AI Development Ability
The code generation capabilities of large language models have improved significantly in recent years. More and more teams are trying to let models build a complete front-end application directly, rather than just generating an individual function. A conversational web page is a good sample for testing this capability. It includes modules such as a message list, an input area, streaming output, session management, a settings panel, and theme switching, covering both UI details and interaction with backend APIs. Completing such an application requires the model to understand requirements, organize the project structure, and identify problems on its own.
This article does not evaluate the strengths or weaknesses of any specific model or tool. Instead, it outlines a reusable methodology: how to break down vague product requirements into model-executable tasks, how to design staged prompts, how to verify the output, and how to make evidence-based optimizations on top of a replicated version.
1. Task Breakdown: Three Types of Deliverables
A complete practice typically includes three types of deliverables:
- Product requirements document and structure diagram: text and diagrams describing what features the page has and how they relate to each other.
- A replicated version: reproducing the reference page as closely as possible at both the functional and visual levels.
- An optimized version: improving interactions and features based on hands-on usage, on top of the replicated version.
There are clear dependencies among the three. The document is the input for the latter two, and the replicated version is the baseline for optimization. If you skip the documentation and write code directly, the model can only guess at feature boundaries from experience, which makes it easy to miss entry points, states, and error handling. The documentation phase therefore cannot be skipped.
2. Structuring the Feature List
When writing the document, it is recommended to first divide the application into modules by usage scenario, then refine each module into concrete features. For a chat web page, a basic structure looks like this:
Chat Web Page├── Session Sidebar│ ├── New session│ ├── Session history list (grouped by time)│ └── Session rename and delete├── Main Chat Area│ ├── Message list (user messages, model messages)│ ├── Streaming output and stop generation│ ├── Markdown rendering and code highlighting│ └── Copy message, regenerate├── Input Area│ ├── Multi-line text input│ ├── Keyboard shortcut to send│ └── Attachment upload (optional)└── Settings Center├── API credential configuration├── Model parameters (temperature, max output length)└── Theme and font
Each feature node should specify three things: trigger condition, expected result, and exception case. For example, “stop generation” is triggered while the model is streaming; the expected result is that output stops immediately and the content already generated is retained; the exception case is that if the abort request fails, the interface must return to a send-ready state. Only with these three points written clearly does the model have a basis for judgment during implementation.
3. Designing Two Rounds of Prompts
Staged prompting is key to this kind of practice. The first round focuses on “what to build”; the second focuses on “whether it runs and where the problems are.” The goals differ, so the writing style should differ as well.
The first-round prompt should include role, goal, constraints, and deliverables:
[Round 1: Requirements]Role: senior product manager and front-end engineerGoal: implement a single-page chat application with a session sidebar,message list, streaming output, and a settings centerConstraints:- Sensitive configuration must be read from environment variables, not hardcoded- The UI must adapt to both desktop and mobile widthsDeliverables: product requirements document (with structure diagram),project code, and run instructions
The second-round prompt injects configuration and requires verification:
[Round 2: Configuration and Verification]The API endpoint and access credentials have been provided via environmentvariables. Do not write them into code or logs.Please complete the following verification and output a test record:1. Send a normal message and check whether streaming output is continuous;2. Simulate network interruption, timeout, and invalid credentials, and checkwhether the error messages are accurate;3. Check edge cases such as empty input, double-clicking send, and scrollingin long conversations;4. List the issues found and explain how they were fixed.
In practice, the depth of execution in the second round varies greatly with the same prompt. Some tools only perform the most basic smoke test, while others proactively cover exception paths and fix defects found during verification. This shows that the second-round prompt cannot just say “test it”—it must define the verification scope explicitly. The more specific the verification scope, the more predictable the results.
4. Key Technical Points in Replicating the Implementation
4.1 The Data Model for Messages and Sessions
The data model is the shared foundation of the UI and the logic. A message needs to record its role, content, and status. The status should include at least four values: pending, streaming, done, and error.
type Role = "user" | "assistant";interface Message {id: string;role: Role;content: string;status: "pending" | "streaming" | "done" | "error";createdAt: number;}interface Session {id: string;title: string;messages: Message[];updatedAt: number;}
Modeling the status explicitly avoids problems such as a message showing “streaming” but being impossible to stop, or a loading animation still displayed after a failure.
4.2 Streaming Rendering and Interruption
Streaming output is the core of the chat experience. The front end reads the response body as a stream and appends text chunk by chunk. Interruption relies on AbortController.
async function streamReply(history: Message[],onChunk: (text: string) => void,signal: AbortSignal): Promise<void> {const response = await fetch("/api/chat", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({messages: history.map(({ role, content }) => ({ role, content })),}),signal,});if (!response.ok || !response.body) {throw new Error(`Request failed with status ${response.status}`);}const reader = response.body.getReader();const decoder = new TextDecoder();while (true) {const { done, value } = await reader.read();if (done) break;onChunk(decoder.decode(value, { stream: true }));}}
The /api/chat path in this code is a placeholder. A real server-side protocol may use an event-stream format, in which case the front end must parse each chunk according to the protocol instead of directly concatenating raw bytes.
4.3 Credential Security
Access credentials should never appear in front-end code. Any script running in the browser can be read, and once a credential is leaked, the only option is to request a new one. A safer approach is to keep credentials on the server side: the front end only calls your own backend API, and the backend forwards requests to the model service.
# The credential is read from an environment variable only on the server sideexport CHAT_API_KEY="<your credential here>"
Credentials should also be masked in logs, keeping only the last few characters for troubleshooting.
4.4 Session Persistence
Session data can be stored in the browser’s local storage. For short sessions, local storage is sufficient. When the number of sessions is large or individual messages are very long, switch to a higher-capacity client-side database, and debounce writes so that every output character does not trigger a storage operation.
5. Verification: Layered Checks of the Output
Model-generated code requires layered verification, not just checking whether the page opens. The table below lists commonly used verification layers:
| Layer | What to Check | Common Issues |
|---|---|---|
| Smoke test | Page loads, send one message | Blank screen, wrong API path |
| Functional test | Create, switch, delete sessions; settings persist | State not synced, data lost after refresh |
| Boundary test | Empty input, very long text, rapid consecutive sends | Duplicate requests, input cleared unexpectedly |
| Exception test | Network loss, timeout, invalid credentials | Unclear error messages, UI stuck |
| UI regression | Different widths, dark mode, font scaling | Broken layout, text overflow |
After verification, record the result of every item, including passed, failed, and not covered. The uncovered items deserve more attention than the failed ones, because they mean problems have not yet been discovered.
6. Optimization Directions: Evidence-Based UX Improvements
The replicated version is only a baseline. The optimization phase should start from real usage scenarios, and each improvement should state what problem it solves.
6.1 Input Experience
When using an IME (input method editor) for CJK input, composition can trigger the Enter key event. If this is not handled, a message may be sent by mistake while the user is still selecting a word.
function handleKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {//
