Recreating and Optimizing a Chat Web UI with AI-Assisted Development

    A practical walkthrough of recreating an AI chat web page using an AI coding assistant: how to split the work into verifiable deliverables, replicate the UI with measurable precision, integrate streaming APIs securely through a server-side proxy, and apply usability optimizations.

    1. Background and Problem Definition

    Conversational web pages are one of the most common forms of AI applications today. Users type a question into an input box, the server returns a response, the page renders the content progressively via streaming, and conversation history is saved. Recreating such a page looks like a simple UI cloning task, but it actually involves requirements gathering, layout replication, API integration, state management, and handling of sensitive credentials.

    This article uses a complete practice run as a thread to show how to leverage an AI coding assistant to turn requirements described in natural language into a working web page, and then optimize the experience on top of that. Only general methods are discussed here; no specific product is evaluated.

    2. Breaking Down the Development Workflow

    It is recommended to split the whole task into three deliverables and work through them in order:

    1. Product feature document and structure diagram: Clarify what features the page has, how they relate to each other, and the boundary conditions of each feature.
    2. Replicated page: Use the target page as the baseline and keep layout, fonts, spacing, and interactions as consistent as possible.
    3. Optimized page: On top of the replica, adjust interactions and features according to usability principles.

    The three deliverables should be completed sequentially. If you jump straight to the optimized version, conventions already established in the original page tend to get lost, and later you won’t be able to compare against the original item by item, making problems hard to trace.

    Prompts should also be delivered in two rounds. The first round describes only the functional and UI requirements, without any keys or service endpoints. The second round injects the API credentials and asks for end-to-end integration. This separates “is the UI correct” from “does the API work,” so when something breaks, the cause can be quickly identified.

    3. Structuring the Product Features

    The feature structure diagram is the foundation for subsequent development. A tree structure with priority annotations for each feature works well. For example:

    1. Chat Web Page
    2. ├── Conversation Management
    3. │ ├── New conversation
    4. │ ├── History list (search, rename, delete)
    5. │ └── Conversation sharing
    6. ├── Input Area
    7. │ ├── Multi-line text input
    8. │ ├── Attachment upload
    9. │ ├── Feature toggles (shown only if the API actually supports them)
    10. │ └── Send / Stop generating
    11. ├── Message Area
    12. │ ├── Streaming rendering
    13. │ ├── Markdown and code highlighting
    14. │ └── Copy, regenerate, feedback
    15. └── Account and Settings
    16. ├── Login state
    17. └── Preferences (theme, language)

    The feature list should distinguish between “visible in the UI” and “implemented on the backend.” If a feature has an entry point but no corresponding API, mark it as pending in the document so developers don’t assume it already works.

    4. Key Points of UI Replication

    The goal of UI replication is to make the differences imperceptible to users, which requires quantitative comparison rather than eyeballing.

    1. Layout structure
    Record the width ratio between the sidebar and main content area, the split between fixed and scrollable regions, and breakpoint positions. On mobile, the sidebar typically becomes a drawer, and the main content should remain unobstructed while the drawer is open.

    2. Input box
    The input box height should adapt to its content, with a maximum line count after which an internal scrollbar appears. Keyboard shortcuts for sending and line breaks should match the original page. On mobile, the on-screen keyboard may cover the input box, so adjust the scroll position on focus or use viewport-related APIs to detect the visible area.

    3. Message bubbles and typography
    The alignment, padding, line height, and font size of user and assistant messages determine the reading experience. Use browser developer tools to read the dimensions and spacing of each element, fill them into a comparison table, and then correct them one by one.

    4. Icons and fonts
    Prefer widely available icon sets or self-drawn vector graphics, and confirm their licensing. If the original font is unavailable, use a system font stack and document the difference.

    5. API Integration and Streaming Output

    5.1 Keys Never Go Into the Frontend

    API credentials are sensitive information. Frontend code can be viewed by anyone, so requests must be forwarded through a server-side proxy. The frontend only calls its own service’s endpoint; the key is kept in server-side environment variables or a secrets management service.

    Here is illustrative server-side proxy code; field names should follow the documentation of the service you use:

    1. // Server route: read the key from environment variables, forward the request, and stream back the response
    2. app.post('/api/chat', async (req, res) => {
    3. const upstream = await fetch(process.env.MODEL_ENDPOINT, {
    4. method: 'POST',
    5. headers: {
    6. 'Authorization': `Bearer ${process.env.MODEL_API_KEY}`,
    7. 'Content-Type': 'application/json',
    8. },
    9. body: JSON.stringify({ messages: req.body.messages, stream: true }),
    10. });
    11. res.setHeader('Content-Type', 'text/event-stream');
    12. for await (const chunk of upstream.body) {
    13. res.write(chunk);
    14. }
    15. res.end();
    16. });

    5.2 Reading the Stream Incrementally on the Frontend

    The frontend reads the response as a stream and renders content incrementally, without waiting for the full response:

    1. const controller = new AbortController();
    2. const resp = await fetch('/api/chat', {
    3. method: 'POST',
    4. headers: { 'Content-Type': 'application/json' },
    5. body: JSON.stringify({ messages }),
    6. signal: controller.signal,
    7. });
    8. const reader = resp.body.getReader();
    9. const decoder = new TextDecoder();
    10. let buffer = '';
    11. while (true) {
    12. const { done, value } = await reader.read();
    13. if (done) break;
    14. buffer += decoder.decode(value, { stream: true });
    15. // Split by the event delimiter, parse the data field, and append it to the current message
    16. // appendToken(parsed);
    17. }

    The AbortController here also serves as the “stop generating” mechanism. Calling controller.abort() interrupts the read while preserving the text generated so far.

    5.3 Common Pitfalls

    • Chunk boundaries: A single data block may contain only half of an event, so a buffer is needed to stitch them together.
    • Garbled multi-byte text: Decoding must use streaming mode; otherwise multi-byte characters can be split mid-character.
    • Connection timeouts: Show a notice when no data arrives for a long time, and allow the user to retry.

    6. Directions for Experience Optimization

    On top of the replica, consider improvements in these areas:

    • Stop and retry: Allow stopping during generation, keep the already-generated content, and provide a regenerate option.
    • Error recovery: When the network drops, preserve the text received so far and mark the answer as incomplete.
    • Conversation persistence: Local storage suits single-device use; server-side storage suits multi-device sync. The privacy and capacity trade-offs between them should be documented in the plan.
    • Context control: When history exceeds the model’s input length limit, truncate older messages or replace them with a summary.
    • Long-list performance: For long conversations, use a virtualized list so only visible messages are rendered. Throttle Markdown rendering so every character doesn’t trigger a full repaint.
    • Accessibility: Provide clear labels for the send button and input box, and return focus to the input after sending. For streaming content, control the frequency of screen reader announcements to avoid constant interruptions.

    Each optimization item should be added to the requirements document with a priority and acceptance criteria, rather than piling up a large batch of features all at once.

    7. Testing and Acceptance

    Testing should cover four layers:

    1. Visual comparison: Overlay screenshots for comparison, and verify the dimensions and spacing of key elements.
    2. Functional cases: Verify each operation—create, switch, delete, search, stop, regenerate, copy, and so on.
    3. Error paths: No network, invalid key, response timeout, overly long input, concurrent submissions, and similar scenarios.
    4. Real-device checks: Verify on-screen keyboard and drawer menu behavior across multiple screen sizes and operating systems.

    The focus of the second round of testing is integration. After injecting the key, first verify the minimal path: send one message and receive the complete response. Then test error paths on top of that. Issues like stream assembly, request cancellation, and consecutive submissions only surface with a valid key.

    Different development processes vary widely in how thorough this second round is. Some only do smoke checks, while others proactively find and fix boundary issues. Acceptance should therefore be based on a pre-written checklist, not on a single demo.

    8. Security and Precautions

    • Never write keys into frontend code, code repositories, logs, or prompts.
    • Set a length limit on user input and perform basic format validation.
    • Conversation sharing needs careful thought about permission scope and link expiration, so that historical content isn’t accidentally exposed.
    • Restrict attachment types and sizes, and validate them again on the server.

    9. Conclusion

    The key to recreating a chat web page is splitting requirements into verifiable deliverables, replicating the UI quantitatively, and integrating the API securely through a server-side proxy. A two-round testing approach separates UI issues from API issues. On that foundation, optimizations such as stop generation, error recovery, and context control can noticeably improve the real-world experience.