freshcrate
Home > Security > agenticchat

agenticchat

Turn natural language into executable code โ€” right in your browser. Lightweight AI chat powered by GPT-4o with sandboxed JavaScript execution.

Description

Turn natural language into executable code โ€” right in your browser. Lightweight AI chat powered by GPT-4o with sandboxed JavaScript execution.

README

๐Ÿค– Agentic Chat

Turn natural language into executable code โ€” right in your browser.

Azure Static Web Apps CI/CD CodeQL License: MIT HTML5 JavaScript OpenAI GitHub repo size GitHub last commit codecov

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.

Live Demo ยท Report Bug ยท Request Feature


โœจ Features

Core

  • 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_KEY placeholders in generated code and prompts for credentials per domain; keys are cached per session

Conversation Management

  • 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

Search & Navigation

  • 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

Productivity

  • 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)

Analysis & Insights

  • 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

Personalization

  • 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

Data

  • 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

AI & Reliability

  • 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)

๐Ÿš€ Getting Started

Prerequisites

  • A modern web browser (Chrome, Firefox, Safari, Edge)
  • An OpenAI API key with GPT-4o access

Usage

  1. Open index.html in your browser โ€” or visit the live demo
  2. Paste your OpenAI API key into the key field (stored in memory only, never persisted)
  3. Type a question or task and press Enter
  4. 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: "..." }

๐Ÿ—๏ธ How It Works

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
  1. A system prompt instructs GPT-4o to respond exclusively with JavaScript in a fenced code block
  2. The app extracts the code using regex and delivers it to a sandboxed iframe via postMessage (not template interpolation โ€” preventing script-tag injection)
  3. The iframe executes the code with new Function() inside an async wrapper
  4. Results are returned via postMessage with origin validation ('null' for sandboxed iframes) and nonce matching

Modules

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

๐Ÿ”’ Security Model

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

โš ๏ธ Known Limitations

  • 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).

๐Ÿ› ๏ธ Tech Stack

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

๐Ÿ“ Project Structure

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 Compatibility

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+ โš ๏ธ Partial Voice input may require user gesture; layout adapts
Mobile Safari 15+ โš ๏ธ Partial 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.

โ“ Troubleshooting

"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, or localStorage will 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.enabled is true in about: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
  • localStorage has 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

๐Ÿค Contributing

Contributions are welcome! Here's how:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'feat: add amazing feature')
  4. Push to your branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Guidelines

  • This is a single-file app โ€” keep it that way unless there's a compelling reason to split
  • All 49 modules live in app.js as 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)

๐Ÿ“„ License

Distributed under the MIT License. See LICENSE for details.


Release History

VersionChangesUrgencyDate
v2.30.0## What's New ### โœจ Smart Model Advisor (Alt+Shift+A) Proactive model recommendation engine that analyzes your conversation patterns and suggests optimal model switches based on task complexity, token usage, and response quality. ### โœจ Smart Context Sidebar (Alt+Shift+I) Proactive intelligence panel that surfaces relevant context, suggestions, and insights alongside your conversations in real time. ### โšก Performance - **Allocation-free sentiment scoring** in MoodRing and ConversationSentimentHigh4/21/2026
v2.28.4## What's Changed ### Refactor - **Extract SSE line parser and unify streaming/non-streaming API call paths** โ€” Consolidates duplicate SSE parsing logic into a shared parser module, reducing code duplication across streaming and non-streaming call paths. Both paths now share the same robust line-parsing pipeline. (7f4a1c7) ### Performance - **Eliminate throwaway array allocations in hot paths** โ€” Replaces temporary array allocations (spreads, slices, intermediate maps) in frequently-called funHigh4/20/2026
v2.28.2## Security ### ConversationAutopilot Hardening - Use ApiKeyManager.getOpenAIKey() instead of reading raw DOM input value, preventing API key exposure via DOM inspection - Add rate limiter (5s minimum between API calls) to prevent rapid-fire spend - Cap 'unlimited' step mode to 50 steps max to prevent unbounded API cost ### ConversationShareLink DoS Protection - Cap decoded JSON payload to 5 MB and encoded base64 to ~7 MB before processing - Limit messages to 200 max and per-message content toHigh4/17/2026
v2.28.0## What's New ### โœจ Features - **Conversation Drift Detector** โ€” proactive topic coherence monitoring alerts when conversations stray off-topic - **Conversation Mood Ring** โ€” real-time sentiment monitor accessible via Alt+M shortcut - **Smart Session Linker** โ€” TF-IDF cosine similarity discovers related sessions (Alt+L) - **Conversation Autopilot** โ€” goal-directed autonomous exploration mode ### โ™ป๏ธ Refactoring - Extracted shared TextAnalytics module from duplicated NLP code across features - RHigh4/16/2026
v2.27.0## What's Changed ### Performance Improvements - **CostDashboard**: Add in-memory cache for cost log entries, eliminating redundant file reads on repeated dashboard opens - **SessionNotes**: Cache \_loadAll()\ results to avoid redundant JSON parsing when notes haven't changed - **SmartTitle**: Cache \generate()\ results to skip redundant regex work for previously-seen inputs All three changes reduce UI latency during normal usage by avoiding repeated I/O and computation for data that rarely chHigh4/5/2026

Dependencies & License Audit

Loading dependencies...

Similar Packages

WeKnoraLLM-powered framework for deep document understanding, semantic retrieval, and context-aware answers using RAG paradigm.v0.4.0
multi-postgres-mcp-server๐Ÿš€ Manage multiple PostgreSQL databases with one MCP server, offering hot reload, access control, and read-only query safety in a single config filemaster@2026-04-21
AGENTS.md_generator๐Ÿค– Generate secure, automated repo documentation and pull request checks with a safe-by-default toolchain for coding agents.main@2026-04-21
terminal-mcp๐Ÿ–ฅ๏ธ Enhance your terminal interactions by allowing AI to see and control your session for real-time debugging and automation.main@2026-04-21
VSCode-Local-CopilotNo descriptionmain@2026-04-21