Skip to content

Add GAIA Chat UI: privacy-first desktop chat with document Q&A - #428

Merged
kovtcharov merged 106 commits into
mainfrom
kalin/chat-ui
Mar 18, 2026
Merged

kovtcharov merged 106 commits into
mainfrom
kalin/chat-ui

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Privacy-first desktop chat application for AMD Ryzen AI — runs 100% locally with document Q&A, streaming agent responses, and zero cloud dependencies.

What this adds:

  • Full-stack chat application: FastAPI backend + React/TypeScript frontend + Electron desktop shell
  • Document Q&A via RAG: drag-and-drop files (PDF, code, text, CSV, 50+ formats), ask questions with page-level citations
  • Real-time agent activity visualization: see the AI's thinking, tool calls, and plan steps as they happen
  • Mobile access via ngrok tunnel with QR code
  • CLI integration: gaia chat --ui launches everything
  • NPM distribution: npm install -g @amd-gaia/agent-ui for standalone use

Features & Capabilities

Chat Interface

  • Streaming responses — token-by-token streaming via Server-Sent Events (SSE) with agent activity events interleaved
  • Agent activity panel — collapsible visualization of thinking steps, tool calls, plan creation, and errors with live spinner during processing
  • Markdown rendering — headers, bold, italic, inline code, fenced code blocks with language labels and copy buttons
  • Conversation history — messages persist in SQLite, restored when switching sessions or reloading
  • Auto-scroll with scroll-to-bottom button when user scrolls up
  • Stop generation — abort mid-stream, partial response saved
  • Auto-title — session title auto-generates from first message (first 50 chars)
  • Session export — download conversation as Markdown file
  • Error detection — assistant error messages (tracebacks, connection failures) get distinct styling with "Something went wrong" banner and actionable fix commands

Document Q&A (RAG)

  • 53+ supported file types: PDF, TXT, MD, CSV, JSON, HTML, XML, YAML, Python, JavaScript, TypeScript, Java, C/C++, Rust, Go, Ruby, Shell scripts, config files, and more
  • Drag-and-drop upload — drop files onto chat view or Document Library modal
  • Path-based indexing — type a file path directly in the Document Library for local files
  • Smart chunking — heuristic-based semantic chunking (500 tokens, 20% overlap) with optional LLM-based intelligent boundary detection
  • Hybrid retrieval — embedding-based FAISS similarity + keyword-based exact phrase matching with deduplication
  • Page-level citations — responses reference specific page numbers from source documents
  • Document deduplication — SHA-256 content hashing prevents re-indexing identical files
  • Per-session attachment — global document library with per-session document binding
  • PDF image extraction — when VLM model (Qwen3-VL-4B) is available, images in PDFs are processed via vision LLM
  • Adaptive retrieval — retrieves 5-25 chunks depending on document size
  • Document context bar — shows indexed document count and filenames below chat header, clickable to manage

Session Management

  • Create/rename/delete sessions via sidebar
  • 2-click delete confirmation with 3-second auto-cancel
  • Search — filter sessions by title (case-insensitive)
  • Relative timestamps — "now", "5m", "2h", "3d", or date format
  • Sidebar resize — drag right edge to resize (200-500px), width persisted
  • Sidebar collapse — collapse to icon-only 56px strip

System Awareness

  • Connection banner — red banner when backend unreachable ("Start it with: gaia chat --ui"), yellow warning when Lemonade not running ("Start it with: lemonade-server serve")
  • Auto-polling — system status checked every 15 seconds
  • Settings modal — shows Lemonade status, loaded model, embedding model, disk space, available memory
  • "Clear All Data" — danger zone button to delete all sessions, messages, and documents with confirmation dialog

Theming & Responsiveness

  • Dark mode default with light mode toggle (persisted in localStorage)
  • Mobile responsive — sidebar becomes slide-out overlay at ≤768px with hamburger menu and tap-to-close overlay
  • Auto-close sidebar on mobile after selecting a session

Mobile Access

  • ngrok tunnel — one-click to expose local server via HTTPS tunnel
  • QR code — scan from phone to access chat on mobile
  • Token authentication — UUID-based token appended to tunnel URL
  • Tunnel password hint — shows public IP for ngrok interstitial page

Welcome Screen

  • Feature cards — Private (data stays on device), Fast (NPU acceleration), Smart (document Q&A), Free (no subscriptions)
  • Suggestion chips — 4 pre-built prompts that auto-create a session and send the message

Architecture

Backend (src/gaia/ui/)

Module Lines Description
server.py 924 FastAPI app factory with 15 REST endpoints, SSE streaming via thread-based producer/consumer, path sanitization, static file serving with SPA fallback
database.py 496 ChatDatabase — thread-safe SQLite with WAL mode, 4 tables (sessions, messages, documents, session_documents), cascade deletes, RLock transactions
models.py 152 14 Pydantic request/response models with validation
sse_handler.py 310 SSEOutputHandler — bridges OutputHandler interface to JSON event queue for SSE delivery. Maps agent thinking, tool calls, plans, errors to typed events
tunnel.py 294 TunnelManager — ngrok process lifecycle, local API polling for tunnel URL, public IP fetching, token generation

