Turn natural language into executable code โ right in your browser.
A lightweight, zero-dependency chat interface that sends your prompts to GPT-4o, extracts the JavaScript it writes, and executes it in a sandboxed iframe โ all from a single HTML file.
- Natural Language โ Code โ Ask a question or describe a task in plain English; GPT-4o returns JavaScript that gets executed automatically
- Sandboxed Execution โ Generated code runs in an
<iframe sandbox="allow-scripts">with no access to the parent page's DOM, cookies, localStorage, or variables - Content Security Policy โ The sandbox iframe enforces
default-src 'none'; connect-src https:so code can call external APIs but nothing else - Nonce Validation โ Each execution gets a
crypto.randomUUID()nonce to prevent stale or replayed postMessage events - Multi-Model Support โ Switch between GPT-4o, GPT-4o-mini, GPT-4-turbo, and more via the model selector
- API Key Management โ Detects
YOUR_API_KEYplaceholders in generated code and prompts for credentials per domain; keys are cached per session
- Conversation History โ Maintains a sliding window of up to 20 message pairs with automatic trimming and token-count warnings
- Multi-Session โ Create, switch between, rename, and delete multiple conversation sessions with auto-save
- Cross-Tab Sync โ Detects concurrent edits across browser tabs via BroadcastChannel
- Conversation Fork โ Branch conversations from any message into new sessions
- Chapters โ Insert named section dividers with a table-of-contents sidebar
- Tags โ Colored tag labels on sessions with filtering and management
- Auto-Tagger โ Heuristic topic detection and automatic tag suggestions
- Message Search โ Full-text search across conversation messages with highlighting
- Global Session Search โ Search across all saved sessions at once
- Conversation Timeline โ Visual minimap sidebar for conversation navigation
- Bookmarks & Pinning โ Bookmark messages for quick reference; pin important ones to a floating bar
- Slash Commands โ
/-triggered command dropdown with autocomplete and keyboard navigation
- Prompt Templates โ Built-in library of categorized prompt templates with search filtering
- Snippet Library โ Save, tag, search, rename, and re-run generated code snippets
- Quick Replies โ Contextual follow-up suggestion chips after AI responses
- Formatting Toolbar โ Markdown formatting buttons above the chat input
- Scratchpad โ Persistent notepad panel with copy/insert/download actions
- Input History โ Navigate previous prompts with โ/โ arrow keys
- File Drop Zone โ Drag-and-drop file inclusion (text-based files, 100 KB limit)
- Focus Mode โ Distraction-free zen mode (Ctrl+Shift+F)
- Chat Stats โ Conversation analytics: word counts, code blocks, response timing
- Cost Dashboard โ Persistent API spend tracker with budget alerts and daily chart
- Message Diff โ Compare any two messages with visual line-level diff
- Conversation Summarizer โ Heuristic summary with topics, decisions, and action items
- Response Time Badge โ Per-response latency indicator
- Persona Presets โ Switchable system prompt presets with custom persona support
- Theme Manager โ Dark/light theme with OS preference detection
- Keyboard Shortcuts โ Global shortcuts with help modal
- Voice Input โ Browser speech recognition with language selection
- Read Aloud โ Text-to-speech for messages with voice/speed controls
- Message Annotations โ Private notes/annotations on messages with labels
- Message Reactions โ Per-message emoji reactions with persistent counts
- Data Backup โ Full backup/restore for all 21 data keys (export/import/selective/merge)
- Zero Dependencies โ Single HTML file + CSS + JS. No build tools, no npm, no bundler. Just open and go.
- Input Guardrails โ Character limit (50K chars), token estimate warnings (~80K threshold), real-time counter
- Response Rating โ Thumbs up/down ratings on AI responses with model satisfaction dashboard
- Smart Retry โ Automatic retry with exponential backoff for transient API failures
- Message Editor โ Edit and resend user messages (truncates history and reloads into input)
- Message Translator โ Inline message translation to 20+ languages via OpenAI API
- Conversation Merge โ Combine 2+ sessions into one merged conversation with chronological interleaving
- Conversation Replay โ Message-by-message playback with transport controls (play/pause/speed)
- Prompt Library โ User-created prompt snippets with folders, search, usage tracking, import/export
- Usage Heatmap โ GitHub-style 7x24 activity heatmap across all sessions
- Word Cloud Generator โ interactive word frequency cloud from conversation with 5 color schemes, PNG download (
Alt+W)
- A modern web browser (Chrome, Firefox, Safari, Edge)
- An OpenAI API key with GPT-4o access
- Open
index.htmlin your browser โ or visit the live demo - Paste your OpenAI API key into the key field (stored in memory only, never persisted)
- Type a question or task and press Enter
- Watch the generated code and its output appear in the console area
> "What's the current UTC time?"
โ GPT-4o generates: return new Date().toUTCString();
โ Output: Fri, 14 Feb 2026 10:00:00 GMT
> "Fetch the top Hacker News story"
โ GPT-4o generates fetch() code targeting the HN API
โ Output: { title: "...", url: "..." }
User Prompt โ GPT-4o (system prompt: reply with JS only)
โ
Markdown response with ```js code block
โ
Regex extraction of JavaScript
โ
Sandboxed iframe execution
โ
postMessage with nonce-validated result
โ
Display output in console area
- A system prompt instructs GPT-4o to respond exclusively with JavaScript in a fenced code block
- The app extracts the code using regex and delivers it to a sandboxed iframe via
postMessage(not template interpolation โ preventing script-tag injection) - The iframe executes the code with
new Function()inside an async wrapper - Results are returned via
postMessagewith origin validation ('null'for sandboxed iframes) and nonce matching
The codebase is organized into 49 IIFE modules in app.js, each using the revealing-module pattern:
Core (7 modules)
| Module | Purpose |
|---|---|
SafeStorage |
Safe localStorage wrapper for restricted-storage environments |
ChatConfig |
Frozen constants โ model list, pricing, token limits, system prompt |
ConversationManager |
Message history with sliding window trimming and token estimation |
SandboxRunner |
Iframe sandbox lifecycle, execution, timeout, cancellation |
ApiKeyManager |
OpenAI + per-service key storage, substitution, validation |
UIController |
All DOM manipulation โ button states, modals, output |
ChatController |
Orchestrates send flow: input โ API โ code extraction โ sandbox |
Features (42 modules)
| Module | Purpose |
|---|---|
PromptTemplates |
Categorized prompt library with search and one-click insert |
HistoryPanel |
Slide-out conversation history with Markdown/JSON export/import |
SnippetLibrary |
Persistent code snippet storage with tagging and search |
MessageSearch |
Full-text search across conversation messages |
ChatBookmarks |
Bookmark individual messages for quick reference |
SlashCommands |
Slash-command dropdown with autocomplete and keyboard nav |
MessageReactions |
Per-message emoji reactions with persistent counts |
KeyboardShortcuts |
Global keyboard shortcuts with help modal |
VoiceInput |
Browser speech recognition with language selection |
ThemeManager |
Dark/light theme with OS preference detection |
SessionManager |
Multi-session persistence with auto-save and quota management |
CrossTabSync |
Multi-tab conflict detection via storage events + BroadcastChannel |
ChatStats |
Conversation analytics (word counts, code blocks, timing) |
CostDashboard |
Persistent API spend tracker with budget alerts and daily chart |
PersonaPresets |
Switchable system prompt presets with custom persona support |
ModelSelector |
Model picker with localStorage persistence |
FileDropZone |
Drag-and-drop file inclusion (text-based files, 100 KB limit) |
FocusMode |
Distraction-free zen mode (Ctrl+Shift+F) |
InputHistory |
Navigate previous prompts with โ/โ arrow keys |
Scratchpad |
Persistent notepad panel with copy/insert/download actions |
ResponseTimeBadge |
Response time indicator below token usage area |
ConversationFork |
Branch conversations from any message into new sessions |
QuickReplies |
Contextual follow-up suggestion chips after AI responses |
MessagePinning |
Pin important messages to a floating quick-jump bar |
ReadAloud |
Text-to-speech for messages with voice/speed controls |
MessageDiff |
Compare any two messages with visual line-level diff |
ConversationTimeline |
Visual minimap sidebar for conversation navigation |
ConversationSummarizer |
Heuristic conversation summary with topics and action items |
MessageAnnotations |
Private notes/annotations on messages with labels |
ConversationChapters |
Named section dividers with TOC navigation |
ConversationTags |
Colored tag labels on sessions with filtering and management |
FormattingToolbar |
Markdown formatting buttons above chat input |
GlobalSessionSearch |
Full-text search across all saved sessions |
AutoTagger |
Heuristic topic detection and automatic tag suggestions |
DataBackup |
Full backup/restore for all user data (21 keys, export/import) |
ResponseRating |
Thumbs up/down ratings on AI responses with model satisfaction dashboard |
ConversationMerge |
Combine 2+ sessions into one merged conversation (chronological interleave) |
ConversationReplay |
Message-by-message playback with transport controls |
PromptLibrary |
User-created prompt snippets with folders, search, usage tracking, import/export |
MessageTranslator |
Inline message translation to 20+ languages via OpenAI API |
MessageEditor |
Edit and resend user messages (truncate history + reload into input) |
SmartRetry |
Automatic retry with exponential backoff for transient API failures |
UsageHeatmap |
GitHub-style 7x24 activity heatmap across all sessions |
SmartPaste |
Intelligent paste formatting โ auto-detects JSON, code, CSV, SQL, URLs, stack traces |
The app executes AI-generated code, so security is a first-class concern:
| Layer | Protection |
|---|---|
| Iframe Sandbox | sandbox="allow-scripts" โ no DOM access, no cookies, no localStorage, no same-origin |
| CSP | default-src 'none'; connect-src https: โ only outbound HTTPS allowed |
| Origin Check | postMessage validated against 'null' origin (sandboxed iframe) |
| Nonce | crypto.randomUUID() ties each execution to its result, preventing replay |
| Code Delivery | Code sent via postMessage, not embedded in HTML (prevents </script> injection) |
| API Key Isolation | OpenAI key stored in parent JS variable only โ never exposed to sandbox |
- Outbound HTTPS is allowed โ The sandbox CSP includes
connect-src https:so LLM-generated code can call external APIs. This is required for the core use case but means sandbox code can make network requests. - Service API keys are injectable โ When you provide a third-party API key (e.g., weather API), it's injected into sandbox code. A prompt injection attack could theoretically exfiltrate it. Your OpenAI key is safe (parent page only).
| Component | Technology |
|---|---|
| Frontend | Vanilla HTML5 + CSS + JavaScript (single file) |
| AI Model | OpenAI GPT-4o via REST API |
| Sandbox | HTML5 iframe sandbox with CSP |
| Hosting | GitHub Pages |
| CI/CD | GitHub Actions |
| Security | CodeQL analysis |
agenticchat/
โโโ index.html # Single-page UI with CSP headers
โโโ app.js # All application logic (48 modular IIFEs)
โโโ style.css # Responsive dark-theme styling
โโโ package.json # npm metadata + test scripts
โโโ jest.config.js # Jest test configuration
โโโ Dockerfile # Multi-stage container build
โโโ CONTRIBUTING.md # Contribution guidelines
โโโ LICENSE # MIT License
โโโ README.md # This file
โโโ docs/
โ โโโ index.html # API reference & architecture docs (GitHub Pages)
โโโ tests/
โ โโโ setup.js # DOM mocking & app.js loader for jsdom
โ โโโ app.test.js # Core module tests (800+)
โ โโโ annotations.test.js # MessageAnnotations tests
โ โโโ auto-tagger.test.js # AutoTagger tests
โ โโโ chapters.test.js # ConversationChapters tests
โ โโโ conversation-merge.test.js # ConversationMerge tests
โ โโโ conversation-replay.test.js # ConversationReplay tests
โ โโโ conversation-tags.test.js # ConversationTags tests
โ โโโ cost-dashboard.test.js # CostDashboard tests
โ โโโ data-backup.test.js # DataBackup tests
โ โโโ formatting-toolbar.test.js # FormattingToolbar tests
โ โโโ message-editor.test.js # MessageEditor tests
โ โโโ message-translator.test.js # MessageTranslator tests
โ โโโ messagediff.test.js # MessageDiff tests
โ โโโ model-compare.test.js # ModelCompare tests
โ โโโ modules.test.js # Module existence/integration tests
โ โโโ pinning.test.js # MessagePinning tests
โ โโโ prompt-library.test.js # PromptLibrary tests
โ โโโ readaloud.test.js # ReadAloud tests
โ โโโ response-rating.test.js # ResponseRating tests
โ โโโ smart-retry.test.js # SmartRetry tests
โ โโโ summarizer.test.js # ConversationSummarizer tests
โ โโโ timeline.test.js # ConversationTimeline tests
โ โโโ usageHeatmap.test.js # UsageHeatmap tests
โโโ .github/
โโโ copilot-instructions.md # Copilot coding agent context
โโโ copilot-setup-steps.yml # Copilot agent setup workflow
โโโ dependabot.yml # Automated dependency updates
โโโ labeler.yml # Auto-label configuration
โโโ PULL_REQUEST_TEMPLATE.md # PR template
โโโ ISSUE_TEMPLATE/
โ โโโ bug_report.yml # Bug report form
โ โโโ feature_request.yml # Feature request form
โ โโโ config.yml # Issue template config
โโโ workflows/
โโโ ci.yml # Build + test + lint
โโโ codeql.yml # CodeQL security scanning
โโโ docker.yml # Docker build & push
โโโ labeler.yml # Auto-labeler workflow
โโโ pages.yml # GitHub Pages deployment
โโโ publish.yml # npm package publishing
โโโ stale.yml # Stale issue/PR management
| Browser | Version | Status | Notes |
|---|---|---|---|
| Chrome | 90+ | โ Full | Recommended โ best sandbox + speech API support |
| Firefox | 88+ | โ Full | Voice input requires media.navigator.enabled |
| Safari | 15+ | โ Full | Minor speech recognition differences |
| Edge | 90+ | โ Full | Chromium-based, same as Chrome |
| Opera | 76+ | โ Full | Chromium-based |
| Mobile Chrome | 90+ | Voice input may require user gesture; layout adapts | |
| Mobile Safari | 15+ | sandbox iframe works but some CSP edge cases exist |
Requirements: All browsers must support crypto.randomUUID() (HTTPS or localhost only), iframe sandbox, and BroadcastChannel. No polyfills needed for modern browsers.
"Failed to fetch" or network errors when sending prompts
- Verify your OpenAI API key is valid and has GPT-4o access
- Check that your API key has sufficient credits/quota
- Ensure you're not behind a corporate proxy that blocks
api.openai.com - Try switching to a different model (e.g., GPT-4o-mini) in the model selector
Generated code doesn't execute / "Sandbox error"
- The sandbox iframe blocks DOM access by design โ code that references
document,window.location, orlocalStoragewill fail - Code can only make outbound HTTPS requests (
connect-src https:) - Check the browser console for CSP violation messages
- If you see timeout errors, the generated code may be stuck in an infinite loop
Voice input not working
- Speech recognition requires HTTPS (or localhost) โ it won't work over plain HTTP
- Firefox: ensure
media.navigator.enabledistrueinabout:config - Safari: grant microphone permission when prompted
- Some browsers require a user gesture (click) to activate the microphone
Data lost between sessions
- All data is stored in
localStorageโ clearing browser data will erase it - Use the Data Backup feature (Settings โ Backup) to export your data regularly
localStoragehas a ~5 MB limit per origin โ the quota indicator in Settings shows usage- Cross-tab sync uses
BroadcastChannel; if you edit in two tabs simultaneously, the last write wins
Cost dashboard shows unexpected charges
- The cost tracker estimates based on token counts and published OpenAI pricing
- Actual billing may differ slightly due to system prompt tokens and retry attempts
- Reset the tracker via Settings โ Cost Dashboard โ Reset
- Set a budget alert threshold to get warnings before hitting your limit
Contributions are welcome! Here's how:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to your branch (
git push origin feature/amazing-feature) - Open a Pull Request
- This is a single-file app โ keep it that way unless there's a compelling reason to split
- All 49 modules live in
app.jsas revealing-module IIFEs - Security is paramount โ any change that touches the sandbox must be reviewed carefully
- Test with various prompt types before submitting (simple questions, API calls, error cases)
Distributed under the MIT License. See LICENSE for details.
Built by Saurav Bhattacharya
