Designing a Single-File Web Chat Tool and Troubleshooting Attachment Uploads
This article covers the design of a single-file, pure front-end web chat tool that calls large language model APIs for tasks like text analysis and story outlining. It explains architecture choices (direct front-end vs. lightweight proxy), API key safety, five common causes of attachment upload failures, context and token management strategies, message editing, a step-by-step troubleshooting workflow, and privacy considerations—with JavaScript code examples included.
1. Background
Some developers build a pure front-end, single-file web page that directly calls a large language model (LLM) API to handle tasks such as text analysis, story setting organization, and outline development. These tools typically share the following traits:
- Data is stored locally in the browser, with no third-party relay service involved;
- The entire application lives in one HTML file, making it easy to modify and distribute;
- Features are customized for the owner’s needs rather than aiming for the full capabilities of a general-purpose product.
In practice, one of the most common problems with these tools is that after switching to certain reasoning modes, attachments fail to upload, or the model shows no response after an upload. Troubleshooting this requires understanding three areas: API capabilities, browser behavior, and context management.
2. Requirement Breakdown
A usable chat tool generally needs to cover the following modules:
- Session management: create, switch, delete, back up, import, and export conversations.
- Parameter configuration: temperature, max output length, reasoning effort, etc., with preset templates.
- Context control: limit the number of historical messages and compress or truncate them beyond a threshold.
- Prompt templates: save frequently used instructions and insert them into the input box.
- Attachment handling: read file content, validate size and format, and append it to the request.
- Message editing: copy or delete individual messages, affecting the context of subsequent requests.
- Usage estimation: estimate input tokens based on message length and provide warnings.
These modules depend on each other. For example, deleting a message changes the context, which in turn affects token estimation and cache hit rates. It is best to define a unified data structure first and then implement each feature.
3. Architecture Choices and API Key Security
3.1 Pure Front-End vs. Lightweight Proxy
| Dimension | Pure front-end (direct API calls) | Lightweight backend proxy |
|---|---|---|
| Deployment | Double-click the HTML file to run | Requires running a small service |
| Key security | Key stays in the browser, with leakage risk | Key stored in server-side environment variables |
| CORS issues | May be restricted by the browser’s same-origin policy | Handled uniformly by the proxy |
| Use cases | Personal local use | Multi-user sharing or public service |
For personal use, the pure front-end approach is simple enough. Keep in mind that data stored in the browser can be read by scripts on the same device, so never hard-code a key into a file you might share, and never embed a key in a publicly accessible page.
3.2 Principles for Storing API Keys
- Only write the key to storage when the user actively enters it, and provide a clear option to delete it;
- Strip the key field by default when exporting backups;
- For multi-user sharing or public deployment, hold the key in a backend proxy instead.
4. Five Common Causes of Attachment Upload Failures
4.1 The Reasoning Mode Does Not Support File Input
Different reasoning modes may enable different capability sets. Some modes only accept plain-text messages and will return an error or silently ignore the attachment when they encounter a file-type field. When troubleshooting, first send a plain-text message in the same mode to confirm the API works, then test the attachment.
4.2 File Size Exceeds Limits
APIs impose limits on both request body size and input token count. A text file of a few megabytes may exceed the single-request input range once converted to tokens. Solutions include:
- Enforcing a file size limit on the front end;
- Splitting long text into segments, submitting them separately, and summarizing the results;
- Extracting only the sections relevant to the task.
4.3 File Format and Encoding Issues
Plain-text files are usually read as UTF-8. If the file is a PDF, Word document, or archive, the browser only gets binary content. Pasting that directly into a request produces large amounts of garbled text that consume tokens without conveying any real information. The correct approach is to extract the text first, either on the front end or on the server.
4.4 Size Inflation from Base64 Encoding
If the API requires binary files to be transmitted as Base64, the data volume grows by roughly one-third. A 2 MB file becomes about 2.7 MB after encoding, making it more likely to hit request body limits.
4.5 Stale Cached Scripts or Faulty State
After a single-file app is updated, the browser may still be running the old script. Another common case is that the attachment object is not cleared from state, so every request repeatedly carries the previous file. Clear the attachment list after sending, and display the current attachment clearly in the UI.
Here is an example of reading a text attachment with validation:
const MAX_ATTACHMENT_BYTES = 2 * 1024 * 1024;async function readTextAttachment(file) {if (file.size > MAX_ATTACHMENT_BYTES) {throw new Error(`Attachment exceeds the ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB limit`);}const isTextFile = file.type.startsWith('text/') ||/\.(txt|md|json|csv)$/i.test(file.name);if (!isTextFile) {throw new Error('Only plain-text attachments are supported; convert other formats to text first');}return await file.text();}
This function performs format and size checks before reading, preventing invalid content from entering the request body.
5. Context and Token Management
5.1 Sliding Window Truncation
The longer the conversation, the more history each request carries, increasing both cost and latency. A common practice is to keep only the most recent turns while always including the system instruction.
function buildRequestMessages(session, maxTurns, systemPrompt) {const active = session.messages.filter(m => !m.deleted);const recent = active.slice(-maxTurns * 2);return [{ role: 'system', content: systemPrompt },...recent.map(({ role, content }) => ({ role, content })),];}
Note that maxTurns * 2 assumes messages come in pairs. If the window boundary happens to land on an assistant message, prepend the matching user message; otherwise the model receives an incomplete conversation.
5.2 Token Estimation
The front end cannot know every model’s exact tokenization, but character counts provide a rough estimate. For Chinese text, each character typically maps to one or more tokens, while English words are split into fragments. Estimates are suitable for warnings, not for billing purposes.
5.3 Cache-Friendly Context Structure
Many servers cache inputs that share the same prefix. If each request inserts different content at the very beginning, the cache can never hit. Keeping the system instruction and early history stable while placing variable content at the end helps reduce redundant computation.
5.4 Compression and Summarization
When a conversation exceeds a threshold, earlier messages can be sent to the model to generate a summary, which then replaces the original text. Compression loses detail, so it works well for preserving early conclusions in setting- or outline-oriented tasks, but not for scenarios that require verbatim citation.
6. Message Editing and Correction
Deleting a message effectively excludes it from subsequent requests. This capability is useful for correcting the model’s faulty reasoning: find the erroneous reply, delete it along with the dependent follow-up messages, then supply the correct information and ask again.
When implementing this:
- Use soft deletion so records can be restored;
- Recalculate the context and refresh the token estimate immediately after deletion;
- Distinguish user prompts, assistant replies, and reasoning traces in the copy function to avoid mixing them together.
7. Troubleshooting Workflow
When attachments fail to upload, check in the following order:
- Send a plain-text message under the same settings to confirm the API works;
- Verify whether the current reasoning mode supports attachment input;
- Check the file’s size, format, and encoding;
- Open the browser’s developer tools to inspect the request body size and any returned error messages;
- Clear the cache and refresh the page to confirm the latest script is in use;
- Verify that the attachment state is properly cleared after sending.
8. Privacy and Data Management
Conversation records may contain creative work, personal information, or business materials. When building such a tool, follow these principles:
- Store data locally by default and state this clearly in the UI;
- Provide a one-click option to erase all data;
- Check exported files and strip out API keys;
- Never send user content anywhere other than the intended API endpoint.
9. Conclusion
The core of a single-file chat tool is a clear data structure and predictable request construction. Attachment upload failures usually stem from mode capabilities, file formats, size limits, or front-end state, and can be located by checking each item in turn. Context truncation, token estimation, and message editing affect one another; a unified design keeps the tool stable over long conversations and helps users control cost and output quality more effectively.