API Endpoints (15):

Category Endpoints
System GET /api/health, GET /api/system/status
Sessions GET/POST /api/sessions, GET/PUT/DELETE /api/sessions/{id}, GET /api/sessions/{id}/messages, GET /api/sessions/{id}/export
Chat POST /api/chat/send (streaming SSE or JSON)
Documents GET /api/documents, POST /api/documents/upload-path, DELETE /api/documents/{id}
Attachments POST/DELETE /api/sessions/{id}/documents/{doc_id}
Tunnel POST /api/tunnel/start, POST /api/tunnel/stop, GET /api/tunnel/status

Frontend (src/gaia/apps/webui/)

Component Description
App.tsx Root component — session loading, status polling, tunnel management, mobile detection
ChatView.tsx Main chat interface — message input, streaming, agent activity, drag-and-drop, auto-scroll, stop generation, session export
Sidebar.tsx Session list with search, 2-click delete, drag-to-resize, collapse/expand, theme toggle, mobile access button
MessageBubble.tsx Message display with markdown rendering (headers, bold, italic, code blocks, lists), copy button, error detection styling
AgentActivity.tsx Collapsible agent activity panel — thinking, tool calls, plans, errors. Inline (during streaming) and summary (after completion) variants
DocumentLibrary.tsx Modal — drag-and-drop upload zone, path input form, document list with size/chunks, delete, stats bar
SettingsModal.tsx Modal — system status grid (Lemonade, model, embedding, disk, memory), about section, "Clear All Data" danger zone
MobileAccessModal.tsx Modal — tunnel status, QR code generation, URL copy, tunnel password hint, step-by-step instructions
ConnectionBanner.tsx Top banner — red (backend down) or yellow (Lemonade down) with retry/dismiss actions
WelcomeScreen.tsx Landing page — feature cards, "Start a New Chat" button, suggestion chips
chatStore.ts Zustand store — sessions, messages, streaming state, agent steps, documents, system status, theme, sidebar state (all persisted where appropriate)
api.ts API client — fetch wrapper with logging/timing, SSE stream parser with agent event routing, AbortController support
logger.ts Color-coded console logger with timing, categories (api, chat, stream, doc, system, nav, ui)

Tech Stack: Vite + React 18 + TypeScript + Zustand + Lucide icons + Electron (optional desktop shell)

SSE Streaming Architecture

ChatAgent.process_query()
    ↓ (console method calls)
SSEOutputHandler (implements OutputHandler)
    ↓ (typed JSON events → queue)
_stream_chat_response() async generator
    ↓ (data: {json}\n\n format)
Frontend SSE parser (api.ts)
    ↓ (event routing)
ChatView callbacks → Zustand store → React render

Event types: status, step, thinking, plan, tool_start, tool_end, tool_result, agent_error, chunk, answer, done, error


Security

  • Path traversal prevention — null byte rejection, Path.resolve() canonicalization, extension allowlist (53 types), symlink resolution
  • Static file containment — relative_to() check ensures served files stay within dist/ directory
  • No authentication — designed for single-user localhost; CORS restricted to localhost origins + ngrok pattern
  • SQL parameterization — all database queries use parameterized statements
  • Input validation — Pydantic models with field constraints (e.g., max_length=100_000 on messages)
  • Path prefix attack fix — security.py fix prevents /home/user/project matching /home/user/project-secrets (appends os.sep before prefix comparison)

CLI Integration

gaia chat --ui                    # Launch on default port 4200
gaia chat --ui --ui-port 4300     # Custom port
  • Binds to 0.0.0.0 for local network access
  • Graceful error messages for missing dependencies (fastapi, uvicorn)
  • Ctrl+C to stop

Bug Fixes Across Core Modules

This branch also includes 13+ bug fixes discovered during code review:

Module Fix
security.py Critical: Fix path prefix attack — append os.sep to prevent /project matching /project-secrets
llm/providers/claude.py Add default max_tokens=4096 when caller omits it (Claude API requires this parameter)
agents/base/agent.py Add stop_progress() on error paths to prevent stuck spinner; refactor rebuild_system_prompt() to use _compose_system_prompt()
api/openai_server.py Guard against None content in message preview (prevents TypeError on len(None))
api/app.py Fix f-string in stop_server() — was missing f prefix, printed literal {port}
api/sse_handler.py Add model_id param to print_processing_start(), streaming param to print_final_answer() (OutputHandler interface compat)
audio/kokoro_tts.py Handle empty audio chunks gracefully (return 100ms silence instead of crash); remove duplicate audio_buffer.put(None) in finally block
mcp/blender_mcp_client.py Handle multi-chunk socket responses (loop recv() until connection closes instead of single 64KB read)
eval/email_generator.py Fix division-by-zero when email list is empty
eval/transcript_generator.py Fix division-by-zero when transcript list is empty
agents/code/tools/file_io.py Fix os.makedirs("") crash when dirname is empty; fix GAIA.md created/updated logic (was checking existence after write)

Documentation

New Pages

Page Path Description
User Guide docs/guides/chat-ui.mdx End-user guide: setup, features walkthrough, document Q&A tutorial
SDK Reference docs/sdk/sdks/chat-ui.mdx Developer reference: API endpoints, Pydantic models, SSE event types, database schema
Technical Spec docs/spec/chat-ui-server.mdx Architecture spec: streaming design, security model, deployment
Agent Capabilities Plan docs/spec/chat-ui-agent-capabilities-plan.md Design document for agent integration

Updated Pages

  • docs/quickstart.mdx — added Desktop App section
  • docs/index.mdx — added Get Started + Capabilities cards
  • docs/guides/chat.mdx — cross-reference to Chat UI
  • docs/sdk/sdks/chat.mdx — cross-reference to Chat UI SDK
  • docs/deployment/ui.mdx — added GAIA Chat alongside RAUX
  • docs/setup.mdx — updated install instructions
  • docs/reference/cli.mdx — added --ui and --ui-port flags
  • docs/docs.json — navigation entries for all 3 new pages

Tests

Test File Tests Coverage
tests/unit/chat/ui/test_database.py 42 Session/message/document CRUD, pagination, cascade deletes, deduplication, stats
tests/unit/chat/ui/test_models.py 27 Pydantic model defaults, optional fields, serialization
tests/unit/chat/ui/test_server.py 81 All 15 endpoints, HTTP status codes, path sanitization security tests, CORS config
tests/unit/chat/ui/test_tunnel.py 11 Tunnel lifecycle, token validation, status reporting
tests/integration/test_chat_ui_integration.py ~30 End-to-end session lifecycle, document workflows, concurrent access, Unicode, export
tests/electron/test_electron_chat_app.js ~100 App config, React/Vite structure, API client completeness, type definitions, privacy design
tests/electron/test_electron_chat_installer.js ~50 Package.json, Forge config, NPM metadata, license headers, build structure

Total: 161 unit tests passing + integration + Electron structural tests


Scripts & CI/CD

File Purpose
scripts/build-ui-installer.ps1 Windows installer build (Electron Forge → .exe)
scripts/build-ui-installer.sh Linux installer build (Electron Forge → .deb)
scripts/install-ui.ps1 One-liner Windows install via npm (irm ... | iex)
scripts/install-ui.sh One-liner Linux/macOS install via npm (curl ... | bash)
scripts/bump-ui-version.mjs Sync package.json version from version.py (single source of truth)
scripts/release-ui.mjs One-command release: sync version → commit → tag → push (CI handles npm publish)
.github/workflows/publish-npm-ui.yml CI: build, test, version verification, publish to npm on v* tags (with manual approval gate)

Setup & Packaging

  • Python package: gaia.ui added to setup.py packages
  • Extras group: pip install amd-gaia[ui] installs fastapi, uvicorn, httpx, psutil
  • NPM package: @amd-gaia/agent-ui with gaia-ui CLI entry point
  • Electron: Forge config for .exe (Windows Squirrel) and .deb (Linux) installers

Key Design Decisions

Decision Rationale
SQLite with WAL Zero-config persistence, shared between CLI and desktop app, WAL mode for concurrent read/write
SSE (not WebSocket) Simpler protocol, works through proxies, sufficient for server→client streaming
Thread-based producer/consumer Agent runs synchronously in thread, SSE handler queues events, async generator yields to client
Global document library + per-session attachment Users build a library once, attach subsets to different conversations
No authentication Single-user local app — CORS restricted to localhost + ngrok origins
Zustand (not Redux) Minimal boilerplate, direct state access, built-in localStorage persistence pattern
Path sanitization over chroot Resolve + extension allowlist + null byte rejection is sufficient for local file access

Test plan

See detailed manual test plans in PR comments:

Quick smoke test:

# Terminal 1
lemonade-server serve

# Terminal 2
cd src/gaia/apps/webui && npm install && npm run build && cd -
gaia chat --ui

# Browser: http://localhost:4200
# 1. Click "Start a New Chat"
# 2. Send a message → verify streaming response with agent activity
# 3. Open Document Library → drag-and-drop a PDF → ask a question about it
# 4. Open Settings → verify system status shows Lemonade running

🤖 Generated with Claude Code

New feature: lightweight desktop chat application with FastAPI backend,
SQLite persistence, SSE streaming, and RAG-powered document Q&A — all
running 100% locally on AMD Ryzen AI hardware.

**Backend (Python):**
- FastAPI server (`gaia.chat.ui.server`) on port 4200
- SQLite database with WAL mode (`gaia.chat.ui.database`)
- 14 Pydantic request/response models (`gaia.chat.ui.models`)
- REST API: sessions CRUD, streaming chat (SSE), document library
- Thread-based producer/consumer pattern for real-time streaming
- Document deduplication via SHA-256 hash
- Shared CLI/UI state via common SQLite database

**Frontend (TypeScript/React):**
- Vite + React + TypeScript web UI
- Sidebar with session management, document library modal
- Markdown rendering with syntax-highlighted code blocks
- Privacy indicators ("100% Local", "Your data never leaves this device")
- Responsive design with light/dark theme support
- Electron shell for desktop packaging

**CLI integration:**
- `gaia chat --ui` launches the Chat Web UI server
- `gaia chat --ui-port 8080` for custom port

**Documentation (3 new pages):**
- User guide: `docs/guides/chat-ui.mdx`
- SDK reference: `docs/sdk/sdks/chat-ui.mdx`
- Technical spec: `docs/spec/chat-ui-server.mdx`
- Updated quickstart with Desktop App section
- Updated index, chat guide, chat SDK, deployment, setup pages
- Added navigation entries in `docs/docs.json`

**Tests:**
- Unit tests for database, models, and server
- Electron app and installer tests

**Scripts & CI:**
- Build scripts for Windows/Linux installers
- NPM publish workflow for chat package
- Version bump and release scripts

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions github-actions Bot added documentation Documentation changes devops DevOps/infrastructure changes chat Chat SDK changes cli CLI changes tests Test changes electron Electron app changes labels Mar 5, 2026
Comment thread src/gaia/chat/ui/server.py Fixed
Comment thread src/gaia/chat/ui/server.py Fixed
Comment thread src/gaia/chat/ui/server.py Fixed
Comment thread src/gaia/chat/ui/server.py Fixed
Comment thread src/gaia/chat/ui/server.py Fixed
Comment thread src/gaia/ui/server.py Fixed
Comment thread src/gaia/ui/server.py Fixed
kovtcharov and others added 4 commits March 5, 2026 16:07
…nstaller improvements

- Add npm publishability: scoped @amd/gaia-chat package with bin/gaia-chat.mjs CLI entry
- Sync all versions from src/gaia/version.py (single source of truth)
- Inject version into UI at build time via Vite define (Sidebar + Settings)
- Create forge.config.cjs for SemVer conversion (4-part -> 3-part for Squirrel)
- Add self-contained main.js Electron entry (no external framework dependency)
- Lowercase installer filename: gaia-chat-setup.exe
- Update CI workflows to verify version.py and build for Windows + Linux
- Add npm publish workflow triggered by chat-v* tags
- Update release/bump scripts to read from version.py
- Update Jest tests to support external forge config and version.py checks

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add restrictive default permissions (contents: read) to publish workflow
- Fix path traversal vulnerability in gaia-chat CLI static file server
  by resolving paths and validating they stay within dist directory

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Resolve and validate file paths in document upload endpoint
- Prevent path traversal in SPA static file serving
- Remove internal error details from user-facing error messages
- Add exc_info logging for better server-side debugging

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add _validate_file_path() with null byte, absolute path, and file extension checks
- Allowlist document/code extensions to prevent unsafe file type uploads
- Add TestValidateFilePath test class with 10 security validation tests
- Add integration test verifying upload endpoint rejects unsafe extensions

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions github-actions Bot added the dependencies Dependency updates label Mar 6, 2026
Comment thread src/gaia/chat/ui/server.py Fixed
Comment thread src/gaia/chat/ui/server.py Fixed
Comment thread src/gaia/chat/ui/server.py Fixed
Comment thread src/gaia/chat/ui/server.py Fixed
kovtcharov and others added 2 commits March 5, 2026 16:17
The release management section incorrectly stated the version was
managed via `version.txt`. The actual scripts read from
`src/gaia/version.py` (GAIA's single source of truth).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ations

- Add _sanitize_document_path() that returns a clean Path, isolating
  user input from all downstream filesystem calls
- Add _sanitize_static_path() with relative_to() containment check
  to prevent directory traversal in SPA file serving
- Reject ".." patterns and null bytes before path construction
- Add TestSanitizeDocumentPath and TestSanitizeStaticPath test classes

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/gaia/ui/server.py Fixed
Comment thread src/gaia/ui/server.py Fixed
Comment thread src/gaia/ui/server.py Fixed
Comment thread src/gaia/ui/server.py Fixed
Comment thread src/gaia/ui/server.py Fixed
Comment thread src/gaia/ui/server.py Fixed
Comment thread src/gaia/ui/server.py Fixed
@kovtcharov kovtcharov self-assigned this Mar 6, 2026
kovtcharov and others added 5 commits March 5, 2026 16:24
- Move path validation into safeLookup() function that rejects
  traversal patterns, null bytes, and non-alphanumeric characters
  before constructing any filesystem paths
- Return safe fallback (index.html) for all invalid paths
- Ensures readFile() only receives paths validated by safeLookup()

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Fix technology description: Vanilla JS -> React + TypeScript (deployment/ui)
- Fix supported file formats to match _ALLOWED_EXTENSIONS allowlist (guides/chat-ui)
- Fix npm package names: @amd/gaia-chat -> @amd-gaia/chat, @gaia/electron -> @amd-gaia/electron
- Add --ui and --ui-port flags to CLI reference with examples (reference/cli)
- Add security helpers to spec function table and update security section
  with accurate host binding info and path validation details (spec/chat-ui-server)
- Enhance quickstart: rename to "Chat UI (Fastest)", add npm one-liner tab,
  update description to emphasize chat-first experience (quickstart)
- Update anchor links in index.mdx and setup.mdx to match new heading
- Add Chat UI to CLAUDE.md project structure, architecture, CLI commands,
  and documentation index

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ements

- Default to dark mode for new users
- Replace generic Bot icon with GAIA robot head mascot (circle)
- Add stop streaming button (replaces send button during generation)
- Add copy-to-clipboard button on all messages (hover to reveal)
- Add scroll-to-bottom FAB when scrolled up in long conversations
- Improve dark mode contrast (sharper bg separation, brighter text)
- Better message visual distinction (user vs assistant backgrounds)
- Fix trash icon overlapping timestamps in sidebar session list
- Rename npm package @amd/gaia-chat to @amd-gaia/chat across all files
- Rename Electron main.js to main.cjs for CommonJS compatibility

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add GAIA robot head favicon for browser tab
- Redesign input box: rounded pill shape, elevated background, softer focus
- Add lock icon to privacy footer
- Feature cards now have background fill for dark mode visibility
- Increase dark mode border contrast for sidebar/content divider
- Fix mobile sidebar defaulting to open on small screens

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ve integration tests

- Add AgentActivity component for real-time tool/shell execution display
- Add structured frontend logging utility (logger.ts)
- Add SSE handler module for server-side streaming with agent events
- Enhance ChatView, Sidebar, and settings with agent activity support
- Expand chatStore with agent activity state management
- Add API service logging, timing, and stream event types
- Enhance ChatAgent with shell tool support and streaming capabilities
- Add 66 integration tests covering full API lifecycle, document workflows,
  SSE streaming, security, pagination, error paths, unicode, and CORS
- Fix Electron test assertions for refactored store and API patterns
- Add chat-ui-agent-capabilities-plan spec document

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions github-actions Bot added the agents label Mar 6, 2026
kovtcharov and others added 3 commits March 6, 2026 11:44
- Remove unused imports: datetime, Any (models.py), UploadFile, File
  (server.py), json, AsyncMock (test_server.py), pytest (test_models.py),
  argparse, server_main (test_chat_ui_integration.py)
- Fix f-string without interpolation in cli.py
- Add pylint disable comments for false-positive no-member (RAGSDK) and
  interface-required unused-argument (sse_handler)
- Apply black/isort formatting to all chat UI source and test files
- Fix Electron test: delete confirmation text changed to "Delete?"
- All 216 Python tests and 252 Jest tests pass, lint clean

Co-Authored-By: Claude Opus 4.6 <[email protected]>
kovtcharov and others added 10 commits March 16, 2026 09:23
- Skip same-repo GitHub blob/tree links in doc link checker (404 during
  PRs before merge, valid after)
- Treat HTTP 5xx errors as warnings instead of broken links (server
  errors are transient, not our broken links)
- Add global exception handler to prevent stack trace exposure to
  external users (CodeQL py/stack-trace-exposure)
- Inline path sanitization in serve_spa for CodeQL visibility
  (py/path-injection) - explicit null byte, traversal, and directory
  containment checks
- Use exc parameter in global exception handler (pylint W0613)
- Bump webui package.json/package-lock.json from 0.16.0 to 0.16.1
  to match version.py (fixes Electron installer version test)
- Fix prompt dispatch race condition: store pendingPrompt in Zustand
  instead of fragile setTimeout + CustomEvent pattern
- Memoize cleanToolCallContent with useMemo to avoid re-parsing on
  every render
- Neutralize reddish message backgrounds in dark mode (tints, user-msg,
  assistant-msg now use neutral white-based tones)
- Assistant messages use AMD red left border to match sidebar branding
- Timestamps always visible at 40% opacity (was hover-only)
- Remove non-clickable feature card hover transform
- Differentiate border-radius design tokens (was all 3-4px)
- Reactive isMobile detection via resize listener
- Remove redundant doc/file buttons from sidebar (kept in chat header)
- Replace window.confirm() with two-click pattern in Settings
- Add clipboard execCommand fallback for localhost (non-HTTPS)
- Add undo toast for session deletion with 5s grace period
- Streaming cursor follows inline with text via CSS :has() selector
- Handle invalid JSON in LLM answer blocks with manual extraction
- Bump version to 0.17.0

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Refactor MessageBubble code/pre handling: fenced blocks detected
  via pre>code wrapper instead of heuristic newline check, fixing
  false positives where inline code containing newlines rendered
  as CodeBlock
- Improve SSE tool result summarizer: handle file_name and file_path
  keys, guard against empty name/directory combinations

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Add robust stripOuterCodeFences() that handles: closed fences
  (```lang\n...\n```), unclosed opening fences, trailing fences,
  and nested wrapping (up to 3 levels)
- Run fence stripping AFTER JSON extraction so fences inside
  {"answer": "```..```"} blocks are also caught
- Use greedy inner match to avoid stopping at embedded ``` in content
- Move fenced code block detection from `code` to `pre` component
  override — react-markdown wraps fenced blocks in <pre><code>,
  so inline backtick content no longer triggers CodeBlock rendering

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…endering fixes (#561)

## Summary

- **Architectural fixes**: Improved `Agent`, `ChatAgent`, and `AgentSDK`
with better LLM backend handling
- **LLM backend**: Added `LemonadeManager` for robust model loading
lifecycle management; fixes to `LemonadeClient` and `lemonade` provider
- **Chat UI backend**: Refactored `chat.py` router, fixed SSE handler,
session management improvements, and database schema updates
- **Frontend**: Fixed code block rendering in `MessageBubble.tsx` and
improved file list tool summaries
- **Tests**: Updated unit tests for SSE handler, LLM, and Lemonade model
loading

## Test plan

- [ ] Run `python -m pytest tests/unit/` — all unit tests pass
- [ ] Verify `gaia chat --ui` launches and renders code blocks correctly
- [ ] Confirm LLM model loading works end-to-end via `LemonadeManager`
- [ ] Check SSE streaming in Agent UI produces correct tool summary
output

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
…delete

- File search: add two-phase strategy with quick search first, deep search only on user request
- MessageBubble: replace stripOuterCodeFences with stripBogusCodeFences that preserves real code blocks
- Sidebar: delete sessions from backend immediately instead of deferring, add pendingDeleteIds filter to prevent poll resurrection
- SSE handler: extract answer text from {"answer": "..."} JSON instead of discarding it
- Add file search spec updates and integration test for files router

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
#563)

… for LLM content

## Changes

<!-- Briefly describe your changes in bulleted form -->
-
-
-
- Apply Black formatting to file_tools.py and sse_handler.py
- Update SSE test to match answer extraction behavior (emits answer event)
- Handle WinError 4551 in test_llm.py when Application Control blocks subprocess

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Update Electron test to check onSendPrompt prop (gaia:send-prompt moved to FileBrowser)
- Update sidebar ARIA test: Document Library button replaced with Search tasks
- Remove broken milestone/15 link from agent-ui plan doc

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@kovtcharov

Copy link
Copy Markdown
Contributor Author

@claude please review this PR and make sure we haven't broken any existing functionality or documentation.

@github-actions

github-actions Bot commented Mar 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @kovtcharov's task —— View job


PR Review: GAIA Chat UI

Overall Assessment: ✅ LGTM

This PR adds a comprehensive privacy-first desktop chat application without breaking existing functionality. Below is my detailed review:


Breaking Changes Analysis

🟢 No Breaking Changes Detected

  1. ChatSDK → AgentSDK Rename: The SDK was renamed from ChatSDK/ChatConfig to AgentSDK/AgentConfig, but backwards-compatible aliases are provided in src/gaia/chat/sdk.py:1254-1258:

    ChatSDK = AgentSDK
    ChatConfig = AgentConfig
    ChatResponse = AgentResponse
    ChatSession = AgentSession

    Existing code using ChatSDK will continue to work.

  2. Module Exports: The src/gaia/chat/__init__.py exports both old and new names, maintaining backwards compatibility.

  3. Documentation Updates: All documentation has been updated to use the new AgentSDK/AgentConfig naming, with proper cross-references.


Security Review

🟢 Security Fixes Applied

  1. Path prefix attack fix (src/gaia/security.py:134-143): The critical security fix preventing /home/user/project from matching /home/user/project-secrets is correctly implemented by appending os.sep before prefix comparison.

  2. Information exposure fixes (per PR comments): Generic error messages are now returned instead of stack traces in the UI routers.

  3. Tunnel authentication (src/gaia/ui/server.py:77-122): Proper Bearer token validation for remote requests through ngrok tunnel.

  4. Path sanitization (src/gaia/ui/utils.py): Document paths are sanitized with null byte rejection, extension allowlists, and symlink resolution.


Documentation Consistency

🟢 Documentation is Consistent

  1. New pages added to docs/docs.json:

    • guides/agent-ui - User guide
    • sdk/sdks/agent-ui - SDK reference
    • spec/agent-ui-server - Technical spec
  2. Cross-references updated in:

    • docs/quickstart.mdx - Desktop App section added
    • docs/guides/chat.mdx - Cross-reference to Chat UI
    • docs/reference/cli.mdx - --ui and --ui-port flags documented
  3. No broken links detected - All documentation references checked.


Code Quality

🟢 Well-Structured Architecture

Component Quality Notes
src/gaia/ui/server.py ✅ Good Clean app factory pattern, proper middleware ordering
src/gaia/ui/database.py ✅ Good Thread-safe SQLite with WAL mode, proper transactions
src/gaia/ui/routers/ ✅ Good Modular router structure, clean separation
src/gaia/ui/sse_handler.py ✅ Good Clean OutputHandler → SSE bridge
Frontend (apps/webui/) ✅ Good React/TypeScript/Vite with Zustand state management

Test Coverage

The PR includes comprehensive test coverage:

  • 161+ unit tests for database, models, server, tunnel
  • Integration tests for chat UI workflows
  • Electron structural tests for app configuration

Minor Observations (Non-blocking)

  1. 🟡 CORS hardcoded ports (src/gaia/ui/server.py:176-183): Consider making this configurable via environment variable.

  2. 🟡 TunnelManager instantiation (src/gaia/ui/server.py:200): Created at app startup even when tunnel is never used - minor resource overhead.


Conclusion

✅ Ready for merge. The PR:

  • Adds extensive new functionality without breaking existing code
  • Maintains backwards compatibility with the ChatSDK → AgentSDK rename
  • Addresses all 46 CodeQL security alerts
  • Includes comprehensive documentation and tests
  • Follows established patterns in the codebase

Note: I was unable to run linting and unit tests directly due to bash command restrictions. The PR author reports 362/362 unit tests passing and Black formatting clean.

kovtcharov and others added 4 commits March 17, 2026 19:21
- Rewrite agent-ui.mdx: remove redundant Get Started section (lives in
  quickstart), add "Search and Browse Files" + "Analyze Documents"
  capabilities, replace ASCII architecture with Mermaid diagram
- Update quickstart.mdx: task-focused intro (not "chatting"), simplify
  npm tab to published package, add auto-bootstrap note, remove
  redundant CLI tab and Desktop Installer content
- Move guides/agent-ui from Getting Started to Python Framework in
  docs.json navigation
- Add auto-bootstrap to gaia-ui.mjs: when Python backend not found,
  automatically runs install scripts (install.ps1/install.sh) to set
  up uv + Python 3.12 + amd-gaia into ~/.gaia/venv
- Add "gaia" bin entry to package.json alongside "gaia-ui"
- Guard against infinite spawn loop when npm "gaia" shadows Python CLI
- Update sdk/sdks/agent-ui.mdx: fix naming (Agent UI not GAIA Chat,
  Agent SDK not Chat SDK), update npm section to show gaia command
- Remove "Generative AI Is Awesome" from sdk/index.mdx
… GAIA personality

CLI:
- Add --ui, --cli, --ui-port top-level flags to gaia command
- Bare `gaia` defaults to launching Agent UI
- Interactive menu with [1] Agent UI [2] CLI [3] Help
- Extract _launch_agent_ui(), _launch_interactive_cli() helpers
- gaia chat --ui preserved as backward-compatible alias

npm package (gaia-ui):
- Auto-install Python backend on first run (uv + Python 3.12 + amd-gaia[ui])
- Pin Python package version to match npm package version
- Auto-update backend on version mismatch
- Run gaia init --profile minimal after first install
- --gaia-version flag for installing specific versions
- Clear error messages with manual install instructions at every step
- Remove "gaia" bin alias to avoid conflict with Python CLI

Agent personality:
- Rewrite ChatAgent system prompt for natural, direct personality
- GAIA speaks like a smart friend, not a corporate assistant
- Pushes back on wrong claims, avoids sycophancy
- No filler phrases, no "As an AI assistant" self-references

Documentation:
- Promote Agent UI to top-level under Python Framework in docs.json
- Rewrite guides/agent-ui.mdx as concise getting started page
- Update quickstart with npm install, update, uninstall, Node.js install instructions
- Add Top-Level Flags section to CLI reference
- Update deployment/ui.mdx with coming-soon warning for desktop installer
- Fix GaiaAgent -> ChatAgent in SDK docs
- Update index.mdx cards for Agent UI

Tests:
- Add chat concurrency, chat helpers, and utils helpers unit tests
- Update database tests

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@kovtcharov
kovtcharov added this pull request to the merge queue Mar 18, 2026
Merged via the queue into main with commit b2ace80 Mar 18, 2026
59 of 60 checks passed
@kovtcharov
kovtcharov deleted the kalin/chat-ui branch March 18, 2026 17:43
@itomek itomek mentioned this pull request Mar 27, 2026
4 tasks
github-merge-queue Bot pushed a commit that referenced this pull request Mar 27, 2026
## Summary

Release v0.17.0 — **GAIA Agent UI**, eval benchmark framework, tool
execution guardrails, system prompt optimization, and security
hardening.

### Files Changed
- **`docs/releases/v0.17.0.mdx`** — Comprehensive release notes (new
file)
- **`docs/docs.json`** — Added `releases/v0.17.0` to Releases tab,
updated navbar to `v0.17.0 · Lemonade 10.0.0`
- **`src/gaia/version.py`** — Already at `0.17.0` on main (no change
needed)

### Release Highlights

**New Features:**
- **GAIA Agent UI** — Full-stack privacy-first desktop chat with
streaming responses, 53+ format document Q&A, ngrok tunnel for mobile,
page-level citations, session management (PR #428)
- **Agent UI Eval Framework** — `gaia eval agent` command with
7-dimension weighted scoring across 34 scenarios, redesigned Settings
modal, `<think>` block display, performance stats (PR #607)
- **Tool Execution Guardrails** — Blocking confirmation popup
(Allow/Deny/Always Allow) before write/shell tools, 60s timeout (PR
#565, #604)
- **Device Support Detection** — AMD Ryzen AI Max + Radeon ≥24GB
detection, `--base-url` remote bypass, `GAIA_SKIP_DEVICE_CHECK` override
(PR #593)
- **Terminal UI Design** — Typewriter welcome page, pixelated AMD
cursor, glassmorphism, `prefers-reduced-motion` support (PR #568)

**Performance:**
- **78% System Prompt Reduction** — 17,600 → 3,853 tokens via two-tier
RAG gating, 600s chat timeout, MCP runtime status display (PR #617)

**Security:**
- **TOCTOU Race Condition** — Atomic `O_NOFOLLOW` + `fstat` fix in
document upload, per-file `asyncio.Lock` (PR #564)

**Bug Fixes:**
- LRU eviction silent failure + new
`--max-indexed-files`/`--max-total-chunks` CLI flags (PR #567)
- Lemonade v10 device key renames: `npu` → `amd_npu`, `gpu` →
`amd_igpu`/`amd_dgpu` (PR #548)
- Agent UI rendering, Windows paths, JSON safety regex, RAG indexing
guards (PR #566, #604, #605)
- Restored accidentally reverted changes from PRs #564, #565, #568 (PR
#608)

### Post-Merge
After merging, tag and push:
```bash
git checkout main && git pull
git tag v0.17.0 && git push origin v0.17.0
```
CI runs `validate-release` → `publish-release`. PyPI gated on Kalin
approval.

## Test plan
- [ ] `docs.json` is valid JSON and renders on Mintlify
- [ ] `validate_release_notes.py` passes for v0.17.0
- [ ] `version.py` reads `0.17.0`
- [ ] Release notes content matches actual PR changes
huong8373tt-beep pushed a commit to huong8373tt-beep/gaia that referenced this pull request Nov 9, 2026
…#7026)

The PR-review workflow checks out fork code while holding the Anthropic
credential and a write-scoped token. It stays safe only because no step
runs that code unless the PR comes from this repo, and until now a code
comment was the only thing enforcing that. A unit test now fails CI if
any step after a checkout installs, builds or runs the checked-out tree
without requiring both `pull_request_target` and a same-repo head. It
also fails on any action not on an explicit allowlist, on any other
workflow that opts into unsafe PR checkout, and on any caller that asks
for the evidence stage outside `pull_request_target`. The evidence stage
is designed for pull_request_target only. Its gate now says so
explicitly, and its only caller already runs on that event, so behaviour
is unchanged.

## Test plan

- [x] `python -m pytest tests/unit/test_claude_run_fork_gate.py
tests/unit/test_evidence_harness_failure_signal.py` passes
- [x] The live workflow passes the guard; dropping the event check from
`Detect testable surface` fails it
- [x] Each of these, injected into a copy of the live workflow, fails
the guard: `if npm test; then`, `while pytest; do`, `! npm ci`, `{ npm
ci; }`, `cmd & npm ci`, `eval "$(cat x)"`, `"$GITHUB_WORKSPACE/x.sh"`,
`${{ github.workspace }}/x.sh`, `python3.12`, `pre-commit`, `docker
build`, an unlisted remote action, a local action
- [x] Parametrized cases cover the `||`/negation bypasses, a fork-only
or event-only gate, `gh pr checkout` as a checkout, and safe shapes that
must not be flagged
- [ ] `actionlint` clean in CI

## Remaining on amd#2948

- Dismiss code-scanning alert amd#428 as a false positive, citing this test
- Re-verify the `execution_file` output name on the next
`claude-code-action` bump

Refs amd#2948
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

audio Audio (ASR/TTS) changes chat Chat SDK changes cli CLI changes dependencies Dependency updates devops DevOps/infrastructure changes documentation Documentation changes electron Electron app changes eval Evaluation framework changes llm LLM backend changes mcp MCP integration changes performance Performance-critical changes rag RAG system changes security Security-sensitive changes talk Talk agent changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants